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