passagemath-symbolics 10.6.40__cp314-cp314t-macosx_13_0_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of passagemath-symbolics might be problematic. Click here for more details.

Files changed (172) hide show
  1. passagemath_symbolics/.dylibs/libgmp.10.dylib +0 -0
  2. passagemath_symbolics/__init__.py +3 -0
  3. passagemath_symbolics-10.6.40.dist-info/METADATA +187 -0
  4. passagemath_symbolics-10.6.40.dist-info/RECORD +172 -0
  5. passagemath_symbolics-10.6.40.dist-info/WHEEL +6 -0
  6. passagemath_symbolics-10.6.40.dist-info/top_level.txt +3 -0
  7. sage/all__sagemath_symbolics.py +17 -0
  8. sage/calculus/all.py +14 -0
  9. sage/calculus/calculus.py +2826 -0
  10. sage/calculus/desolvers.py +1866 -0
  11. sage/calculus/predefined.py +51 -0
  12. sage/calculus/tests.py +225 -0
  13. sage/calculus/var.cpython-314t-darwin.so +0 -0
  14. sage/calculus/var.pyx +401 -0
  15. sage/dynamics/all__sagemath_symbolics.py +6 -0
  16. sage/dynamics/complex_dynamics/all.py +5 -0
  17. sage/dynamics/complex_dynamics/mandel_julia.py +765 -0
  18. sage/dynamics/complex_dynamics/mandel_julia_helper.cpython-314t-darwin.so +0 -0
  19. sage/dynamics/complex_dynamics/mandel_julia_helper.pyx +1035 -0
  20. sage/ext/all__sagemath_symbolics.py +1 -0
  21. sage/ext_data/kenzo/CP2.txt +45 -0
  22. sage/ext_data/kenzo/CP3.txt +349 -0
  23. sage/ext_data/kenzo/CP4.txt +4774 -0
  24. sage/ext_data/kenzo/README.txt +49 -0
  25. sage/ext_data/kenzo/S4.txt +20 -0
  26. sage/ext_data/magma/latex/latex.m +1021 -0
  27. sage/ext_data/magma/latex/latex.spec +1 -0
  28. sage/ext_data/magma/sage/basic.m +356 -0
  29. sage/ext_data/magma/sage/sage.spec +1 -0
  30. sage/ext_data/magma/spec +9 -0
  31. sage/geometry/all__sagemath_symbolics.py +8 -0
  32. sage/geometry/hyperbolic_space/all.py +5 -0
  33. sage/geometry/hyperbolic_space/hyperbolic_coercion.py +743 -0
  34. sage/geometry/hyperbolic_space/hyperbolic_constants.py +5 -0
  35. sage/geometry/hyperbolic_space/hyperbolic_geodesic.py +2409 -0
  36. sage/geometry/hyperbolic_space/hyperbolic_interface.py +206 -0
  37. sage/geometry/hyperbolic_space/hyperbolic_isometry.py +1082 -0
  38. sage/geometry/hyperbolic_space/hyperbolic_model.py +1502 -0
  39. sage/geometry/hyperbolic_space/hyperbolic_point.py +621 -0
  40. sage/geometry/riemannian_manifolds/all.py +7 -0
  41. sage/geometry/riemannian_manifolds/parametrized_surface3d.py +1632 -0
  42. sage/geometry/riemannian_manifolds/surface3d_generators.py +461 -0
  43. sage/interfaces/all__sagemath_symbolics.py +1 -0
  44. sage/interfaces/magma.py +3017 -0
  45. sage/interfaces/magma_free.py +92 -0
  46. sage/interfaces/maple.py +1397 -0
  47. sage/interfaces/mathematica.py +1345 -0
  48. sage/interfaces/mathics.py +1312 -0
  49. sage/interfaces/sympy.py +1398 -0
  50. sage/interfaces/sympy_wrapper.py +197 -0
  51. sage/interfaces/tides.py +938 -0
  52. sage/libs/all__sagemath_symbolics.py +6 -0
  53. sage/manifolds/all.py +7 -0
  54. sage/manifolds/calculus_method.py +555 -0
  55. sage/manifolds/catalog.py +437 -0
  56. sage/manifolds/chart.py +4019 -0
  57. sage/manifolds/chart_func.py +3419 -0
  58. sage/manifolds/continuous_map.py +2183 -0
  59. sage/manifolds/continuous_map_image.py +155 -0
  60. sage/manifolds/differentiable/affine_connection.py +2475 -0
  61. sage/manifolds/differentiable/all.py +1 -0
  62. sage/manifolds/differentiable/automorphismfield.py +1383 -0
  63. sage/manifolds/differentiable/automorphismfield_group.py +604 -0
  64. sage/manifolds/differentiable/bundle_connection.py +1445 -0
  65. sage/manifolds/differentiable/characteristic_cohomology_class.py +1840 -0
  66. sage/manifolds/differentiable/chart.py +1241 -0
  67. sage/manifolds/differentiable/curve.py +1028 -0
  68. sage/manifolds/differentiable/de_rham_cohomology.py +541 -0
  69. sage/manifolds/differentiable/degenerate.py +559 -0
  70. sage/manifolds/differentiable/degenerate_submanifold.py +1671 -0
  71. sage/manifolds/differentiable/diff_form.py +1658 -0
  72. sage/manifolds/differentiable/diff_form_module.py +1062 -0
  73. sage/manifolds/differentiable/diff_map.py +1315 -0
  74. sage/manifolds/differentiable/differentiable_submanifold.py +291 -0
  75. sage/manifolds/differentiable/examples/all.py +1 -0
  76. sage/manifolds/differentiable/examples/euclidean.py +2517 -0
  77. sage/manifolds/differentiable/examples/real_line.py +897 -0
  78. sage/manifolds/differentiable/examples/sphere.py +1186 -0
  79. sage/manifolds/differentiable/examples/symplectic_space.py +187 -0
  80. sage/manifolds/differentiable/examples/symplectic_space_test.py +40 -0
  81. sage/manifolds/differentiable/integrated_curve.py +4035 -0
  82. sage/manifolds/differentiable/levi_civita_connection.py +841 -0
  83. sage/manifolds/differentiable/manifold.py +4254 -0
  84. sage/manifolds/differentiable/manifold_homset.py +1826 -0
  85. sage/manifolds/differentiable/metric.py +3032 -0
  86. sage/manifolds/differentiable/mixed_form.py +1507 -0
  87. sage/manifolds/differentiable/mixed_form_algebra.py +559 -0
  88. sage/manifolds/differentiable/multivector_module.py +800 -0
  89. sage/manifolds/differentiable/multivectorfield.py +1520 -0
  90. sage/manifolds/differentiable/poisson_tensor.py +268 -0
  91. sage/manifolds/differentiable/pseudo_riemannian.py +755 -0
  92. sage/manifolds/differentiable/pseudo_riemannian_submanifold.py +1839 -0
  93. sage/manifolds/differentiable/scalarfield.py +1343 -0
  94. sage/manifolds/differentiable/scalarfield_algebra.py +472 -0
  95. sage/manifolds/differentiable/symplectic_form.py +910 -0
  96. sage/manifolds/differentiable/symplectic_form_test.py +220 -0
  97. sage/manifolds/differentiable/tangent_space.py +412 -0
  98. sage/manifolds/differentiable/tangent_vector.py +616 -0
  99. sage/manifolds/differentiable/tensorfield.py +4665 -0
  100. sage/manifolds/differentiable/tensorfield_module.py +963 -0
  101. sage/manifolds/differentiable/tensorfield_paral.py +2450 -0
  102. sage/manifolds/differentiable/tensorfield_paral_test.py +16 -0
  103. sage/manifolds/differentiable/vector_bundle.py +1728 -0
  104. sage/manifolds/differentiable/vectorfield.py +1717 -0
  105. sage/manifolds/differentiable/vectorfield_module.py +2445 -0
  106. sage/manifolds/differentiable/vectorframe.py +1832 -0
  107. sage/manifolds/family.py +270 -0
  108. sage/manifolds/local_frame.py +1490 -0
  109. sage/manifolds/manifold.py +3090 -0
  110. sage/manifolds/manifold_homset.py +452 -0
  111. sage/manifolds/operators.py +359 -0
  112. sage/manifolds/point.py +994 -0
  113. sage/manifolds/scalarfield.py +3718 -0
  114. sage/manifolds/scalarfield_algebra.py +629 -0
  115. sage/manifolds/section.py +3111 -0
  116. sage/manifolds/section_module.py +831 -0
  117. sage/manifolds/structure.py +229 -0
  118. sage/manifolds/subset.py +2764 -0
  119. sage/manifolds/subsets/all.py +1 -0
  120. sage/manifolds/subsets/closure.py +131 -0
  121. sage/manifolds/subsets/pullback.py +885 -0
  122. sage/manifolds/topological_submanifold.py +891 -0
  123. sage/manifolds/trivialization.py +733 -0
  124. sage/manifolds/utilities.py +1348 -0
  125. sage/manifolds/vector_bundle.py +1342 -0
  126. sage/manifolds/vector_bundle_fiber.py +332 -0
  127. sage/manifolds/vector_bundle_fiber_element.py +111 -0
  128. sage/matrix/all__sagemath_symbolics.py +1 -0
  129. sage/matrix/matrix_symbolic_dense.cpython-314t-darwin.so +0 -0
  130. sage/matrix/matrix_symbolic_dense.pxd +6 -0
  131. sage/matrix/matrix_symbolic_dense.pyx +1022 -0
  132. sage/matrix/matrix_symbolic_sparse.cpython-314t-darwin.so +0 -0
  133. sage/matrix/matrix_symbolic_sparse.pxd +6 -0
  134. sage/matrix/matrix_symbolic_sparse.pyx +1029 -0
  135. sage/modules/all__sagemath_symbolics.py +1 -0
  136. sage/modules/vector_callable_symbolic_dense.py +105 -0
  137. sage/modules/vector_symbolic_dense.py +116 -0
  138. sage/modules/vector_symbolic_sparse.py +118 -0
  139. sage/rings/all__sagemath_symbolics.py +4 -0
  140. sage/rings/asymptotic/all.py +6 -0
  141. sage/rings/asymptotic/asymptotic_expansion_generators.py +1485 -0
  142. sage/rings/asymptotic/asymptotic_ring.py +4858 -0
  143. sage/rings/asymptotic/asymptotics_multivariate_generating_functions.py +4153 -0
  144. sage/rings/asymptotic/growth_group.py +5373 -0
  145. sage/rings/asymptotic/growth_group_cartesian.py +1400 -0
  146. sage/rings/asymptotic/term_monoid.py +5237 -0
  147. sage/rings/function_field/all__sagemath_symbolics.py +2 -0
  148. sage/rings/polynomial/all__sagemath_symbolics.py +1 -0
  149. sage/symbolic/all.py +15 -0
  150. sage/symbolic/assumptions.py +985 -0
  151. sage/symbolic/benchmark.py +93 -0
  152. sage/symbolic/callable.py +459 -0
  153. sage/symbolic/complexity_measures.py +35 -0
  154. sage/symbolic/constants.py +1287 -0
  155. sage/symbolic/expression_conversion_algebraic.py +310 -0
  156. sage/symbolic/expression_conversion_sympy.py +317 -0
  157. sage/symbolic/expression_conversions.py +1713 -0
  158. sage/symbolic/function_factory.py +355 -0
  159. sage/symbolic/integration/all.py +1 -0
  160. sage/symbolic/integration/external.py +270 -0
  161. sage/symbolic/integration/integral.py +1115 -0
  162. sage/symbolic/maxima_wrapper.py +162 -0
  163. sage/symbolic/operators.py +267 -0
  164. sage/symbolic/random_tests.py +462 -0
  165. sage/symbolic/relation.py +1907 -0
  166. sage/symbolic/ring.cpython-314t-darwin.so +0 -0
  167. sage/symbolic/ring.pxd +5 -0
  168. sage/symbolic/ring.pyx +1396 -0
  169. sage/symbolic/subring.py +1025 -0
  170. sage/symbolic/symengine.py +19 -0
  171. sage/symbolic/tests.py +40 -0
  172. sage/symbolic/units.py +1470 -0
@@ -0,0 +1,2826 @@
1
+ # sage_setup: distribution = sagemath-symbolics
2
+ r"""
3
+ Symbolic Computation
4
+
5
+ AUTHORS:
6
+
7
+ - Bobby Moretti and William Stein (2006-2007)
8
+
9
+ - Robert Bradshaw (2007-10): minpoly(), numerical algorithm
10
+
11
+ - Robert Bradshaw (2008-10): minpoly(), algebraic algorithm
12
+
13
+ - Golam Mortuza Hossain (2009-06-15): _limit_latex()
14
+
15
+ - Golam Mortuza Hossain (2009-06-22): _laplace_latex(), _inverse_laplace_latex()
16
+
17
+ - Tom Coates (2010-06-11): fixed :issue:`9217`
18
+
19
+ EXAMPLES:
20
+
21
+ The basic units of the calculus package are symbolic expressions which
22
+ are elements of the symbolic expression ring (SR). To create a
23
+ symbolic variable object in Sage, use the :func:`var` function, whose
24
+ argument is the text of that variable. Note that Sage is intelligent
25
+ about LaTeXing variable names.
26
+
27
+ ::
28
+
29
+ sage: x1 = var('x1'); x1
30
+ x1
31
+ sage: latex(x1)
32
+ x_{1}
33
+ sage: theta = var('theta'); theta
34
+ theta
35
+ sage: latex(theta)
36
+ \theta
37
+
38
+ Sage predefines ``x`` to be a global indeterminate.
39
+ Thus the following works::
40
+
41
+ sage: x^2
42
+ x^2
43
+ sage: type(x)
44
+ <class 'sage.symbolic.expression.Expression'>
45
+
46
+ More complicated expressions in Sage can be built up using ordinary
47
+ arithmetic. The following are valid, and follow the rules of Python
48
+ arithmetic: (The '=' operator represents assignment, and not
49
+ equality)
50
+
51
+ ::
52
+
53
+ sage: var('x,y,z')
54
+ (x, y, z)
55
+ sage: f = x + y + z/(2*sin(y*z/55))
56
+ sage: g = f^f; g
57
+ (x + y + 1/2*z/sin(1/55*y*z))^(x + y + 1/2*z/sin(1/55*y*z))
58
+
59
+ Differentiation and integration are available, but behind the
60
+ scenes through Maxima::
61
+
62
+ sage: f = sin(x)/cos(2*y)
63
+ sage: f.derivative(y)
64
+ 2*sin(x)*sin(2*y)/cos(2*y)^2
65
+ sage: g = f.integral(x); g
66
+ -cos(x)/cos(2*y)
67
+
68
+ Note that these methods usually require an explicit variable name. If none
69
+ is given, Sage will try to find one for you.
70
+
71
+ ::
72
+
73
+ sage: f = sin(x); f.derivative()
74
+ cos(x)
75
+
76
+ If the expression is a callable symbolic expression (i.e., the
77
+ variable order is specified), then Sage can calculate the matrix
78
+ derivative (i.e., the gradient, Jacobian matrix, etc.) if no variables
79
+ are specified. In the example below, we use the second derivative
80
+ test to determine that there is a saddle point at (0,-1/2).
81
+
82
+ ::
83
+
84
+ sage: f(x,y) = x^2*y + y^2 + y
85
+ sage: f.diff() # gradient
86
+ (x, y) |--> (2*x*y, x^2 + 2*y + 1)
87
+ sage: solve(list(f.diff()), [x,y])
88
+ [[x == -I, y == 0], [x == I, y == 0], [x == 0, y == (-1/2)]]
89
+ sage: H=f.diff(2); H # Hessian matrix
90
+ [(x, y) |--> 2*y (x, y) |--> 2*x]
91
+ [(x, y) |--> 2*x (x, y) |--> 2]
92
+ sage: H(x=0, y=-1/2)
93
+ [-1 0]
94
+ [ 0 2]
95
+ sage: H(x=0, y=-1/2).eigenvalues()
96
+ [-1, 2]
97
+
98
+ Here we calculate the Jacobian for the polar coordinate transformation::
99
+
100
+ sage: T(r,theta) = [r*cos(theta),r*sin(theta)]
101
+ sage: T
102
+ (r, theta) |--> (r*cos(theta), r*sin(theta))
103
+ sage: T.diff() # Jacobian matrix
104
+ [ (r, theta) |--> cos(theta) (r, theta) |--> -r*sin(theta)]
105
+ [ (r, theta) |--> sin(theta) (r, theta) |--> r*cos(theta)]
106
+ sage: diff(T) # Jacobian matrix
107
+ [ (r, theta) |--> cos(theta) (r, theta) |--> -r*sin(theta)]
108
+ [ (r, theta) |--> sin(theta) (r, theta) |--> r*cos(theta)]
109
+ sage: T.diff().det() # Jacobian
110
+ (r, theta) |--> r*cos(theta)^2 + r*sin(theta)^2
111
+
112
+ When the order of variables is ambiguous, Sage will raise an
113
+ exception when differentiating::
114
+
115
+ sage: f = sin(x+y); f.derivative()
116
+ Traceback (most recent call last):
117
+ ...
118
+ ValueError: No differentiation variable specified.
119
+
120
+ Simplifying symbolic sums is also possible, using the
121
+ :func:`sum` command, which also uses Maxima in the background::
122
+
123
+ sage: k, m = var('k, m')
124
+ sage: sum(1/k^4, k, 1, oo)
125
+ 1/90*pi^4
126
+ sage: sum(binomial(m,k), k, 0, m)
127
+ 2^m
128
+
129
+ Symbolic matrices can be used as well in various ways,
130
+ including exponentiation::
131
+
132
+ sage: M = matrix([[x,x^2],[1/x,x]])
133
+ sage: M^2
134
+ [x^2 + x 2*x^3]
135
+ [ 2 x^2 + x]
136
+ sage: e^M
137
+ [ 1/2*(e^(2*sqrt(x)) + 1)*e^(x - sqrt(x)) 1/2*(x*e^(2*sqrt(x)) - x)*sqrt(x)*e^(x - sqrt(x))]
138
+ [ 1/2*(e^(2*sqrt(x)) - 1)*e^(x - sqrt(x))/x^(3/2) 1/2*(e^(2*sqrt(x)) + 1)*e^(x - sqrt(x))]
139
+
140
+ Complex exponentiation works, but may require a patched version of
141
+ maxima (:issue:`32898`) for now::
142
+
143
+ sage: M = i*matrix([[pi]])
144
+ sage: e^M # not tested, requires patched maxima
145
+ [-1]
146
+ sage: M = i*matrix([[pi,0],[0,2*pi]])
147
+ sage: e^M
148
+ [-1 0]
149
+ [ 0 1]
150
+ sage: M = matrix([[0,pi],[-pi,0]])
151
+ sage: e^M
152
+ [-1 0]
153
+ [ 0 -1]
154
+
155
+ Substitution works similarly. We can substitute with a python
156
+ dict::
157
+
158
+ sage: f = sin(x*y - z)
159
+ sage: f({x: var('t'), y: z})
160
+ sin(t*z - z)
161
+
162
+ Also we can substitute with keywords::
163
+
164
+ sage: f = sin(x*y - z)
165
+ sage: f(x=t, y=z)
166
+ sin(t*z - z)
167
+
168
+ Another example::
169
+
170
+ sage: f = sin(2*pi*x/y)
171
+ sage: f(x=4)
172
+ sin(8*pi/y)
173
+
174
+ It is no longer allowed to call expressions with positional arguments::
175
+
176
+ sage: f = sin(x)
177
+ sage: f(y)
178
+ Traceback (most recent call last):
179
+ ...
180
+ TypeError: Substitution using function-call syntax and unnamed
181
+ arguments has been removed. You can use named arguments instead, like
182
+ EXPR(x=..., y=...)
183
+ sage: f(x=pi)
184
+ 0
185
+
186
+ We can also make a :class:`CallableSymbolicExpression`,
187
+ which is a :class:`SymbolicExpression` that is a function of
188
+ specified variables in a fixed order. Each
189
+ :class:`SymbolicExpression` has a
190
+ ``function(...)`` method that is used to create a
191
+ :class:`CallableSymbolicExpression`, as illustrated below::
192
+
193
+ sage: u = log((2-x)/(y+5))
194
+ sage: f = u.function(x, y); f
195
+ (x, y) |--> log(-(x - 2)/(y + 5))
196
+
197
+ There is an easier way of creating a
198
+ :class:`CallableSymbolicExpression`, which relies on the
199
+ Sage preparser.
200
+
201
+ ::
202
+
203
+ sage: f(x,y) = log(x)*cos(y); f
204
+ (x, y) |--> cos(y)*log(x)
205
+
206
+ Then we have fixed an order of variables and there is no ambiguity
207
+ substituting or evaluating::
208
+
209
+ sage: f(x,y) = log((2-x)/(y+5))
210
+ sage: f(7,t)
211
+ log(-5/(t + 5))
212
+
213
+ Some further examples::
214
+
215
+ sage: f = 5*sin(x)
216
+ sage: f
217
+ 5*sin(x)
218
+ sage: f(x=2)
219
+ 5*sin(2)
220
+ sage: f(x=pi)
221
+ 0
222
+ sage: float(f(x=pi))
223
+ 0.0
224
+
225
+ Another example::
226
+
227
+ sage: f = integrate(1/sqrt(9+x^2), x); f
228
+ arcsinh(1/3*x)
229
+ sage: f(x=3)
230
+ arcsinh(1)
231
+ sage: f.derivative(x)
232
+ 1/sqrt(x^2 + 9)
233
+
234
+ We compute the length of the parabola from 0 to 2::
235
+
236
+ sage: x = var('x')
237
+ sage: y = x^2
238
+ sage: dy = derivative(y,x)
239
+ sage: z = integral(sqrt(1 + dy^2), x, 0, 2)
240
+ sage: z
241
+ sqrt(17) + 1/4*arcsinh(4)
242
+ sage: n(z,200)
243
+ 4.6467837624329358733826155674904591885104869874232887508703
244
+ sage: float(z)
245
+ 4.646783762432936
246
+
247
+ We test pickling::
248
+
249
+ sage: x, y = var('x,y')
250
+ sage: f = -sqrt(pi)*(x^3 + sin(x/cos(y)))
251
+ sage: bool(loads(dumps(f)) == f)
252
+ True
253
+
254
+ Coercion examples:
255
+
256
+ We coerce various symbolic expressions into the complex numbers::
257
+
258
+ sage: CC(I)
259
+ 1.00000000000000*I
260
+ sage: CC(2*I)
261
+ 2.00000000000000*I
262
+ sage: ComplexField(200)(2*I)
263
+ 2.0000000000000000000000000000000000000000000000000000000000*I
264
+ sage: ComplexField(200)(sin(I))
265
+ 1.1752011936438014568823818505956008151557179813340958702296*I
266
+ sage: f = sin(I) + cos(I/2); f
267
+ cosh(1/2) + I*sinh(1)
268
+ sage: CC(f)
269
+ 1.12762596520638 + 1.17520119364380*I
270
+ sage: ComplexField(200)(f)
271
+ 1.1276259652063807852262251614026720125478471180986674836290
272
+ + 1.1752011936438014568823818505956008151557179813340958702296*I
273
+ sage: ComplexField(100)(f)
274
+ 1.1276259652063807852262251614 + 1.1752011936438014568823818506*I
275
+
276
+ We illustrate construction of an inverse sum where each denominator
277
+ has a new variable name::
278
+
279
+ sage: f = sum(1/var('n%s'%i)^i for i in range(10))
280
+ sage: f
281
+ 1/n1 + 1/n2^2 + 1/n3^3 + 1/n4^4 + 1/n5^5 + 1/n6^6 + 1/n7^7 + 1/n8^8 + 1/n9^9 + 1
282
+
283
+ Note that after calling var, the variables are immediately
284
+ available for use::
285
+
286
+ sage: (n1 + n2)^5
287
+ (n1 + n2)^5
288
+
289
+ We can, of course, substitute::
290
+
291
+ sage: f(n9=9, n7=n6)
292
+ 1/n1 + 1/n2^2 + 1/n3^3 + 1/n4^4 + 1/n5^5 + 1/n6^6 + 1/n6^7 + 1/n8^8
293
+ + 387420490/387420489
294
+
295
+ TESTS:
296
+
297
+ Substitution::
298
+
299
+ sage: f = x
300
+ sage: f(x=5)
301
+ 5
302
+
303
+ Simplifying expressions involving scientific notation::
304
+
305
+ sage: k = var('k')
306
+ sage: a0 = 2e-06; a1 = 12
307
+ sage: c = a1 + a0*k; c
308
+ (2.00000000000000e-6)*k + 12
309
+ sage: sqrt(c)
310
+ sqrt((2.00000000000000e-6)*k + 12)
311
+ sage: sqrt(c^3)
312
+ sqrt(((2.00000000000000e-6)*k + 12)^3)
313
+
314
+ The symbolic calculus package uses its own copy of Maxima for
315
+ simplification, etc., which is separate from the default
316
+ system-wide version::
317
+
318
+ sage: maxima.eval('[x,y]: [1,2]')
319
+ '[1,2]'
320
+ sage: maxima.eval('expand((x+y)^3)')
321
+ '27'
322
+
323
+ If the copy of Maxima used by the symbolic calculus package were
324
+ the same as the default one, then the following would return 27,
325
+ which would be very confusing indeed!
326
+
327
+ ::
328
+
329
+ sage: x, y = var('x,y')
330
+ sage: expand((x+y)^3)
331
+ x^3 + 3*x^2*y + 3*x*y^2 + y^3
332
+
333
+ Set x to be 5 in maxima::
334
+
335
+ sage: maxima('x: 5')
336
+ 5
337
+ sage: maxima('x + x + %pi')
338
+ %pi+10
339
+
340
+ Simplifications like these are now done using Pynac::
341
+
342
+ sage: x + x + pi
343
+ pi + 2*x
344
+
345
+ But this still uses Maxima::
346
+
347
+ sage: (x + x + pi).simplify()
348
+ pi + 2*x
349
+
350
+ Note that ``x`` is still ``x``, since the
351
+ maxima used by the calculus package is different than the one in
352
+ the interactive interpreter.
353
+
354
+ Check to see that the problem with the variables method mentioned
355
+ in :issue:`3779` is actually fixed::
356
+
357
+ sage: f = function('F')(x)
358
+ sage: diff(f*SR(1),x)
359
+ diff(F(x), x)
360
+
361
+ Doubly ensure that :issue:`7479` is working::
362
+
363
+ sage: f(x)=x
364
+ sage: integrate(f,x,0,1)
365
+ 1/2
366
+
367
+ Check that the problem with Taylor expansions of the gamma function
368
+ (:issue:`9217`) is fixed::
369
+
370
+ sage: taylor(gamma(1/3+x),x,0,3)
371
+ -1/432*((72*euler_gamma^3 + 36*euler_gamma^2*(sqrt(3)*pi + 9*log(3)) + ...
372
+ sage: [f[0].n() for f in _.coefficients()] # numerical coefficients to make comparison easier; Maple 12 gives same answer
373
+ [2.6789385347..., -8.3905259853..., 26.662447494..., -80.683148377...]
374
+
375
+ Ensure that :issue:`8582` is fixed::
376
+
377
+ sage: k = var("k")
378
+ sage: sum(1/(1+k^2), k, -oo, oo)
379
+ -1/2*I*psi(I + 1) + 1/2*I*psi(-I + 1) - 1/2*I*psi(I) + 1/2*I*psi(-I)
380
+
381
+ Ensure that :issue:`8624` is fixed::
382
+
383
+ sage: integrate(abs(cos(x)) * sin(x), x, pi/2, pi)
384
+ 1/2
385
+ sage: integrate(sqrt(cos(x)^2 + sin(x)^2), x, 0, 2*pi)
386
+ 2*pi
387
+
388
+ Ensure that :issue:`25626` is fixed. As the form of the answer is dependent of
389
+ the giac version, we simplify it (see :issue:`34037`)::
390
+
391
+ sage: # needs sage.libs.giac
392
+ sage: t = SR.var('t')
393
+ sage: integrate(exp(t)/(t + 1)^2, t, algorithm='giac').full_simplify()
394
+ ((t + 1)*Ei(t + 1) - e^(t + 1))/(t*e + e)
395
+
396
+ Check if maxima has redundant variables defined after initialization,
397
+ see :issue:`9538`::
398
+
399
+ sage: maxima = sage.interfaces.maxima.maxima
400
+ sage: maxima('f1')
401
+ f1
402
+ sage: sage.calculus.calculus.maxima('f1')
403
+ f1
404
+
405
+ To check that :issue:`14821` is fixed::
406
+
407
+ sage: H = exp(-1.0 * x)
408
+ sage: H.integral(x, 0, 1)
409
+ 0.6321205588285577
410
+ sage: result = integral(exp(-300.0/(-0.064*x+14.0)),x,0.0,120.0)
411
+ ...
412
+ sage: result # abs tol 1e-10
413
+ 4.62770039817000e-9
414
+
415
+ To check that :issue:`27092` is fixed::
416
+
417
+ sage: n = var('n')
418
+ sage: sum(binomial(1, n), n, 0, oo)
419
+ 2
420
+ """
421
+
422
+ import re
423
+ from sage.arith.misc import algebraic_dependency
424
+ from sage.rings.integer import Integer
425
+ from sage.rings.rational_field import QQ
426
+ from sage.rings.real_double import RealDoubleElement
427
+ from sage.rings.real_mpfr import RR, create_RealNumber
428
+ from sage.rings.cc import CC
429
+
430
+ from sage.misc.latex import latex
431
+ from sage.misc.parser import Parser, LookupNameMaker
432
+ from sage.structure.element import Expression
433
+ from sage.symbolic.ring import var, SR
434
+ from sage.symbolic.symbols import symbol_table
435
+ from sage.symbolic.function import Function
436
+ from sage.symbolic.function_factory import function_factory
437
+ from sage.symbolic.integration.integral import (indefinite_integral,
438
+ definite_integral)
439
+
440
+ from sage.misc.lazy_import import lazy_import
441
+ lazy_import('sage.interfaces.maxima_lib', 'maxima')
442
+ from types import FunctionType
443
+
444
+
445
+ ########################################################
446
+ def symbolic_sum(expression, v, a, b, algorithm='maxima', hold=False):
447
+ r"""
448
+ Return the symbolic sum `\sum_{v = a}^b expression` with respect
449
+ to the variable `v` with endpoints `a` and `b`.
450
+
451
+ INPUT:
452
+
453
+ - ``expression`` -- a symbolic expression
454
+
455
+ - ``v`` -- a variable or variable name
456
+
457
+ - ``a`` -- lower endpoint of the sum
458
+
459
+ - ``b`` -- upper endpoint of the sum
460
+
461
+ - ``algorithm`` -- (default: ``'maxima'``) one of
462
+
463
+ - ``'maxima'`` -- use Maxima (the default)
464
+
465
+ - ``'maple'`` -- (optional) use Maple
466
+
467
+ - ``'mathematica'`` -- (optional) use Mathematica
468
+
469
+ - ``'giac'`` -- (optional) use Giac
470
+
471
+ - ``'sympy'`` -- use SymPy
472
+
473
+ - ``hold`` -- boolean (default: ``False``); if ``True``, don't evaluate
474
+
475
+ EXAMPLES::
476
+
477
+ sage: k, n = var('k,n')
478
+ sage: from sage.calculus.calculus import symbolic_sum
479
+ sage: symbolic_sum(k, k, 1, n).factor()
480
+ 1/2*(n + 1)*n
481
+
482
+ ::
483
+
484
+ sage: symbolic_sum(1/k^4, k, 1, oo)
485
+ 1/90*pi^4
486
+
487
+ ::
488
+
489
+ sage: symbolic_sum(1/k^5, k, 1, oo)
490
+ zeta(5)
491
+
492
+ A well known binomial identity::
493
+
494
+ sage: symbolic_sum(binomial(n,k), k, 0, n)
495
+ 2^n
496
+
497
+ And some truncations thereof::
498
+
499
+ sage: assume(n>1)
500
+ sage: symbolic_sum(binomial(n,k), k, 1, n)
501
+ 2^n - 1
502
+ sage: symbolic_sum(binomial(n,k), k, 2, n)
503
+ 2^n - n - 1
504
+ sage: symbolic_sum(binomial(n,k), k, 0, n-1)
505
+ 2^n - 1
506
+ sage: symbolic_sum(binomial(n,k), k, 1, n-1)
507
+ 2^n - 2
508
+
509
+ The binomial theorem::
510
+
511
+ sage: x, y = var('x, y')
512
+ sage: symbolic_sum(binomial(n,k) * x^k * y^(n-k), k, 0, n)
513
+ (x + y)^n
514
+
515
+ ::
516
+
517
+ sage: symbolic_sum(k * binomial(n, k), k, 1, n)
518
+ 2^(n - 1)*n
519
+
520
+ ::
521
+
522
+ sage: symbolic_sum((-1)^k*binomial(n,k), k, 0, n)
523
+ 0
524
+
525
+ ::
526
+
527
+ sage: symbolic_sum(2^(-k)/(k*(k+1)), k, 1, oo)
528
+ -log(2) + 1
529
+
530
+ Summing a hypergeometric term::
531
+
532
+ sage: symbolic_sum(binomial(n, k) * factorial(k) / factorial(n+1+k), k, 0, n)
533
+ 1/2*sqrt(pi)/factorial(n + 1/2)
534
+
535
+ We check a well known identity::
536
+
537
+ sage: bool(symbolic_sum(k^3, k, 1, n) == symbolic_sum(k, k, 1, n)^2)
538
+ True
539
+
540
+ A geometric sum::
541
+
542
+ sage: a, q = var('a, q')
543
+ sage: symbolic_sum(a*q^k, k, 0, n)
544
+ (a*q^(n + 1) - a)/(q - 1)
545
+
546
+ For the geometric series, we will have to assume
547
+ the right values for the sum to converge::
548
+
549
+ sage: assume(abs(q) < 1)
550
+ sage: symbolic_sum(a*q^k, k, 0, oo)
551
+ -a/(q - 1)
552
+
553
+ A divergent geometric series. Don't forget
554
+ to forget your assumptions::
555
+
556
+ sage: forget()
557
+ sage: assume(q > 1)
558
+ sage: symbolic_sum(a*q^k, k, 0, oo)
559
+ Traceback (most recent call last):
560
+ ...
561
+ ValueError: Sum is divergent.
562
+ sage: forget()
563
+ sage: assumptions() # check the assumptions were really forgotten
564
+ []
565
+
566
+ A summation performed by Mathematica::
567
+
568
+ sage: symbolic_sum(1/(1+k^2), k, -oo, oo, algorithm='mathematica') # optional - mathematica
569
+ pi*coth(pi)
570
+
571
+ An example of this summation with Giac::
572
+
573
+ sage: # needs giac
574
+ sage: symbolic_sum(1/(1+k^2), k, -oo, oo, algorithm='giac').factor()
575
+ pi*(e^(2*pi) + 1)/((e^pi + 1)*(e^pi - 1))
576
+
577
+ The same summation is solved by SymPy::
578
+
579
+ sage: symbolic_sum(1/(1+k^2), k, -oo, oo, algorithm='sympy')
580
+ pi/tanh(pi)
581
+
582
+ SymPy and Maxima 5.39.0 can do the following (see
583
+ :issue:`22005`)::
584
+
585
+ sage: sum(1/((2*n+1)^2-4)^2, n, 0, Infinity, algorithm='sympy')
586
+ 1/64*pi^2
587
+ sage: sum(1/((2*n+1)^2-4)^2, n, 0, Infinity)
588
+ 1/64*pi^2
589
+
590
+ Use Maple as a backend for summation::
591
+
592
+ sage: symbolic_sum(binomial(n,k)*x^k, k, 0, n, algorithm='maple') # optional - maple
593
+ (x + 1)^n
594
+
595
+ If you don't want to evaluate immediately give the ``hold`` keyword::
596
+
597
+ sage: s = sum(n, n, 1, k, hold=True); s
598
+ sum(n, n, 1, k)
599
+ sage: s.unhold()
600
+ 1/2*k^2 + 1/2*k
601
+ sage: s.subs(k == 10)
602
+ sum(n, n, 1, 10)
603
+ sage: s.subs(k == 10).unhold()
604
+ 55
605
+ sage: s.subs(k == 10).n()
606
+ 55.0000000000000
607
+
608
+ TESTS:
609
+
610
+ :issue:`10564` is fixed::
611
+
612
+ sage: sum (n^3 * x^n, n, 0, infinity)
613
+ (x^3 + 4*x^2 + x)/(x^4 - 4*x^3 + 6*x^2 - 4*x + 1)
614
+
615
+ .. NOTE::
616
+
617
+ Sage can currently only understand a subset of the output of Maxima,
618
+ Maple and Mathematica, so even if the chosen backend can perform
619
+ the summation the result might not be convertible into a Sage
620
+ expression.
621
+ """
622
+ if not (isinstance(v, Expression) and v.is_symbol()):
623
+ if isinstance(v, str):
624
+ v = var(v)
625
+ else:
626
+ raise TypeError("need a summation variable")
627
+
628
+ if v in SR(a).variables() or v in SR(b).variables():
629
+ raise ValueError("summation limits must not depend on the summation variable")
630
+
631
+ if hold:
632
+ from sage.functions.other import symbolic_sum as ssum
633
+ return ssum(expression, v, a, b)
634
+
635
+ if algorithm == 'maxima':
636
+ return maxima.sr_sum(expression,v,a,b)
637
+
638
+ elif algorithm == 'mathematica':
639
+ try:
640
+ sum = "Sum[%s, {%s, %s, %s}]" % tuple([repr(expr._mathematica_()) for expr in (expression, v, a, b)])
641
+ except TypeError:
642
+ raise ValueError("Mathematica cannot make sense of input")
643
+ from sage.interfaces.mathematica import mathematica
644
+ try:
645
+ result = mathematica(sum)
646
+ except TypeError:
647
+ raise ValueError("Mathematica cannot make sense of: %s" % sum)
648
+ return result.sage()
649
+
650
+ elif algorithm == 'maple':
651
+ sum = "sum(%s, %s=%s..%s)" % tuple([repr(expr._maple_()) for expr in (expression, v, a, b)])
652
+ from sage.interfaces.maple import maple
653
+ try:
654
+ result = maple(sum).simplify()
655
+ except TypeError:
656
+ raise ValueError("Maple cannot make sense of: %s" % sum)
657
+ return result.sage()
658
+
659
+ elif algorithm == 'giac':
660
+ sum = "sum(%s, %s, %s, %s)" % tuple([repr(expr._giac_()) for expr in (expression, v, a, b)])
661
+ from sage.interfaces.giac import giac
662
+ try:
663
+ result = giac(sum)
664
+ except TypeError:
665
+ raise ValueError("Giac cannot make sense of: %s" % sum)
666
+ return result.sage()
667
+
668
+ elif algorithm == 'sympy':
669
+ expression,v,a,b = (expr._sympy_() for expr in (expression, v, a, b))
670
+ from sympy import summation
671
+ from sage.interfaces.sympy import sympy_init
672
+ sympy_init()
673
+ result = summation(expression, (v, a, b))
674
+ try:
675
+ return result._sage_()
676
+ except AttributeError:
677
+ raise AttributeError("Unable to convert SymPy result (={}) into"
678
+ " Sage".format(result))
679
+
680
+ else:
681
+ raise ValueError("unknown algorithm: %s" % algorithm)
682
+
683
+
684
+ def nintegral(ex, x, a, b,
685
+ desired_relative_error='1e-8',
686
+ maximum_num_subintervals=200):
687
+ r"""
688
+ Return a floating point machine precision numerical approximation
689
+ to the integral of ``self`` from `a` to
690
+ `b`, computed using floating point arithmetic via maxima.
691
+
692
+ INPUT:
693
+
694
+ - ``x`` -- variable to integrate with respect to
695
+
696
+ - ``a`` -- lower endpoint of integration
697
+
698
+ - ``b`` -- upper endpoint of integration
699
+
700
+ - ``desired_relative_error`` -- (default: ``1e-8``) the
701
+ desired relative error
702
+
703
+ - ``maximum_num_subintervals`` -- (default: 200)
704
+ maximal number of subintervals
705
+
706
+ OUTPUT: float; approximation to the integral
707
+
708
+ - float: estimated absolute error of the
709
+ approximation
710
+
711
+ - the number of integrand evaluations
712
+
713
+ - an error code:
714
+
715
+ - ``0`` -- no problems were encountered
716
+
717
+ - ``1`` -- too many subintervals were done
718
+
719
+ - ``2`` -- excessive roundoff error
720
+
721
+ - ``3`` -- extremely bad integrand behavior
722
+
723
+ - ``4`` -- failed to converge
724
+
725
+ - ``5`` -- integral is probably divergent or slowly
726
+ convergent
727
+
728
+ - ``6`` -- the input is invalid; this includes the case of
729
+ ``desired_relative_error`` being too small to be achieved
730
+
731
+ ALIAS: :func:`nintegrate` is the same as :func:`nintegral`
732
+
733
+ REMARK: There is also a function
734
+ :func:`numerical_integral` that implements numerical
735
+ integration using the GSL C library. It is potentially much faster
736
+ and applies to arbitrary user defined functions.
737
+
738
+ Also, there are limits to the precision to which Maxima can compute
739
+ the integral due to limitations in quadpack.
740
+ In the following example, remark that the last value of the returned
741
+ tuple is ``6``, indicating that the input was invalid, in this case
742
+ because of a too high desired precision.
743
+
744
+ ::
745
+
746
+ sage: f = x
747
+ sage: f.nintegral(x, 0, 1, 1e-14)
748
+ (0.0, 0.0, 0, 6)
749
+
750
+ EXAMPLES::
751
+
752
+ sage: f(x) = exp(-sqrt(x))
753
+ sage: f.nintegral(x, 0, 1)
754
+ (0.5284822353142306, 4.163...e-11, 231, 0)
755
+
756
+ We can also use the :func:`numerical_integral` function,
757
+ which calls the GSL C library.
758
+
759
+ ::
760
+
761
+ sage: numerical_integral(f, 0, 1)
762
+ (0.528482232253147, 6.83928460...e-07)
763
+
764
+ Note that in exotic cases where floating point evaluation of the
765
+ expression leads to the wrong value, then the output can be
766
+ completely wrong::
767
+
768
+ sage: f = exp(pi*sqrt(163)) - 262537412640768744
769
+
770
+ Despite appearance, `f` is really very close to 0, but one
771
+ gets a nonzero value since the definition of
772
+ ``float(f)`` is that it makes all constants inside the
773
+ expression floats, then evaluates each function and each arithmetic
774
+ operation using float arithmetic::
775
+
776
+ sage: float(f)
777
+ -480.0
778
+
779
+ Computing to higher precision we see the truth::
780
+
781
+ sage: f.n(200)
782
+ -7.4992740280181431112064614366622348652078895136533593355718e-13
783
+ sage: f.n(300)
784
+ -7.49927402801814311120646143662663009137292462589621789352095066181709095575681963967103004e-13
785
+
786
+ Now numerically integrating, we see why the answer is wrong::
787
+
788
+ sage: f.nintegrate(x,0,1)
789
+ (-480.000000000000..., 5.32907051820075...e-12, 21, 0)
790
+
791
+ It is just because every floating point evaluation of `f` returns `-480.0`
792
+ in floating point.
793
+
794
+ Important note: using PARI/GP one can compute numerical integrals
795
+ to high precision::
796
+
797
+ sage: # needs sage.libs.pari
798
+ sage: gp.eval('intnum(x=17,42,exp(-x^2)*log(x))')
799
+ '2.5657285005610514829176211363206621657 E-127'
800
+ sage: old_prec = gp.set_real_precision(50)
801
+ sage: gp.eval('intnum(x=17,42,exp(-x^2)*log(x))')
802
+ '2.5657285005610514829173563961304957417746108003917 E-127'
803
+ sage: gp.set_real_precision(old_prec)
804
+ 57
805
+
806
+ Note that the input function above is a string in PARI syntax.
807
+ """
808
+ try:
809
+ v = ex._maxima_().quad_qags(x, a, b,
810
+ epsrel=desired_relative_error,
811
+ limit=maximum_num_subintervals)
812
+ except TypeError as err:
813
+ if "ERROR" in str(err):
814
+ raise ValueError("Maxima (via quadpack) cannot compute the integral")
815
+ else:
816
+ raise TypeError(err)
817
+
818
+ # Maxima returns unevaluated expressions when the underlying library fails
819
+ # to perform numerical integration. See:
820
+ # http://www.math.utexas.edu/pipermail/maxima/2008/012975.html
821
+ if 'quad_qags' in str(v):
822
+ raise ValueError("Maxima (via quadpack) cannot compute the integral")
823
+
824
+ return float(v[0]), float(v[1]), Integer(v[2]), Integer(v[3])
825
+
826
+
827
+ nintegrate = nintegral
828
+
829
+
830
+ def symbolic_product(expression, v, a, b, algorithm='maxima', hold=False):
831
+ r"""
832
+ Return the symbolic product `\prod_{v = a}^b expression` with respect
833
+ to the variable `v` with endpoints `a` and `b`.
834
+
835
+ INPUT:
836
+
837
+ - ``expression`` -- a symbolic expression
838
+
839
+ - ``v`` -- a variable or variable name
840
+
841
+ - ``a`` -- lower endpoint of the product
842
+
843
+ - ``b`` -- upper endpoint of the prduct
844
+
845
+ - ``algorithm`` -- (default: ``'maxima'``) one of
846
+
847
+ - ``'maxima'`` -- use Maxima (the default)
848
+
849
+ - ``'giac'`` -- use Giac (optional)
850
+
851
+ - ``'sympy'`` -- use SymPy
852
+
853
+ - ``'mathematica'`` -- (optional) use Mathematica
854
+
855
+ - ``hold`` -- boolean (default: ``False``); if ``True``, don't evaluate
856
+
857
+ EXAMPLES::
858
+
859
+ sage: i, k, n = var('i,k,n')
860
+ sage: from sage.calculus.calculus import symbolic_product
861
+ sage: symbolic_product(k, k, 1, n)
862
+ factorial(n)
863
+ sage: symbolic_product(x + i*(i+1)/2, i, 1, 4)
864
+ x^4 + 20*x^3 + 127*x^2 + 288*x + 180
865
+ sage: symbolic_product(i^2, i, 1, 7)
866
+ 25401600
867
+ sage: f = function('f')
868
+ sage: symbolic_product(f(i), i, 1, 7)
869
+ f(7)*f(6)*f(5)*f(4)*f(3)*f(2)*f(1)
870
+ sage: symbolic_product(f(i), i, 1, n)
871
+ product(f(i), i, 1, n)
872
+ sage: assume(k>0)
873
+ sage: symbolic_product(integrate (x^k, x, 0, 1), k, 1, n)
874
+ 1/factorial(n + 1)
875
+ sage: symbolic_product(f(i), i, 1, n).log().log_expand()
876
+ sum(log(f(i)), i, 1, n)
877
+
878
+ TESTS:
879
+
880
+ Verify that :issue:`30520` is fixed::
881
+
882
+ sage: symbolic_product(-x^2,x,1,n)
883
+ (-1)^n*factorial(n)^2
884
+ """
885
+ if not (isinstance(v, Expression) and v.is_symbol()):
886
+ if isinstance(v, str):
887
+ v = var(v)
888
+ else:
889
+ raise TypeError("need a multiplication variable")
890
+
891
+ if v in SR(a).variables() or v in SR(b).variables():
892
+ raise ValueError("product limits must not depend on the multiplication variable")
893
+
894
+ if hold:
895
+ from sage.functions.other import symbolic_product as sprod
896
+ return sprod(expression, v, a, b)
897
+
898
+ if algorithm == 'maxima':
899
+ return maxima.sr_prod(expression,v,a,b)
900
+
901
+ elif algorithm == 'mathematica':
902
+ try:
903
+ prod = "Product[%s, {%s, %s, %s}]" % tuple([repr(expr._mathematica_()) for expr in (expression, v, a, b)])
904
+ except TypeError:
905
+ raise ValueError("Mathematica cannot make sense of input")
906
+ from sage.interfaces.mathematica import mathematica
907
+ try:
908
+ result = mathematica(prod)
909
+ except TypeError:
910
+ raise ValueError("Mathematica cannot make sense of: %s" % sum)
911
+ return result.sage()
912
+
913
+ elif algorithm == 'giac':
914
+ prod = "product(%s, %s, %s, %s)" % tuple([repr(expr._giac_()) for expr in (expression, v, a, b)])
915
+ from sage.interfaces.giac import giac
916
+ try:
917
+ result = giac(prod)
918
+ except TypeError:
919
+ raise ValueError("Giac cannot make sense of: %s" % sum)
920
+ return result.sage()
921
+
922
+ elif algorithm == 'sympy':
923
+ expression,v,a,b = (expr._sympy_() for expr in (expression, v, a, b))
924
+ from sympy import product as sproduct
925
+ from sage.interfaces.sympy import sympy_init
926
+ sympy_init()
927
+ result = sproduct(expression, (v, a, b))
928
+ try:
929
+ return result._sage_()
930
+ except AttributeError:
931
+ raise AttributeError("Unable to convert SymPy result (={}) into"
932
+ " Sage".format(result))
933
+
934
+ else:
935
+ raise ValueError("unknown algorithm: %s" % algorithm)
936
+
937
+
938
+ def minpoly(ex, var='x', algorithm=None, bits=None, degree=None, epsilon=0):
939
+ r"""
940
+ Return the minimal polynomial of ``self``, if possible.
941
+
942
+ INPUT:
943
+
944
+ - ``var`` -- polynomial variable name (default: ``'x'``)
945
+
946
+ - ``algorithm`` -- ``'algebraic'`` or ``'numerical'`` (default
947
+ both, but with numerical first)
948
+
949
+ - ``bits`` -- the number of bits to use in numerical
950
+ approx
951
+
952
+ - ``degree`` -- the expected algebraic degree
953
+
954
+ - ``epsilon`` -- return without error as long as
955
+ f(self) epsilon, in the case that the result cannot be proven
956
+
957
+ All of the above parameters are optional, with epsilon=0, ``bits`` and
958
+ ``degree`` tested up to 1000 and 24 by default respectively. The
959
+ numerical algorithm will be faster if bits and/or degree are given
960
+ explicitly. The algebraic algorithm ignores the last three
961
+ parameters.
962
+
963
+ OUTPUT: the minimal polynomial of ``self``. If the numerical algorithm
964
+ is used, then it is proved symbolically when ``epsilon=0`` (default).
965
+
966
+ If the minimal polynomial could not be found, two distinct kinds of
967
+ errors are raised. If no reasonable candidate was found with the
968
+ given ``bits``/``degree`` parameters, a :exc:`ValueError` will be
969
+ raised. If a reasonable candidate was found but (perhaps due to
970
+ limits in the underlying symbolic package) was unable to be proved
971
+ correct, a :exc:`NotImplementedError` will be raised.
972
+
973
+ ALGORITHM: Two distinct algorithms are used, depending on the
974
+ algorithm parameter. By default, the numerical algorithm is
975
+ attempted first, then the algebraic one.
976
+
977
+ Algebraic: Attempt to evaluate this expression in ``QQbar``, using
978
+ cyclotomic fields to resolve exponential and trig functions at
979
+ rational multiples of `\pi`, field extensions to handle roots and
980
+ rational exponents, and computing compositums to represent the full
981
+ expression as an element of a number field where the minimal
982
+ polynomial can be computed exactly. The ``bits``, ``degree``, and ``epsilon``
983
+ parameters are ignored.
984
+
985
+ Numerical: Computes a numerical approximation of
986
+ ``self`` and use PARI's :pari:`algdep` to get a candidate
987
+ minpoly `f`. If `f(\mathtt{self})`,
988
+ evaluated to a higher precision, is close enough to 0 then evaluate
989
+ `f(\mathtt{self})` symbolically, attempting to prove
990
+ vanishing. If this fails, and ``epsilon`` is nonzero,
991
+ return `f` if and only if
992
+ `f(\mathtt{self}) < \mathtt{epsilon}`.
993
+ Otherwise raise a :exc:`ValueError` (if no suitable
994
+ candidate was found) or a :exc:`NotImplementedError` (if a
995
+ likely candidate was found but could not be proved correct).
996
+
997
+ EXAMPLES: First some simple examples::
998
+
999
+ sage: # needs fpylll
1000
+ sage: sqrt(2).minpoly()
1001
+ x^2 - 2
1002
+ sage: minpoly(2^(1/3))
1003
+ x^3 - 2
1004
+ sage: minpoly(sqrt(2) + sqrt(-1))
1005
+ x^4 - 2*x^2 + 9
1006
+ sage: minpoly(sqrt(2)-3^(1/3))
1007
+ x^6 - 6*x^4 + 6*x^3 + 12*x^2 + 36*x + 1
1008
+
1009
+
1010
+ Works with trig and exponential functions too.
1011
+
1012
+ ::
1013
+
1014
+ sage: # needs fpylll
1015
+ sage: sin(pi/3).minpoly()
1016
+ x^2 - 3/4
1017
+ sage: sin(pi/7).minpoly()
1018
+ x^6 - 7/4*x^4 + 7/8*x^2 - 7/64
1019
+ sage: minpoly(exp(I*pi/17))
1020
+ x^16 - x^15 + x^14 - x^13 + x^12 - x^11 + x^10 - x^9 + x^8
1021
+ - x^7 + x^6 - x^5 + x^4 - x^3 + x^2 - x + 1
1022
+
1023
+ Here we verify it gives the same result as the abstract number
1024
+ field.
1025
+
1026
+ ::
1027
+
1028
+ sage: # needs fpylll
1029
+ sage: (sqrt(2) + sqrt(3) + sqrt(6)).minpoly()
1030
+ x^4 - 22*x^2 - 48*x - 23
1031
+ sage: K.<a,b> = NumberField([x^2-2, x^2-3])
1032
+ sage: (a+b+a*b).absolute_minpoly()
1033
+ x^4 - 22*x^2 - 48*x - 23
1034
+
1035
+ The :func:`minpoly` function is used implicitly when creating
1036
+ number fields::
1037
+
1038
+ sage: # needs fpylll
1039
+ sage: x = var('x')
1040
+ sage: eqn = x^3 + sqrt(2)*x + 5 == 0
1041
+ sage: a = solve(eqn, x)[0].rhs()
1042
+ sage: QQ[a]
1043
+ Number Field in a with defining polynomial x^6 + 10*x^3 - 2*x^2 + 25
1044
+ with a = 0.7185272465828846? - 1.721353471724806?*I
1045
+
1046
+ Here we solve a cubic and then recover it from its complicated
1047
+ radical expansion.
1048
+
1049
+ ::
1050
+
1051
+ sage: # needs fpylll
1052
+ sage: f = x^3 - x + 1
1053
+ sage: a = f.solve(x)[0].rhs(); a
1054
+ -1/2*(1/18*sqrt(23)*sqrt(3) - 1/2)^(1/3)*(I*sqrt(3) + 1)
1055
+ - 1/6*(-I*sqrt(3) + 1)/(1/18*sqrt(23)*sqrt(3) - 1/2)^(1/3)
1056
+ sage: a.minpoly()
1057
+ x^3 - x + 1
1058
+
1059
+ Note that simplification may be necessary to see that the minimal
1060
+ polynomial is correct.
1061
+
1062
+ ::
1063
+
1064
+ sage: # needs fpylll
1065
+ sage: a = sqrt(2) + sqrt(3) + sqrt(5)
1066
+ sage: f = a.minpoly(); f
1067
+ x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576
1068
+ sage: f(a)
1069
+ (sqrt(5) + sqrt(3) + sqrt(2))^8 - 40*(sqrt(5) + sqrt(3) + sqrt(2))^6
1070
+ + 352*(sqrt(5) + sqrt(3) + sqrt(2))^4 - 960*(sqrt(5) + sqrt(3) + sqrt(2))^2
1071
+ + 576
1072
+ sage: f(a).expand()
1073
+ 0
1074
+
1075
+ ::
1076
+
1077
+ sage: # needs fpylll
1078
+ sage: a = sin(pi/7)
1079
+ sage: f = a.minpoly(algorithm='numerical'); f
1080
+ x^6 - 7/4*x^4 + 7/8*x^2 - 7/64
1081
+ sage: f(a).horner(a).numerical_approx(100)
1082
+ 0.00000000000000000000000000000
1083
+
1084
+ The degree must be high enough (default tops out at 24).
1085
+
1086
+ ::
1087
+
1088
+ sage: # needs fpylll
1089
+ sage: a = sqrt(3) + sqrt(2)
1090
+ sage: a.minpoly(algorithm='numerical', bits=100, degree=3)
1091
+ Traceback (most recent call last):
1092
+ ...
1093
+ ValueError: Could not find minimal polynomial (100 bits, degree 3).
1094
+ sage: a.minpoly(algorithm='numerical', bits=100, degree=10)
1095
+ x^4 - 10*x^2 + 1
1096
+
1097
+ ::
1098
+
1099
+ sage: # needs fpylll
1100
+ sage: cos(pi/33).minpoly(algorithm='algebraic')
1101
+ x^10 + 1/2*x^9 - 5/2*x^8 - 5/4*x^7 + 17/8*x^6 + 17/16*x^5
1102
+ - 43/64*x^4 - 43/128*x^3 + 3/64*x^2 + 3/128*x + 1/1024
1103
+ sage: cos(pi/33).minpoly(algorithm='numerical')
1104
+ x^10 + 1/2*x^9 - 5/2*x^8 - 5/4*x^7 + 17/8*x^6 + 17/16*x^5
1105
+ - 43/64*x^4 - 43/128*x^3 + 3/64*x^2 + 3/128*x + 1/1024
1106
+
1107
+ Sometimes it fails, as it must given that some numbers aren't algebraic::
1108
+
1109
+ sage: sin(1).minpoly(algorithm='numerical') # needs fpylll
1110
+ Traceback (most recent call last):
1111
+ ...
1112
+ ValueError: Could not find minimal polynomial (1000 bits, degree 24).
1113
+
1114
+ .. NOTE::
1115
+
1116
+ Of course, failure to produce a minimal polynomial does not
1117
+ necessarily indicate that this number is transcendental.
1118
+ """
1119
+ if algorithm is None or algorithm.startswith('numeric'):
1120
+ bits_list = [bits] if bits else [100,200,500,1000]
1121
+ degree_list = [degree] if degree else [2,4,8,12,24]
1122
+
1123
+ for bits in bits_list:
1124
+ a = ex.numerical_approx(bits)
1125
+ check_bits = int(1.25 * bits + 80)
1126
+ aa = ex.numerical_approx(check_bits)
1127
+
1128
+ for degree in degree_list:
1129
+
1130
+ f = QQ[var](algebraic_dependency(a, degree)) # TODO: use the known_bits parameter?
1131
+ # If indeed we have found a minimal polynomial,
1132
+ # it should be accurate to a much higher precision.
1133
+ error = abs(f(aa))
1134
+ dx = ~RR(Integer(1) << (check_bits - degree - 2))
1135
+ expected_error = abs(f.derivative()(CC(aa))) * dx
1136
+
1137
+ if error < expected_error:
1138
+ # Degree might have been an over-estimate,
1139
+ # factor because we want (irreducible) minpoly.
1140
+ ff = f.factor()
1141
+ for g, e in ff:
1142
+ lead = g.leading_coefficient()
1143
+ if lead != 1:
1144
+ g = g / lead
1145
+ expected_error = abs(g.derivative()(CC(aa))) * dx
1146
+ error = abs(g(aa))
1147
+ if error < expected_error:
1148
+ # See if we can prove equality exactly
1149
+ if g(ex).simplify_trig().canonicalize_radical() == 0:
1150
+ return g
1151
+ # Otherwise fall back to numerical guess
1152
+ elif epsilon and error < epsilon:
1153
+ return g
1154
+ elif algorithm is not None:
1155
+ raise NotImplementedError("Could not prove minimal polynomial %s (epsilon %s)" % (g, RR(error).str(no_sci=False)))
1156
+
1157
+ if algorithm is not None:
1158
+ raise ValueError("Could not find minimal polynomial (%s bits, degree %s)." % (bits, degree))
1159
+
1160
+ if algorithm is None or algorithm == 'algebraic':
1161
+ from sage.rings.qqbar import QQbar
1162
+ return QQ[var](QQbar(ex).minpoly())
1163
+
1164
+ raise ValueError("Unknown algorithm: %s" % algorithm)
1165
+
1166
+
1167
+ ###################################################################
1168
+ # limits
1169
+ ###################################################################
1170
+ def limit(ex, *args, dir=None, taylor=False, algorithm='maxima', **kwargs):
1171
+ r"""
1172
+ Return the limit as the variable `v` approaches `a`
1173
+ from the given direction.
1174
+
1175
+ SYNTAX:
1176
+
1177
+ There are two ways of invoking limit. One can write
1178
+ ``limit(expr, x=a, <keywords>)`` or ``limit(expr, x, a, <keywords>)``.
1179
+ In the first option, ``x`` must be a valid Python identifier. Its
1180
+ string representation is used to create the corresponding symbolic
1181
+ variable with respect to which to take the limit. In the second
1182
+ option, ``x`` can simply be a symbolic variable. For symbolic
1183
+ variables that do not have a string representation that is a valid
1184
+ Python identifier (for instance, if ``x`` is an indexed symbolic
1185
+ variable), the second option is required.
1186
+
1187
+ INPUT:
1188
+
1189
+ - ``ex`` -- the expression whose limit is computed. Must be convertible
1190
+ to a symbolic expression.
1191
+ - ``v`` -- The variable for the limit. Required for the
1192
+ ``limit(expr, v, a)`` syntax. Must be convertible to a symbolic
1193
+ variable.
1194
+ - ``a`` -- The value the variable approaches. Required for the
1195
+ ``limit(expr, v, a)`` syntax. Must be convertible to a symbolic
1196
+ expression.
1197
+ - ``dir`` -- (default: ``None``) direction for the limit:
1198
+ ``'plus'`` (or ``'+'`` or ``'right'`` or ``'above'``) for a limit from above,
1199
+ ``'minus'`` (or ``'-'`` or ``'left'`` or ``'below'``) for a limit from below.
1200
+ Omitted (``None``) implies a two-sided limit.
1201
+ - ``taylor`` -- (default: ``False``) if ``True``, use Taylor
1202
+ series via Maxima (may handle more cases but potentially less stable).
1203
+ Setting this automatically uses the ``'maxima_taylor'`` algorithm.
1204
+ - ``algorithm`` -- (default: ``'maxima'``) the backend algorithm to use.
1205
+ Options include ``'maxima'``, ``'maxima_taylor'``, ``'sympy'``,
1206
+ ``'giac'``, ``'fricas'``, ``'mathematica_free'``.
1207
+ - ``**kwargs`` -- (optional) single named parameter. Required for the
1208
+ ``limit(expr, v=a)`` syntax to specify variable and limit point.
1209
+
1210
+ .. NOTE::
1211
+
1212
+ The output may also use ``und`` (undefined), ``ind``
1213
+ (indefinite but bounded), and ``infinity`` (complex
1214
+ infinity).
1215
+
1216
+ EXAMPLES::
1217
+
1218
+ sage: x = var('x')
1219
+ sage: f = (1 + 1/x)^x
1220
+ sage: limit(f, x=oo)
1221
+ e
1222
+ sage: limit(f, x, oo)
1223
+ e
1224
+ sage: f.limit(x=5)
1225
+ 7776/3125
1226
+ sage: f.limit(x, 5)
1227
+ 7776/3125
1228
+
1229
+ The positional ``limit(expr, v, a)`` syntax is particularly useful
1230
+ when the limit variable ``v`` is an indexed variable or another
1231
+ expression that cannot be used as a keyword argument
1232
+ (fixes :issue:`38761`)::
1233
+
1234
+ sage: y = var('y', n=3)
1235
+ sage: g = sum(y); g
1236
+ y0 + y1 + y2
1237
+ sage: limit(g, y[1], 1)
1238
+ y0 + y2 + 1
1239
+ sage: g.limit(y[0], 5)
1240
+ y1 + y2 + 5
1241
+ sage: limit(y[0]^2 + y[1], y[0], y[2]) # Limit as y0 -> y2
1242
+ y2^2 + y1
1243
+
1244
+ Directional limits work with both syntaxes::
1245
+
1246
+ sage: limit(1/x, x, 0, dir='+')
1247
+ +Infinity
1248
+ sage: limit(1/x, x=0, dir='-')
1249
+ -Infinity
1250
+ sage: limit(exp(-1/x), x, 0, dir='left')
1251
+ +Infinity
1252
+
1253
+ Using different algorithms::
1254
+
1255
+ sage: limit(sin(x)/x, x, 0, algorithm='sympy')
1256
+ 1
1257
+ sage: limit(abs(x)/x, x, 0, algorithm='giac') # needs sage.libs.giac # Two-sided limit -> undefined
1258
+ und
1259
+ sage: limit(x^x, x, 0, dir='+', algorithm='fricas') # optional - fricas
1260
+ 1
1261
+
1262
+ Using Taylor series (can sometimes handle more complex limits)::
1263
+
1264
+ sage: limit((cos(x)-1)/x^2, x, 0, taylor=True)
1265
+ -1/2
1266
+
1267
+ Error handling for incorrect syntax::
1268
+
1269
+ sage: limit(sin(x)/x, x=0, y=1) # Too many keyword args
1270
+ Traceback (most recent call last):
1271
+ ...
1272
+ ValueError: multiple keyword arguments specified
1273
+ sage: limit(sin(x)/x, x, 0, y=1) # Mixed positional (v,a) and keyword variable
1274
+ Traceback (most recent call last):
1275
+ ...
1276
+ ValueError: cannot mix positional specification of limit variable and point with keyword variable arguments
1277
+ sage: limit(sin(x)/x, x) # Not enough positional args
1278
+ Traceback (most recent call last):
1279
+ ...
1280
+ ValueError: three positional arguments (expr, v, a) or one positional and one keyword argument (expr, v=a) required
1281
+ sage: limit(sin(x)/x) # No variable specified
1282
+ Traceback (most recent call last):
1283
+ ...
1284
+ ValueError: invalid limit specification
1285
+ sage: limit(sin(x)/x, x, 0, x=0) # Mixing both syntaxes
1286
+ Traceback (most recent call last):
1287
+ ...
1288
+ ValueError: cannot mix positional specification of limit variable and point with keyword variable arguments
1289
+
1290
+ Domain to real, a regression in 5.46.0, see https://sf.net/p/maxima/bugs/4138 ::
1291
+
1292
+ sage: maxima_calculus.eval("domain:real")
1293
+ ...
1294
+ sage: f = (1 + 1/x)^x
1295
+ sage: f.limit(x=1.2).n()
1296
+ 2.06961575467...
1297
+ sage: maxima_calculus.eval("domain:complex");
1298
+ ...
1299
+
1300
+ Otherwise, it works ::
1301
+
1302
+ sage: f.limit(x=I, taylor=True)
1303
+ (-I + 1)^I
1304
+ sage: f(x=1.2)
1305
+ 2.0696157546720...
1306
+ sage: f(x=I)
1307
+ (-I + 1)^I
1308
+ sage: CDF(f(x=I))
1309
+ 2.0628722350809046 + 0.7450070621797239*I
1310
+ sage: CDF(f.limit(x=I))
1311
+ 2.0628722350809046 + 0.7450070621797239*I
1312
+
1313
+ Notice that Maxima may ask for more information::
1314
+
1315
+ sage: var('a')
1316
+ a
1317
+ sage: limit(x^a,x=0)
1318
+ Traceback (most recent call last):
1319
+ ...
1320
+ ValueError: Computation failed since Maxima requested additional
1321
+ constraints; using the 'assume' command before evaluation
1322
+ *may* help (example of legal syntax is 'assume(a>0)', see
1323
+ `assume?` for more details)
1324
+ Is a positive, negative or zero?
1325
+
1326
+ With this example, Maxima is looking for a LOT of information::
1327
+
1328
+ sage: assume(a>0)
1329
+ sage: limit(x^a,x=0) # random - maxima 5.46.0 does not need extra assumption
1330
+ Traceback (most recent call last):
1331
+ ...
1332
+ ValueError: Computation failed since Maxima requested additional
1333
+ constraints; using the 'assume' command before evaluation *may* help
1334
+ (example of legal syntax is 'assume(a>0)', see `assume?` for
1335
+ more details)
1336
+ Is a an integer?
1337
+ sage: assume(a,'integer')
1338
+ sage: limit(x^a, x=0) # random - maxima 5.46.0 does not need extra assumption
1339
+ Traceback (most recent call last):
1340
+ ...
1341
+ ValueError: Computation failed since Maxima requested additional
1342
+ constraints; using the 'assume' command before evaluation *may* help
1343
+ (example of legal syntax is 'assume(a>0)', see `assume?` for
1344
+ more details)
1345
+ Is a an even number?
1346
+ sage: assume(a, 'even')
1347
+ sage: limit(x^a, x=0)
1348
+ 0
1349
+ sage: forget()
1350
+
1351
+ More examples::
1352
+
1353
+ sage: limit(x*log(x), x=0, dir='+')
1354
+ 0
1355
+ sage: lim((x+1)^(1/x), x=0)
1356
+ e
1357
+ sage: lim(e^x/x, x=oo)
1358
+ +Infinity
1359
+ sage: lim(e^x/x, x=-oo)
1360
+ 0
1361
+ sage: lim(-e^x/x, x=oo)
1362
+ -Infinity
1363
+ sage: lim((cos(x))/(x^2), x=0)
1364
+ +Infinity
1365
+ sage: lim(sqrt(x^2+1) - x, x=oo)
1366
+ 0
1367
+ sage: lim(x^2/(sec(x)-1), x=0)
1368
+ 2
1369
+ sage: lim(cos(x)/(cos(x)-1), x=0)
1370
+ -Infinity
1371
+ sage: lim(x*sin(1/x), x=0)
1372
+ 0
1373
+ sage: limit(e^(-1/x), x=0, dir='right')
1374
+ 0
1375
+ sage: limit(e^(-1/x), x=0, dir='left')
1376
+ +Infinity
1377
+
1378
+ ::
1379
+
1380
+ sage: f = log(log(x)) / log(x)
1381
+ sage: forget(); assume(x < -2); lim(f, x=0, taylor=True)
1382
+ 0
1383
+ sage: forget()
1384
+
1385
+ Here ind means "indefinite but bounded"::
1386
+
1387
+ sage: lim(sin(1/x), x = 0)
1388
+ ind
1389
+
1390
+ We can use other packages than maxima, namely "sympy", "giac", "fricas".
1391
+
1392
+ With the standard package Giac::
1393
+
1394
+ sage: # needs sage.libs.giac
1395
+ sage: (exp(-x)/(2+sin(x))).limit(x=oo, algorithm='giac')
1396
+ 0
1397
+ sage: limit(e^(-1/x), x=0, dir='right', algorithm='giac')
1398
+ 0
1399
+ sage: limit(e^(-1/x), x=0, dir='left', algorithm='giac')
1400
+ +Infinity
1401
+ sage: (x / (x+2^x+cos(x))).limit(x=-infinity, algorithm='giac')
1402
+ 1
1403
+
1404
+ With the optional package FriCAS::
1405
+
1406
+ sage: (x / (x+2^x+cos(x))).limit(x=-infinity, algorithm='fricas') # optional - fricas
1407
+ 1
1408
+ sage: limit(e^(-1/x), x=0, dir='right', algorithm='fricas') # optional - fricas
1409
+ 0
1410
+ sage: limit(e^(-1/x), x=0, dir='left', algorithm='fricas') # optional - fricas
1411
+ +Infinity
1412
+
1413
+ One can also call Mathematica's online interface::
1414
+
1415
+ sage: limit(pi+log(x)/x,x=oo, algorithm='mathematica_free') # optional - internet
1416
+ pi
1417
+
1418
+ TESTS::
1419
+
1420
+ sage: lim(x^2, x=2, dir='nugget')
1421
+ Traceback (most recent call last):
1422
+ ...
1423
+ ValueError: dir must be one of None, 'plus', '+', 'above', 'right', 'minus', '-', 'below', 'left'
1424
+
1425
+ sage: x.limit(x=3, algorithm='nugget')
1426
+ Traceback (most recent call last):
1427
+ ...
1428
+ ValueError: Unknown algorithm: nugget
1429
+
1430
+ We check that :issue:`3718` is fixed, so that
1431
+ Maxima gives correct limits for the floor function::
1432
+
1433
+ sage: limit(floor(x), x=0, dir='-')
1434
+ -1
1435
+ sage: limit(floor(x), x=0, dir='+')
1436
+ 0
1437
+ sage: limit(floor(x), x=0)
1438
+ ...nd
1439
+
1440
+ Maxima gives the right answer here, too, showing
1441
+ that :issue:`4142` is fixed::
1442
+
1443
+ sage: f = sqrt(1 - x^2)
1444
+ sage: g = diff(f, x); g
1445
+ -x/sqrt(-x^2 + 1)
1446
+ sage: limit(g, x=1, dir='-')
1447
+ -Infinity
1448
+
1449
+ ::
1450
+
1451
+ sage: limit(1/x, x=0)
1452
+ Infinity
1453
+ sage: limit(1/x, x=0, dir='+')
1454
+ +Infinity
1455
+ sage: limit(1/x, x=0, dir='-')
1456
+ -Infinity
1457
+
1458
+ Check that :issue:`8942` is fixed::
1459
+
1460
+ sage: f(x) = (cos(pi/4 - x) - tan(x)) / (1 - sin(pi/4 + x))
1461
+ sage: limit(f(x), x=pi/4, dir='minus')
1462
+ +Infinity
1463
+ sage: limit(f(x), x=pi/4, dir='plus')
1464
+ -Infinity
1465
+ sage: limit(f(x), x=pi/4)
1466
+ Infinity
1467
+
1468
+ Check that :issue:`12708` is fixed::
1469
+
1470
+ sage: limit(tanh(x), x=0)
1471
+ 0
1472
+
1473
+ Check that :issue:`15386` is fixed::
1474
+
1475
+ sage: n = var('n')
1476
+ sage: assume(n>0)
1477
+ sage: sequence = -(3*n^2 + 1)*(-1)^n / sqrt(n^5 + 8*n^3 + 8)
1478
+ sage: limit(sequence, n=infinity)
1479
+ 0
1480
+ sage: forget() # Clean up assumption
1481
+
1482
+ Check if :issue:`23048` is fixed::
1483
+
1484
+ sage: (1/(x-3)).limit(x=3, dir='below')
1485
+ -Infinity
1486
+
1487
+ From :issue:`14677`::
1488
+
1489
+ sage: f = (x^x - sin(x)^sin(x)) / (x^3*log(x))
1490
+ sage: limit(f, x=0, algorithm='fricas') # optional - fricas
1491
+ und
1492
+
1493
+ sage: limit(f, x=0, dir='right', algorithm='fricas') # optional - fricas
1494
+ 1/6
1495
+
1496
+ From :issue:`26497`::
1497
+
1498
+ sage: mu, y, sigma = var("mu, y, sigma")
1499
+ sage: f = 1/2*sqrt(2)*e^(-1/2*(mu - log(y))^2/sigma^2)/(sqrt(pi)*sigma*y)
1500
+ sage: limit(f, y=0, algorithm='fricas') # optional - fricas
1501
+ 0
1502
+
1503
+ From :issue:`26060`::
1504
+
1505
+ sage: limit(x / (x + 2^x + cos(x)), x=-infinity)
1506
+ 1
1507
+
1508
+ # Added specific tests for argument parsing logic to ensure coverage
1509
+ sage: limit(x+1, x=1)
1510
+ 2
1511
+ sage: limit(x+1, x, 1)
1512
+ 2
1513
+ sage: limit(x+1, 'x', 1)
1514
+ 2
1515
+ sage: limit(x+1, v=x, a=1) # using v=, a= keywords triggers multiple keyword error
1516
+ Traceback (most recent call last):
1517
+ ...
1518
+ ValueError: multiple keyword arguments specified
1519
+ sage: limit(x+1, v=x, a=1, algorithm='sympy') # as above
1520
+ Traceback (most recent call last):
1521
+ ...
1522
+ ValueError: multiple keyword arguments specified
1523
+ sage: limit(x+1, x=1, algorithm='sympy')
1524
+ 2
1525
+ sage: limit(x+1, x, 1, algorithm='sympy')
1526
+ 2
1527
+
1528
+ # Test that var() is not called unnecessarily on symbolic input v
1529
+ sage: y = var('y', n=3)
1530
+ sage: limit(sum(y), y[1], 1) # Should work directly
1531
+ y0 + y2 + 1
1532
+
1533
+ # Test conversion of v if not symbolic
1534
+ sage: limit(x**2, 'x', 3)
1535
+ 9
1536
+ sage: y = var('y')
1537
+ sage: limit(x**2 + y, "y", x) # Need y=var('y') defined for this test
1538
+ x^2 + x
1539
+
1540
+ # Test conversion of a if not symbolic
1541
+ sage: limit(x**2, x, "3")
1542
+ 9
1543
+
1544
+ # Test using a constant number as variable 'v' fails
1545
+ sage: limit(x**2 + 5, 5, 10)
1546
+ Traceback (most recent call last):
1547
+ ...
1548
+ TypeError: limit variable must be a variable, not a constant
1549
+ """
1550
+ # Process expression
1551
+ if not isinstance(ex, Expression):
1552
+ ex = SR(ex)
1553
+
1554
+ # Argument parsing: Determining v and a based on syntax used
1555
+ v = None
1556
+ a = None
1557
+
1558
+ if len(args) == 2: # Syntax: limit(ex, v, a, ...)
1559
+ if kwargs: # Cannot mix positional v, a with keyword args
1560
+ raise ValueError("cannot mix positional specification of limit variable and point with keyword variable arguments")
1561
+ v = args[0]
1562
+ a = args[1]
1563
+ elif len(args) == 1:
1564
+ if kwargs:
1565
+ raise ValueError("cannot mix positional specification of limit variable and point with keyword variable arguments")
1566
+ else:
1567
+ raise ValueError("three positional arguments (expr, v, a) or one positional and one keyword argument (expr, v=a) required")
1568
+ elif len(args) == 0: # Potential syntax: limit(ex, v=a, ...) or limit(ex)
1569
+ if len(kwargs) == 1:
1570
+ k, = kwargs.keys()
1571
+ v = var(k)
1572
+ a = kwargs[k]
1573
+ elif len(kwargs) == 0: # For No variable specified at all
1574
+ raise ValueError("invalid limit specification")
1575
+ else: # For Multiple keyword arguments like x=1, y=2
1576
+ raise ValueError("multiple keyword arguments specified")
1577
+
1578
+ # Ensuring v is a symbolic expression and a valid limit variable
1579
+ if not isinstance(v, Expression):
1580
+ v = SR(v)
1581
+ if not v.is_symbol():
1582
+ raise TypeError("limit variable must be a variable, not a constant")
1583
+
1584
+ # Ensuring a is a symbolic expression
1585
+ if not isinstance(a, Expression):
1586
+ a = SR(a)
1587
+
1588
+ # Processing algorithm and direction options
1589
+ effective_algorithm = algorithm
1590
+ if taylor and algorithm == 'maxima':
1591
+ effective_algorithm = 'maxima_taylor'
1592
+
1593
+ dir_plus = ['plus', '+', 'above', 'right']
1594
+ dir_minus = ['minus', '-', 'below', 'left']
1595
+ dir_both = [None] + dir_plus + dir_minus
1596
+ if dir not in dir_both:
1597
+ raise ValueError("dir must be one of " + ", ".join(map(repr, dir_both)))
1598
+
1599
+ # Calling the appropriate backend based on effective_algorithm
1600
+ l = None
1601
+ if effective_algorithm == 'maxima':
1602
+ if dir is None:
1603
+ l = maxima.sr_limit(ex, v, a)
1604
+ elif dir in dir_plus:
1605
+ l = maxima.sr_limit(ex, v, a, 'plus')
1606
+ elif dir in dir_minus:
1607
+ l = maxima.sr_limit(ex, v, a, 'minus')
1608
+ elif effective_algorithm == 'maxima_taylor':
1609
+ if dir is None:
1610
+ l = maxima.sr_tlimit(ex, v, a)
1611
+ elif dir in dir_plus:
1612
+ l = maxima.sr_tlimit(ex, v, a, 'plus')
1613
+ elif dir in dir_minus:
1614
+ l = maxima.sr_tlimit(ex, v, a, 'minus')
1615
+ elif effective_algorithm == 'sympy':
1616
+ import sympy
1617
+ sympy_dir = '+-'
1618
+ if dir in dir_plus:
1619
+ sympy_dir = '+'
1620
+ elif dir in dir_minus:
1621
+ sympy_dir = '-'
1622
+ l = sympy.limit(ex._sympy_(), v._sympy_(), a._sympy_(), dir=sympy_dir)
1623
+ elif effective_algorithm == 'fricas':
1624
+ from sage.interfaces.fricas import fricas
1625
+ eq = fricas.equation(v._fricas_(), a._fricas_())
1626
+ f = ex._fricas_()
1627
+ fricas_dir_arg = None
1628
+ if dir in dir_plus:
1629
+ fricas_dir_arg = '"right"'
1630
+ elif dir in dir_minus:
1631
+ fricas_dir_arg = '"left"'
1632
+
1633
+ if fricas_dir_arg:
1634
+ l = fricas.limit(f, eq, fricas_dir_arg).sage()
1635
+ else:
1636
+ l_raw = fricas.limit(f, eq).sage()
1637
+ if isinstance(l_raw, dict):
1638
+ l = SR('und')
1639
+ else:
1640
+ l = l_raw
1641
+ elif effective_algorithm == 'giac':
1642
+ from sage.libs.giac.giac import libgiac
1643
+ giac_v = v._giac_init_()
1644
+ giac_a = a._giac_init_()
1645
+ giac_dir_arg = 0 # Default for two-sided
1646
+ if dir in dir_plus:
1647
+ giac_dir_arg = 1
1648
+ elif dir in dir_minus:
1649
+ giac_dir_arg = -1
1650
+ l = libgiac.limit(ex, giac_v, giac_a, giac_dir_arg).sage()
1651
+ elif effective_algorithm == 'mathematica_free':
1652
+ # Ensuring mma_free_limit exists
1653
+ l = mma_free_limit(ex, v, a, dir)
1654
+ else:
1655
+ raise ValueError("Unknown algorithm: %s" % effective_algorithm)
1656
+
1657
+ original_parent = ex.parent()
1658
+
1659
+ return original_parent(l)
1660
+
1661
+
1662
+ # lim is alias for limit
1663
+ lim = limit
1664
+
1665
+
1666
+ def mma_free_limit(expression, v, a, dir=None):
1667
+ """
1668
+ Limit using Mathematica's online interface.
1669
+
1670
+ INPUT:
1671
+
1672
+ - ``expression`` -- symbolic expression
1673
+ - ``v`` -- variable
1674
+ - ``a`` -- value where the variable goes to
1675
+ - ``dir`` -- ``'+'``, ``'-'`` or ``None`` (default: ``None``)
1676
+
1677
+ EXAMPLES::
1678
+
1679
+ sage: from sage.calculus.calculus import mma_free_limit
1680
+ sage: mma_free_limit(sin(x)/x, x, a=0) # optional - internet
1681
+ 1
1682
+
1683
+ Another simple limit::
1684
+
1685
+ sage: mma_free_limit(e^(-x), x, a=oo) # optional - internet
1686
+ 0
1687
+ """
1688
+ from sage.interfaces.mathematica import request_wolfram_alpha, parse_moutput_from_json, symbolic_expression_from_mathematica_string
1689
+ dir_plus = ['plus', '+', 'above', 'right']
1690
+ dir_minus = ['minus', '-', 'below', 'left']
1691
+ math_expr = expression._mathematica_init_()
1692
+ variable = v._mathematica_init_()
1693
+ a = a._mathematica_init_()
1694
+ if dir is None:
1695
+ input = "Limit[{},{} -> {}]".format(math_expr, variable, a)
1696
+ elif dir in dir_plus:
1697
+ dir = 'Direction -> "FromAbove"'
1698
+ input = "Limit[{}, {} -> {}, {}]".format(math_expr, variable, a, dir)
1699
+ elif dir in dir_minus:
1700
+ dir = 'Direction -> "FromBelow"'
1701
+ input = "Limit[{}, {} -> {}, {}]".format(math_expr, variable, a, dir)
1702
+ else:
1703
+ raise ValueError('wrong input for limit')
1704
+ json_page_data = request_wolfram_alpha(input)
1705
+ all_outputs = parse_moutput_from_json(json_page_data)
1706
+ if not all_outputs:
1707
+ raise ValueError("no outputs found in the answer from Wolfram Alpha")
1708
+ first_output = all_outputs[0]
1709
+ return symbolic_expression_from_mathematica_string(first_output)
1710
+
1711
+
1712
+ ###################################################################
1713
+ # Laplace transform
1714
+ ###################################################################
1715
+ def laplace(ex, t, s, algorithm='maxima'):
1716
+ r"""
1717
+ Return the Laplace transform with respect to the variable `t` and
1718
+ transform parameter `s`, if possible.
1719
+
1720
+ If this function cannot find a solution, a formal function is returned.
1721
+ The function that is returned may be viewed as a function of `s`.
1722
+
1723
+ DEFINITION:
1724
+
1725
+ The Laplace transform of a function `f(t)`, defined for all real numbers
1726
+ `t \geq 0`, is the function `F(s)` defined by
1727
+
1728
+ .. MATH::
1729
+
1730
+ F(s) = \int_{0}^{\infty} e^{-st} f(t) dt.
1731
+
1732
+ INPUT:
1733
+
1734
+ - ``ex`` -- a symbolic expression
1735
+
1736
+ - ``t`` -- independent variable
1737
+
1738
+ - ``s`` -- transform parameter
1739
+
1740
+ - ``algorithm`` -- (default: ``'maxima'``) one of
1741
+
1742
+ - ``'maxima'`` -- use Maxima (the default)
1743
+
1744
+ - ``'sympy'`` -- use SymPy
1745
+
1746
+ - ``'giac'`` -- use Giac (optional)
1747
+
1748
+ .. NOTE::
1749
+
1750
+ The ``'sympy'`` algorithm returns the tuple (`F`, `a`, ``cond``)
1751
+ where `F` is the Laplace transform of `f(t)`,
1752
+ `Re(s)>a` is the half-plane of convergence, and ``cond`` are
1753
+ auxiliary convergence conditions.
1754
+
1755
+ .. SEEALSO::
1756
+
1757
+ :func:`inverse_laplace`
1758
+
1759
+ EXAMPLES:
1760
+
1761
+ We compute a few Laplace transforms::
1762
+
1763
+ sage: var('x, s, z, t, t0')
1764
+ (x, s, z, t, t0)
1765
+ sage: sin(x).laplace(x, s)
1766
+ 1/(s^2 + 1)
1767
+ sage: (z + exp(x)).laplace(x, s)
1768
+ z/s + 1/(s - 1)
1769
+ sage: log(t/t0).laplace(t, s)
1770
+ -(euler_gamma + log(s) + log(t0))/s
1771
+
1772
+ We do a formal calculation::
1773
+
1774
+ sage: f = function('f')(x)
1775
+ sage: g = f.diff(x); g
1776
+ diff(f(x), x)
1777
+ sage: g.laplace(x, s)
1778
+ s*laplace(f(x), x, s) - f(0)
1779
+
1780
+ A BATTLE BETWEEN the X-women and the Y-men (by David
1781
+ Joyner): Solve
1782
+
1783
+ .. MATH::
1784
+
1785
+ x' = -16y, x(0)=270, y' = -x + 1, y(0) = 90.
1786
+
1787
+ This models a fight between two sides, the "X-women" and the
1788
+ "Y-men", where the X-women have 270 initially and the Y-men have
1789
+ 90, but the Y-men are better at fighting, because of the higher
1790
+ factor of "-16" vs "-1", and also get an occasional reinforcement,
1791
+ because of the "+1" term.
1792
+
1793
+ ::
1794
+
1795
+ sage: var('t')
1796
+ t
1797
+ sage: t = var('t')
1798
+ sage: x = function('x')(t)
1799
+ sage: y = function('y')(t)
1800
+ sage: de1 = x.diff(t) + 16*y
1801
+ sage: de2 = y.diff(t) + x - 1
1802
+ sage: de1.laplace(t, s)
1803
+ s*laplace(x(t), t, s) + 16*laplace(y(t), t, s) - x(0)
1804
+ sage: de2.laplace(t, s)
1805
+ s*laplace(y(t), t, s) - 1/s + laplace(x(t), t, s) - y(0)
1806
+
1807
+ Next we form the augmented matrix of the above system::
1808
+
1809
+ sage: A = matrix([[s, 16, 270], [1, s, 90+1/s]])
1810
+ sage: E = A.echelon_form()
1811
+ sage: xt = E[0,2].inverse_laplace(s,t)
1812
+ sage: yt = E[1,2].inverse_laplace(s,t)
1813
+ sage: xt
1814
+ -91/2*e^(4*t) + 629/2*e^(-4*t) + 1
1815
+ sage: yt
1816
+ 91/8*e^(4*t) + 629/8*e^(-4*t)
1817
+ sage: p1 = plot(xt, 0, 1/2, rgbcolor=(1,0,0)) # needs sage.plot
1818
+ sage: p2 = plot(yt, 0, 1/2, rgbcolor=(0,1,0)) # needs sage.plot
1819
+ sage: import tempfile
1820
+ sage: with tempfile.NamedTemporaryFile(suffix='.png') as f: # needs sage.plot
1821
+ ....: (p1 + p2).save(f.name)
1822
+
1823
+ Another example::
1824
+
1825
+ sage: var('a,s,t')
1826
+ (a, s, t)
1827
+ sage: f = exp (2*t + a) * sin(t) * t; f
1828
+ t*e^(a + 2*t)*sin(t)
1829
+ sage: L = laplace(f, t, s); L
1830
+ 2*(s - 2)*e^a/(s^2 - 4*s + 5)^2
1831
+ sage: inverse_laplace(L, s, t)
1832
+ t*e^(a + 2*t)*sin(t)
1833
+
1834
+ The Laplace transform of the exponential function::
1835
+
1836
+ sage: laplace(exp(x), x, s)
1837
+ 1/(s - 1)
1838
+
1839
+ Dirac's delta distribution is handled (the output of SymPy is
1840
+ related to a choice that has to be made when defining Laplace
1841
+ transforms of distributions)::
1842
+
1843
+ sage: laplace(dirac_delta(t), t, s)
1844
+ 1
1845
+ sage: F, a, cond = laplace(dirac_delta(t), t, s, algorithm='sympy')
1846
+ sage: a, cond # random - sympy <1.10 gives (-oo, True)
1847
+ (0, True)
1848
+ sage: F # random - sympy <1.9 includes undefined heaviside(0) in answer
1849
+ 1
1850
+ sage: laplace(dirac_delta(t), t, s, algorithm='giac') # needs giac
1851
+ 1
1852
+
1853
+ Heaviside step function can be handled with different interfaces.
1854
+ Try with Maxima::
1855
+
1856
+ sage: laplace(heaviside(t-1), t, s)
1857
+ e^(-s)/s
1858
+
1859
+ Try with giac, if it is installed::
1860
+
1861
+ sage: # needs giac
1862
+ sage: laplace(heaviside(t-1), t, s, algorithm='giac')
1863
+ e^(-s)/s
1864
+
1865
+ Try with SymPy::
1866
+
1867
+ sage: laplace(heaviside(t-1), t, s, algorithm='sympy')
1868
+ (e^(-s)/s, 0, True)
1869
+
1870
+ TESTS:
1871
+
1872
+ Testing Giac::
1873
+
1874
+ sage: # needs giac
1875
+ sage: var('t, s')
1876
+ (t, s)
1877
+ sage: laplace(5*cos(3*t-2)*heaviside(t-2), t, s, algorithm='giac')
1878
+ 5*(s*cos(4)*e^(-2*s) - 3*e^(-2*s)*sin(4))/(s^2 + 9)
1879
+
1880
+ Check unevaluated expression from Giac (it is locale-dependent, see
1881
+ :issue:`22833`)::
1882
+
1883
+ sage: # needs giac
1884
+ sage: n = SR.var('n')
1885
+ sage: laplace(t^n, t, s, algorithm='giac')
1886
+ laplace(t^n, t, s)
1887
+
1888
+ Testing SymPy::
1889
+
1890
+ sage: n = SR.var('n')
1891
+ sage: F, a, cond = laplace(t^n, t, s, algorithm='sympy')
1892
+ sage: a, cond
1893
+ (0, re(n) > -1)
1894
+ sage: F.simplify()
1895
+ s^(-n - 1)*gamma(n + 1)
1896
+
1897
+
1898
+ Testing Maxima::
1899
+ sage: n = SR.var('n')
1900
+ sage: assume(n > -1)
1901
+ sage: laplace(t^n, t, s, algorithm='maxima')
1902
+ s^(-n - 1)*gamma(n + 1)
1903
+
1904
+ Check that :issue:`24212` is fixed::
1905
+
1906
+ sage: F, a, cond = laplace(cos(t^2), t, s, algorithm='sympy')
1907
+ sage: a, cond
1908
+ (0, True)
1909
+ sage: F._sympy_().simplify()
1910
+ sqrt(pi)*(sqrt(2)*sin(s**2/4)*fresnelc(sqrt(2)*s/(2*sqrt(pi))) -
1911
+ sqrt(2)*cos(s**2/4)*fresnels(sqrt(2)*s/(2*sqrt(pi))) + cos(s**2/4 + pi/4))/2
1912
+
1913
+ Testing result from SymPy that Sage doesn't know how to handle::
1914
+
1915
+ sage: laplace(cos(-1/t), t, s, algorithm='sympy')
1916
+ Traceback (most recent call last):
1917
+ ...
1918
+ AttributeError: Unable to convert SymPy result (=meijerg(((), ()), ((-1/2, 0, 1/2), (0,)), ...)/4) into Sage
1919
+ """
1920
+ if not isinstance(ex, (Expression, Function)):
1921
+ ex = SR(ex)
1922
+
1923
+ if algorithm == 'maxima':
1924
+ return ex.parent()(ex._maxima_().laplace(var(t), var(s)))
1925
+
1926
+ elif algorithm == 'sympy':
1927
+ ex_sy, t, s = (expr._sympy_() for expr in (ex, t, s))
1928
+ from sympy import laplace_transform
1929
+ from sage.interfaces.sympy import sympy_init
1930
+ sympy_init()
1931
+ result = laplace_transform(ex_sy, t, s)
1932
+ if isinstance(result, tuple):
1933
+ try:
1934
+ (result, a, cond) = result
1935
+ return result._sage_(), a, cond
1936
+ except AttributeError:
1937
+ raise AttributeError("Unable to convert SymPy result (={}) into"
1938
+ " Sage".format(result))
1939
+ elif 'LaplaceTransform' in format(result):
1940
+ return dummy_laplace(ex, t, s)
1941
+ else:
1942
+ return result
1943
+
1944
+ elif algorithm == 'giac':
1945
+ from sage.interfaces.giac import giac
1946
+ try:
1947
+ result = giac.laplace(ex, t, s)
1948
+ except TypeError:
1949
+ raise ValueError("Giac cannot make sense of: %s" % ex)
1950
+ if 'integrate' in format(result) or 'integration' in format(result):
1951
+ return dummy_laplace(ex, t, s)
1952
+ else:
1953
+ return result.sage()
1954
+
1955
+ else:
1956
+ raise ValueError("Unknown algorithm: %s" % algorithm)
1957
+
1958
+
1959
+ def inverse_laplace(ex, s, t, algorithm='maxima'):
1960
+ r"""
1961
+ Return the inverse Laplace transform with respect to the variable `t` and
1962
+ transform parameter `s`, if possible.
1963
+
1964
+ If this function cannot find a solution, a formal function is returned.
1965
+ The function that is returned may be viewed as a function of `t`.
1966
+
1967
+ DEFINITION:
1968
+
1969
+ The inverse Laplace transform of a function `F(s)` is the function
1970
+ `f(t)`, defined by
1971
+
1972
+ .. MATH::
1973
+
1974
+ f(t) = \frac{1}{2\pi i} \int_{\gamma-i\infty}^{\gamma + i\infty} e^{st} F(s) ds,
1975
+
1976
+ where `\gamma` is chosen so that the contour path of
1977
+ integration is in the region of convergence of `F(s)`.
1978
+
1979
+ INPUT:
1980
+
1981
+ - ``ex`` -- a symbolic expression
1982
+
1983
+ - ``s`` -- transform parameter
1984
+
1985
+ - ``t`` -- independent variable
1986
+
1987
+ - ``algorithm`` -- (default: ``'maxima'``) one of
1988
+
1989
+ - ``'maxima'`` -- use Maxima (the default)
1990
+
1991
+ - ``'sympy'`` -- use SymPy
1992
+
1993
+ - ``'giac'`` -- use Giac (optional)
1994
+
1995
+ .. SEEALSO::
1996
+
1997
+ :func:`laplace`
1998
+
1999
+ EXAMPLES::
2000
+
2001
+ sage: var('w, m')
2002
+ (w, m)
2003
+ sage: f = (1/(w^2+10)).inverse_laplace(w, m); f
2004
+ 1/10*sqrt(10)*sin(sqrt(10)*m)
2005
+ sage: laplace(f, m, w)
2006
+ 1/(w^2 + 10)
2007
+
2008
+ sage: f(t) = t*cos(t)
2009
+ sage: s = var('s')
2010
+ sage: L = laplace(f, t, s); L
2011
+ t |--> 2*s^2/(s^2 + 1)^2 - 1/(s^2 + 1)
2012
+ sage: inverse_laplace(L, s, t)
2013
+ t |--> t*cos(t)
2014
+ sage: inverse_laplace(1/(s^3+1), s, t)
2015
+ 1/3*(sqrt(3)*sin(1/2*sqrt(3)*t) - cos(1/2*sqrt(3)*t))*e^(1/2*t) + 1/3*e^(-t)
2016
+
2017
+ No explicit inverse Laplace transform, so one is returned formally a
2018
+ function ``ilt``::
2019
+
2020
+ sage: inverse_laplace(cos(s), s, t)
2021
+ ilt(cos(s), s, t)
2022
+
2023
+ Transform an expression involving a time-shift, via SymPy::
2024
+
2025
+ sage: inverse_laplace(1/s^2*exp(-s), s, t, algorithm='sympy').simplify()
2026
+ (t - 1)*heaviside(t - 1)
2027
+
2028
+ The same instance with Giac::
2029
+
2030
+ sage: # needs giac
2031
+ sage: inverse_laplace(1/s^2*exp(-s), s, t, algorithm='giac')
2032
+ (t - 1)*heaviside(t - 1)
2033
+
2034
+ Transform a rational expression::
2035
+
2036
+ sage: # needs giac
2037
+ sage: inverse_laplace((2*s^2*exp(-2*s) - exp(-s))/(s^3+1), s, t,
2038
+ ....: algorithm='giac')
2039
+ -1/3*(sqrt(3)*e^(1/2*t - 1/2)*sin(1/2*sqrt(3)*(t - 1))
2040
+ - cos(1/2*sqrt(3)*(t - 1))*e^(1/2*t - 1/2) + e^(-t + 1))*heaviside(t - 1)
2041
+ + 2/3*(2*cos(1/2*sqrt(3)*(t - 2))*e^(1/2*t - 1) + e^(-t + 2))*heaviside(t - 2)
2042
+
2043
+ sage: inverse_laplace(1/(s - 1), s, x)
2044
+ e^x
2045
+
2046
+ The inverse Laplace transform of a constant is a delta
2047
+ distribution::
2048
+
2049
+ sage: inverse_laplace(1, s, t)
2050
+ dirac_delta(t)
2051
+ sage: inverse_laplace(1, s, t, algorithm='sympy')
2052
+ dirac_delta(t)
2053
+ sage: inverse_laplace(1, s, t, algorithm='giac') # needs giac
2054
+ dirac_delta(t)
2055
+
2056
+ TESTS:
2057
+
2058
+ Testing unevaluated expression from Maxima::
2059
+
2060
+ sage: var('t, s')
2061
+ (t, s)
2062
+ sage: inverse_laplace(exp(-s)/s, s, t)
2063
+ ilt(e^(-s)/s, s, t)
2064
+
2065
+ Testing Giac::
2066
+
2067
+ sage: # needs giac
2068
+ sage: inverse_laplace(exp(-s)/s, s, t, algorithm='giac')
2069
+ heaviside(t - 1)
2070
+
2071
+ Testing SymPy::
2072
+
2073
+ sage: inverse_laplace(exp(-s)/s, s, t, algorithm='sympy')
2074
+ heaviside(t - 1)
2075
+
2076
+ Testing unevaluated expression from Giac::
2077
+
2078
+ sage: # needs giac
2079
+ sage: n = SR.var('n')
2080
+ sage: inverse_laplace(1/s^n, s, t, algorithm='giac')
2081
+ ilt(1/(s^n), t, s)
2082
+
2083
+ Try with Maxima::
2084
+
2085
+ sage: n = SR.var('n')
2086
+ sage: inverse_laplace(1/s^n, s, t, algorithm='maxima')
2087
+ ilt(1/(s^n), s, t)
2088
+
2089
+ Try with SymPy::
2090
+
2091
+ sage: inverse_laplace(1/s^n, s, t, algorithm='sympy')
2092
+ t^(n - 1)*heaviside(t)/gamma(n)
2093
+
2094
+ Testing unevaluated expression from SymPy::
2095
+
2096
+ sage: inverse_laplace(cos(s), s, t, algorithm='sympy')
2097
+ ilt(cos(s), t, s)
2098
+
2099
+ Testing the same with Giac::
2100
+
2101
+ sage: # needs giac
2102
+ sage: inverse_laplace(cos(s), s, t, algorithm='giac')
2103
+ ilt(cos(s), t, s)
2104
+ """
2105
+ if not isinstance(ex, Expression):
2106
+ ex = SR(ex)
2107
+
2108
+ if algorithm == 'maxima':
2109
+ return ex.parent()(ex._maxima_().ilt(var(s), var(t)))
2110
+
2111
+ elif algorithm == 'sympy':
2112
+ ex_sy, s, t = (expr._sympy_() for expr in (ex, s, t))
2113
+ from sympy import inverse_laplace_transform
2114
+ from sage.interfaces.sympy import sympy_init
2115
+ sympy_init()
2116
+ result = inverse_laplace_transform(ex_sy, s, t)
2117
+ try:
2118
+ return result._sage_()
2119
+ except AttributeError:
2120
+ if 'InverseLaplaceTransform' in format(result):
2121
+ return dummy_inverse_laplace(ex, t, s)
2122
+ else:
2123
+ raise AttributeError("Unable to convert SymPy result (={}) into"
2124
+ " Sage".format(result))
2125
+
2126
+ elif algorithm == 'giac':
2127
+ from sage.interfaces.giac import giac
2128
+ try:
2129
+ result = giac.invlaplace(ex, s, t)
2130
+ except TypeError:
2131
+ raise ValueError("Giac cannot make sense of: %s" % ex)
2132
+ if 'ilaplace' in format(result):
2133
+ return dummy_inverse_laplace(ex, t, s)
2134
+ else:
2135
+ return result.sage()
2136
+
2137
+ else:
2138
+ raise ValueError("Unknown algorithm: %s" % algorithm)
2139
+
2140
+
2141
+ ###################################################################
2142
+ # symbolic evaluation "at" a point
2143
+ ###################################################################
2144
+ def at(ex, *args, **kwds):
2145
+ """
2146
+ Parses ``at`` formulations from other systems, such as Maxima.
2147
+ Replaces evaluation 'at' a point with substitution method of
2148
+ a symbolic expression.
2149
+
2150
+ EXAMPLES:
2151
+
2152
+ We do not import ``at`` at the top level, but we can use it
2153
+ as a synonym for substitution if we import it::
2154
+
2155
+ sage: g = x^3 - 3
2156
+ sage: from sage.calculus.calculus import at
2157
+ sage: at(g, x=1)
2158
+ -2
2159
+ sage: g.subs(x=1)
2160
+ -2
2161
+
2162
+ We find a formal Taylor expansion::
2163
+
2164
+ sage: h,x = var('h,x')
2165
+ sage: u = function('u')
2166
+ sage: u(x + h)
2167
+ u(h + x)
2168
+ sage: diff(u(x+h), x)
2169
+ D[0](u)(h + x)
2170
+ sage: taylor(u(x+h), h, 0, 4)
2171
+ 1/24*h^4*diff(u(x), x, x, x, x) + 1/6*h^3*diff(u(x), x, x, x)
2172
+ + 1/2*h^2*diff(u(x), x, x) + h*diff(u(x), x) + u(x)
2173
+
2174
+ We compute a Laplace transform::
2175
+
2176
+ sage: var('s,t')
2177
+ (s, t)
2178
+ sage: f = function('f')(t)
2179
+ sage: f.diff(t, 2)
2180
+ diff(f(t), t, t)
2181
+ sage: f.diff(t,2).laplace(t,s)
2182
+ s^2*laplace(f(t), t, s) - s*f(0) - D[0](f)(0)
2183
+
2184
+ We can also accept a non-keyword list of expression substitutions,
2185
+ like Maxima does (:issue:`12796`)::
2186
+
2187
+ sage: from sage.calculus.calculus import at
2188
+ sage: f = function('f')
2189
+ sage: at(f(x), [x == 1])
2190
+ f(1)
2191
+
2192
+ TESTS:
2193
+
2194
+ Our one non-keyword argument must be a list::
2195
+
2196
+ sage: from sage.calculus.calculus import at
2197
+ sage: f = function('f')
2198
+ sage: at(f(x), x == 1)
2199
+ Traceback (most recent call last):
2200
+ ...
2201
+ TypeError: at can take at most one argument, which must be a list
2202
+
2203
+ We should convert our first argument to a symbolic expression::
2204
+
2205
+ sage: from sage.calculus.calculus import at
2206
+ sage: at(int(1), x=1)
2207
+ 1
2208
+ """
2209
+ if not isinstance(ex, (Expression, Function)):
2210
+ ex = SR(ex)
2211
+ kwds = {(k[10:] if k[:10] == "_SAGE_VAR_" else k): v
2212
+ for k, v in kwds.items()}
2213
+ if len(args) == 1 and isinstance(args[0], list):
2214
+ for c in args[0]:
2215
+ kwds[str(c.lhs())] = c.rhs()
2216
+ elif args:
2217
+ raise TypeError("at can take at most one argument, which must be a list")
2218
+
2219
+ return ex.subs(**kwds)
2220
+
2221
+
2222
+ def dummy_diff(*args):
2223
+ """
2224
+ This function is called when 'diff' appears in a Maxima string.
2225
+
2226
+ EXAMPLES::
2227
+
2228
+ sage: from sage.calculus.calculus import dummy_diff
2229
+ sage: x,y = var('x,y')
2230
+ sage: dummy_diff(sin(x*y), x, SR(2), y, SR(1))
2231
+ -x*y^2*cos(x*y) - 2*y*sin(x*y)
2232
+
2233
+ Here the function is used implicitly::
2234
+
2235
+ sage: a = var('a')
2236
+ sage: f = function('cr')(a)
2237
+ sage: g = f.diff(a); g
2238
+ diff(cr(a), a)
2239
+ """
2240
+ f = args[0]
2241
+ args = list(args[1:])
2242
+ for i in range(1, len(args), 2):
2243
+ args[i] = Integer(args[i])
2244
+ return f.diff(*args)
2245
+
2246
+
2247
+ def dummy_integrate(*args):
2248
+ """
2249
+ This function is called to create formal wrappers of integrals that
2250
+ Maxima can't compute:
2251
+
2252
+ EXAMPLES::
2253
+
2254
+ sage: from sage.calculus.calculus import dummy_integrate
2255
+ sage: f = function('f')
2256
+ sage: dummy_integrate(f(x), x)
2257
+ integrate(f(x), x)
2258
+ sage: a,b = var('a,b')
2259
+ sage: dummy_integrate(f(x), x, a, b)
2260
+ integrate(f(x), x, a, b)
2261
+ """
2262
+ if len(args) == 4:
2263
+ return definite_integral(*args, hold=True)
2264
+ else:
2265
+ return indefinite_integral(*args, hold=True)
2266
+
2267
+
2268
+ def dummy_laplace(*args):
2269
+ """
2270
+ This function is called to create formal wrappers of laplace transforms
2271
+ that Maxima can't compute:
2272
+
2273
+ EXAMPLES::
2274
+
2275
+ sage: from sage.calculus.calculus import dummy_laplace
2276
+ sage: s,t = var('s,t')
2277
+ sage: f = function('f')
2278
+ sage: dummy_laplace(f(t), t, s)
2279
+ laplace(f(t), t, s)
2280
+ """
2281
+ return _laplace(args[0], var(repr(args[1])), var(repr(args[2])))
2282
+
2283
+
2284
+ def dummy_inverse_laplace(*args):
2285
+ """
2286
+ This function is called to create formal wrappers of inverse Laplace
2287
+ transforms that Maxima can't compute:
2288
+
2289
+ EXAMPLES::
2290
+
2291
+ sage: from sage.calculus.calculus import dummy_inverse_laplace
2292
+ sage: s,t = var('s,t')
2293
+ sage: F = function('F')
2294
+ sage: dummy_inverse_laplace(F(s), s, t)
2295
+ ilt(F(s), s, t)
2296
+ """
2297
+ return _inverse_laplace(args[0], var(repr(args[1])), var(repr(args[2])))
2298
+
2299
+
2300
+ def dummy_pochhammer(*args):
2301
+ """
2302
+ This function is called to create formal wrappers of Pochhammer symbols.
2303
+
2304
+ EXAMPLES::
2305
+
2306
+ sage: from sage.calculus.calculus import dummy_pochhammer
2307
+ sage: s,t = var('s,t')
2308
+ sage: dummy_pochhammer(s, t)
2309
+ gamma(s + t)/gamma(s)
2310
+ """
2311
+ x, y = args
2312
+ from sage.functions.gamma import gamma
2313
+ return gamma(x + y) / gamma(x)
2314
+
2315
+
2316
+ #######################################################
2317
+ #
2318
+ # Helper functions for printing latex expression
2319
+ #
2320
+ #######################################################
2321
+
2322
+ def _laplace_latex_(self, *args):
2323
+ r"""
2324
+ Return LaTeX expression for Laplace transform of a symbolic function.
2325
+
2326
+ EXAMPLES::
2327
+
2328
+ sage: from sage.calculus.calculus import _laplace_latex_
2329
+ sage: var('s,t')
2330
+ (s, t)
2331
+ sage: f = function('f')(t)
2332
+ sage: _laplace_latex_(0,f,t,s)
2333
+ '\\mathcal{L}\\left(f\\left(t\\right), t, s\\right)'
2334
+ sage: latex(laplace(f, t, s))
2335
+ \mathcal{L}\left(f\left(t\right), t, s\right)
2336
+ """
2337
+ return "\\mathcal{L}\\left(%s\\right)" % (', '.join(latex(x) for x in args))
2338
+
2339
+
2340
+ def _inverse_laplace_latex_(self, *args):
2341
+ r"""
2342
+ Return LaTeX expression for inverse Laplace transform
2343
+ of a symbolic function.
2344
+
2345
+ EXAMPLES::
2346
+
2347
+ sage: from sage.calculus.calculus import _inverse_laplace_latex_
2348
+ sage: var('s,t')
2349
+ (s, t)
2350
+ sage: F = function('F')(s)
2351
+ sage: _inverse_laplace_latex_(0,F,s,t)
2352
+ '\\mathcal{L}^{-1}\\left(F\\left(s\\right), s, t\\right)'
2353
+ sage: latex(inverse_laplace(F,s,t))
2354
+ \mathcal{L}^{-1}\left(F\left(s\right), s, t\right)
2355
+ """
2356
+ return "\\mathcal{L}^{-1}\\left(%s\\right)" % (', '.join(latex(x) for x in args))
2357
+
2358
+
2359
+ # Return un-evaluated expression as instances of NewSymbolicFunction
2360
+ _laplace = function_factory('laplace', print_latex_func=_laplace_latex_)
2361
+ _inverse_laplace = function_factory('ilt',
2362
+ print_latex_func=_inverse_laplace_latex_)
2363
+
2364
+ ######################################i################
2365
+
2366
+
2367
+ # Conversion dict for special maxima objects
2368
+ # c,k1,k2 are from ode2()
2369
+ symtable = {'%pi': 'pi', '%e': 'e', '%i': 'I',
2370
+ '%gamma': 'euler_gamma',
2371
+ '%c': '_C', '%k1': '_K1', '%k2': '_K2',
2372
+ 'e': '_e', 'i': '_i', 'I': '_I'}
2373
+
2374
+
2375
+ maxima_qp = re.compile(r"\?\%[\w]*") # e.g., ?%jacobi_cd
2376
+
2377
+ maxima_var = re.compile(r"[\w\%]*") # e.g., %jacobi_cd
2378
+
2379
+ sci_not = re.compile(r"(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]\d+)")
2380
+
2381
+ polylog_ex = re.compile(r'li\[([^\[\]]*)\]\(')
2382
+
2383
+ maxima_polygamma = re.compile(r"psi\[([^\[\]]*)\]\(") # matches psi[n]( where n is a number
2384
+
2385
+ maxima_hyper = re.compile(r"\%f\[\d+,\d+\]") # matches %f[m,n]
2386
+
2387
+
2388
+ def _is_function(v):
2389
+ r"""
2390
+ Return whether a symbolic element is a function, not a variable.
2391
+
2392
+ TESTS::
2393
+
2394
+ sage: from sage.calculus.calculus import _is_function
2395
+ sage: _is_function(x)
2396
+ False
2397
+ sage: _is_function(sin)
2398
+ True
2399
+
2400
+ Check that :issue:`31756` is fixed::
2401
+
2402
+ sage: from sage.symbolic.expression import symbol_table
2403
+ sage: _is_function(symbol_table['mathematica'][('Gamma', 1)])
2404
+ True
2405
+
2406
+ sage: from sage.symbolic.expression import register_symbol
2407
+ sage: foo = lambda x: x^2 + 1
2408
+ sage: register_symbol(foo, dict(mathematica='Foo')) # optional - mathematica
2409
+ sage: mathematica('Foo[x]').sage() # optional - mathematica
2410
+ x^2 + 1
2411
+ """
2412
+ # note that Sage variables are callable, so we only check the type
2413
+ return isinstance(v, (Function, FunctionType))
2414
+
2415
+
2416
+ def symbolic_expression_from_maxima_string(x, equals_sub=False, maxima=maxima):
2417
+ r"""
2418
+ Given a string representation of a Maxima expression, parse it and
2419
+ return the corresponding Sage symbolic expression.
2420
+
2421
+ INPUT:
2422
+
2423
+ - ``x`` -- string
2424
+
2425
+ - ``equals_sub`` -- boolean (default: ``False``); if ``True``, replace
2426
+ '=' by '==' in self
2427
+
2428
+ - ``maxima`` -- (default: the calculus package's copy of
2429
+ Maxima) the Maxima interpreter to use
2430
+
2431
+ EXAMPLES::
2432
+
2433
+ sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms
2434
+ sage: sefms('x^%e + %e^%pi + %i + sin(0)')
2435
+ x^e + e^pi + I
2436
+ sage: f = function('f')(x)
2437
+ sage: sefms('?%at(f(x),x=2)#1')
2438
+ f(2) != 1
2439
+ sage: a = sage.calculus.calculus.maxima("x#0"); a
2440
+ x # 0
2441
+ sage: a.sage()
2442
+ x != 0
2443
+
2444
+ TESTS:
2445
+
2446
+ :issue:`8459` fixed::
2447
+
2448
+ sage: maxima('3*li[2](u)+8*li[33](exp(u))').sage()
2449
+ 3*dilog(u) + 8*polylog(33, e^u)
2450
+
2451
+ Check if :issue:`8345` is fixed::
2452
+
2453
+ sage: assume(x,'complex')
2454
+ sage: t = x.conjugate()
2455
+ sage: latex(t)
2456
+ \overline{x}
2457
+ sage: latex(t._maxima_()._sage_())
2458
+ \overline{x}
2459
+
2460
+ Check that we can understand maxima's not-equals (:issue:`8969`)::
2461
+
2462
+ sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms
2463
+ sage: sefms("x!=3") == (factorial(x) == 3)
2464
+ True
2465
+ sage: sefms("x # 3") == SR(x != 3)
2466
+ True
2467
+ sage: solve([x != 5], x) in [[[x - 5 != 0]], [[x < 5], [5 < x]]]
2468
+ True
2469
+ sage: solve([2*x==3, x != 5], x)
2470
+ [[x == (3/2)...
2471
+
2472
+ Make sure that we don't accidentally pick up variables in the maxima namespace (:issue:`8734`)::
2473
+
2474
+ sage: sage.calculus.calculus.maxima('my_new_var : 2')
2475
+ 2
2476
+ sage: var('my_new_var').full_simplify()
2477
+ my_new_var
2478
+
2479
+ ODE solution constants are treated differently (:issue:`16007`)::
2480
+
2481
+ sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms
2482
+ sage: sefms('%k1*x + %k2*y + %c')
2483
+ _K1*x + _K2*y + _C
2484
+
2485
+ Check that some hypothetical variables don't end up as special constants (:issue:`6882`)::
2486
+
2487
+ sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms
2488
+ sage: sefms('%i')^2
2489
+ -1
2490
+ sage: ln(sefms('%e'))
2491
+ 1
2492
+ sage: sefms('i')^2
2493
+ _i^2
2494
+ sage: sefms('I')^2
2495
+ _I^2
2496
+ sage: sefms('ln(e)')
2497
+ ln(_e)
2498
+ sage: sefms('%inf')
2499
+ +Infinity
2500
+ """
2501
+ var_syms = {k[0]: v for k, v in symbol_table.get('maxima', {}).items()
2502
+ if not _is_function(v)}
2503
+ function_syms = {k[0]: v for k, v in symbol_table.get('maxima', {}).items()
2504
+ if _is_function(v)}
2505
+
2506
+ if not x:
2507
+ raise RuntimeError("invalid symbolic expression -- ''")
2508
+ maxima.set('_tmp_', x)
2509
+
2510
+ # This is inefficient since it so rarely is needed:
2511
+ #r = maxima._eval_line('listofvars(_tmp_);')[1:-1]
2512
+
2513
+ s = maxima._eval_line('_tmp_;')
2514
+
2515
+ # We don't actually implement a parser for maxima expressions.
2516
+ # Instead we simply transform the string until it is a valid
2517
+ # sagemath expression and parse that.
2518
+
2519
+ # Remove ticks in front of symbolic functions. You might think
2520
+ # there is a potential very subtle bug if 'foo is in a string
2521
+ # literal -- but string literals should *never* ever be part of a
2522
+ # symbolic expression.
2523
+ s = s.replace("'","")
2524
+
2525
+ delayed_functions = maxima_qp.findall(s)
2526
+ if len(delayed_functions):
2527
+ for X in delayed_functions:
2528
+ if X == '?%at': # we will replace Maxima's "at" with symbolic evaluation, not a SymbolicFunction
2529
+ pass
2530
+ else:
2531
+ function_syms[X[2:]] = function_factory(X[2:])
2532
+ s = s.replace("?%", "")
2533
+
2534
+ s = maxima_hyper.sub('hypergeometric', s)
2535
+
2536
+ # Look up every variable in the symtable keys and fill a replacement list.
2537
+ cursor = 0
2538
+ l = []
2539
+ for m in maxima_var.finditer(s):
2540
+ if m.group(0) in symtable:
2541
+ l.append(s[cursor:m.start()])
2542
+ l.append(symtable.get(m.group(0)))
2543
+ cursor = m.end()
2544
+ if cursor > 0:
2545
+ l.append(s[cursor:])
2546
+ s = "".join(l)
2547
+
2548
+ s = s.replace("%","")
2549
+
2550
+ s = s.replace("#","!=") # a lot of this code should be refactored somewhere...
2551
+ #we apply the square-bracket replacing patterns repeatedly
2552
+ #to ensure that nested brackets get handled (from inside to out)
2553
+ while True:
2554
+ olds = s
2555
+ s = polylog_ex.sub('polylog(\\1,', s)
2556
+ s = maxima_polygamma.sub(r'psi(\g<1>,', s) # this replaces psi[n](foo) with psi(n,foo), ensuring that derivatives of the digamma function are parsed properly below
2557
+ if s == olds:
2558
+ break
2559
+
2560
+ if equals_sub:
2561
+ s = s.replace('=', '==')
2562
+ # unfortunately, this will turn != into !==, which we correct
2563
+ s = s.replace("!==", "!=")
2564
+
2565
+ #replace %union from to_poly_solve with a list
2566
+ if s[0:5] == 'union':
2567
+ s = s[5:]
2568
+ s = s[s.find("(") + 1:s.rfind(")")]
2569
+ s = "[" + s + "]" # turn it into a string that looks like a list
2570
+
2571
+ # replace %solve from to_poly_solve with the expressions
2572
+ if s[0:5] == 'solve':
2573
+ s = s[5:]
2574
+ s = s[s.find("(") + 1:s.find("]") + 1]
2575
+
2576
+ # replace all instances of Maxima's scientific notation
2577
+ # with regular notation
2578
+ search = sci_not.search(s)
2579
+ while search is not None:
2580
+ (start, end) = search.span()
2581
+ r = create_RealNumber(s[start:end]).str(no_sci=2, truncate=True)
2582
+ s = s.replace(s[start:end], r)
2583
+ search = sci_not.search(s)
2584
+
2585
+ function_syms['diff'] = dummy_diff
2586
+ function_syms['integrate'] = dummy_integrate
2587
+ function_syms['laplace'] = dummy_laplace
2588
+ function_syms['ilt'] = dummy_inverse_laplace
2589
+ function_syms['at'] = at
2590
+ function_syms['pochhammer'] = dummy_pochhammer
2591
+
2592
+ global is_simplified
2593
+ try:
2594
+ # use a global flag so all expressions obtained via
2595
+ # evaluation of maxima code are assumed pre-simplified
2596
+ is_simplified = True
2597
+ SRM_parser._variable_constructor().set_names(var_syms)
2598
+ SRM_parser._callable_constructor().set_names(function_syms)
2599
+ return SRM_parser.parse_sequence(s)
2600
+ except SyntaxError:
2601
+ raise TypeError("unable to make sense of Maxima expression '%s' in Sage" % s)
2602
+ finally:
2603
+ is_simplified = False
2604
+
2605
+
2606
+ # Comma format options for Maxima
2607
+ def mapped_opts(v):
2608
+ """
2609
+ Used internally when creating a string of options to pass to
2610
+ Maxima.
2611
+
2612
+ INPUT:
2613
+
2614
+ - ``v`` -- an object
2615
+
2616
+ OUTPUT: string
2617
+
2618
+ The main use of this is to turn Python bools into lower case
2619
+ strings.
2620
+
2621
+ EXAMPLES::
2622
+
2623
+ sage: sage.calculus.calculus.mapped_opts(True)
2624
+ 'true'
2625
+ sage: sage.calculus.calculus.mapped_opts(False)
2626
+ 'false'
2627
+ sage: sage.calculus.calculus.mapped_opts('bar')
2628
+ 'bar'
2629
+ """
2630
+ if isinstance(v, bool):
2631
+ return str(v).lower()
2632
+ return str(v)
2633
+
2634
+
2635
+ def maxima_options(**kwds):
2636
+ """
2637
+ Used internally to create a string of options to pass to Maxima.
2638
+
2639
+ EXAMPLES::
2640
+
2641
+ sage: sage.calculus.calculus.maxima_options(an_option=True, another=False, foo='bar')
2642
+ 'an_option=true,another=false,foo=bar'
2643
+ """
2644
+ return ','.join('%s=%s' % (key, mapped_opts(val))
2645
+ for key, val in sorted(kwds.items()))
2646
+
2647
+
2648
+ # Parser for symbolic ring elements
2649
+
2650
+ # We keep two dictionaries syms_cur and syms_default to keep the current symbol
2651
+ # table and the state of the table at startup respectively. These are used by
2652
+ # the restore() function (see sage.misc.reset).
2653
+
2654
+ syms_cur = symbol_table.get('functions', {})
2655
+ syms_default = dict(syms_cur)
2656
+
2657
+
2658
+ def _toplevel_dict():
2659
+ try:
2660
+ import sage.all as toplevel
2661
+ except ImportError:
2662
+ try:
2663
+ import sage.all__sagemath_symbolics as toplevel
2664
+ except ImportError:
2665
+ try:
2666
+ import sage.all__sagemath_modules as toplevel
2667
+ except ImportError:
2668
+ try:
2669
+ import sage.all__sagemath_categories as toplevel
2670
+ except ImportError:
2671
+ import sage.all__sagemath_objects as toplevel
2672
+ return toplevel.__dict__
2673
+
2674
+
2675
+ def _find_var(name, interface=None):
2676
+ """
2677
+ Function to pass to Parser for constructing
2678
+ variables from strings. For internal use.
2679
+
2680
+ EXAMPLES::
2681
+
2682
+ sage: y = SR.var('y')
2683
+ sage: sage.calculus.calculus._find_var('y')
2684
+ y
2685
+ sage: sage.calculus.calculus._find_var('I')
2686
+ I
2687
+ sage: sage.calculus.calculus._find_var(repr(maxima(y)), interface='maxima')
2688
+ y
2689
+
2690
+ ::
2691
+
2692
+ sage: # needs giac
2693
+ sage: y = SR.var('y')
2694
+ sage: sage.calculus.calculus._find_var(repr(giac(y)), interface='giac')
2695
+ y
2696
+ """
2697
+ if interface == 'maxima':
2698
+ if name.startswith("_SAGE_VAR_"):
2699
+ return var(name[10:])
2700
+ elif interface == 'giac':
2701
+ if name.startswith('sageVAR'):
2702
+ return var(name[7:])
2703
+ else:
2704
+ v = SR.symbols.get(name)
2705
+ if v is not None:
2706
+ return v
2707
+
2708
+ # try to find the name in the global namespace
2709
+ # needed for identifiers like 'e', etc.
2710
+ try:
2711
+ return SR(_toplevel_dict()[name])
2712
+ except (KeyError, TypeError):
2713
+ return var(name)
2714
+
2715
+
2716
+ def _find_func(name, create_when_missing=True):
2717
+ """
2718
+ Function to pass to Parser for constructing
2719
+ functions from strings. For internal use.
2720
+
2721
+ EXAMPLES::
2722
+
2723
+ sage: sage.calculus.calculus._find_func('limit')
2724
+ limit
2725
+ sage: sage.calculus.calculus._find_func('zeta_zeros')
2726
+ zeta_zeros
2727
+ sage: f(x)=sin(x)
2728
+ sage: sage.calculus.calculus._find_func('f')
2729
+ f
2730
+ sage: sage.calculus.calculus._find_func('g', create_when_missing=False)
2731
+ sage: s = sage.calculus.calculus._find_func('sin')
2732
+ sage: s(0)
2733
+ 0
2734
+ """
2735
+ f = symbol_table['functions'].get(name)
2736
+ if f is not None:
2737
+ return f
2738
+
2739
+ try:
2740
+ f = SR(_toplevel_dict()[name])
2741
+ if not isinstance(f, Expression):
2742
+ return f
2743
+ except (KeyError, TypeError):
2744
+ if create_when_missing:
2745
+ return function_factory(name)
2746
+ else:
2747
+ return None
2748
+
2749
+
2750
+ parser_make_var = LookupNameMaker({}, fallback=_find_var)
2751
+ parser_make_function = LookupNameMaker({}, fallback=_find_func)
2752
+
2753
+ SR_parser = Parser(make_int=lambda x: SR(Integer(x)),
2754
+ make_float=lambda x: SR(create_RealNumber(x)),
2755
+ make_var=parser_make_var,
2756
+ make_function=parser_make_function)
2757
+
2758
+
2759
+ def symbolic_expression_from_string(s, syms=None, accept_sequence=False, *, parser=None):
2760
+ """
2761
+ Given a string, (attempt to) parse it and return the
2762
+ corresponding Sage symbolic expression. Normally used
2763
+ to return Maxima output to the user.
2764
+
2765
+ INPUT:
2766
+
2767
+ - ``s`` -- string
2768
+
2769
+ - ``syms`` -- (default: ``{}``) dictionary of
2770
+ strings to be regarded as symbols or functions;
2771
+ keys are pairs (string, number of arguments)
2772
+
2773
+ - ``accept_sequence`` -- boolean (default: ``False``); controls whether
2774
+ to allow a (possibly nested) set of lists and tuples
2775
+ as input
2776
+
2777
+ - ``parser`` -- (default: ``SR_parser``) parser for internal use
2778
+
2779
+ EXAMPLES::
2780
+
2781
+ sage: from sage.calculus.calculus import symbolic_expression_from_string
2782
+ sage: y = var('y')
2783
+ sage: symbolic_expression_from_string('[sin(0)*x^2,3*spam+e^pi]',
2784
+ ....: syms={('spam',0): y}, accept_sequence=True)
2785
+ [0, 3*y + e^pi]
2786
+
2787
+ TESTS:
2788
+
2789
+ Check that the precision is preserved (:issue:`28814`)::
2790
+
2791
+ sage: symbolic_expression_from_string(str(RealField(100)(1/3)))
2792
+ 0.3333333333333333333333333333
2793
+ sage: symbolic_expression_from_string(str(RealField(100)(10^-500/3)))
2794
+ 3.333333333333333333333333333e-501
2795
+
2796
+ The Giac interface uses a different parser (:issue:`30133`)::
2797
+
2798
+ sage: # needs giac
2799
+ sage: from sage.calculus.calculus import SR_parser_giac
2800
+ sage: symbolic_expression_from_string(repr(giac(SR.var('e'))), parser=SR_parser_giac)
2801
+ e
2802
+ """
2803
+ if syms is None:
2804
+ syms = {}
2805
+ if parser is None:
2806
+ parser = SR_parser
2807
+ parse_func = parser.parse_sequence if accept_sequence else parser.parse_expression
2808
+ # this assumes that the parser has constructors of type `LookupNameMaker`
2809
+ parser._variable_constructor().set_names({k[0]: v for k, v in syms.items()
2810
+ if not _is_function(v)})
2811
+ parser._callable_constructor().set_names({k[0]: v for k, v in syms.items()
2812
+ if _is_function(v)})
2813
+ return parse_func(s)
2814
+
2815
+
2816
+ parser_make_Mvar = LookupNameMaker({}, fallback=lambda x: _find_var(x, interface='maxima'))
2817
+
2818
+ SRM_parser = Parser(make_int=lambda x: SR(Integer(x)),
2819
+ make_float=lambda x: SR(RealDoubleElement(x)),
2820
+ make_var=parser_make_Mvar,
2821
+ make_function=parser_make_function)
2822
+
2823
+ SR_parser_giac = Parser(make_int=lambda x: SR(Integer(x)),
2824
+ make_float=lambda x: SR(create_RealNumber(x)),
2825
+ make_var=LookupNameMaker({}, fallback=lambda x: _find_var(x, interface='giac')),
2826
+ make_function=parser_make_function)