Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/sympy/concrete/__init__.py +8 -0
- env-llmeval/lib/python3.10/site-packages/sympy/concrete/delta.py +331 -0
- env-llmeval/lib/python3.10/site-packages/sympy/concrete/expr_with_intlimits.py +354 -0
- env-llmeval/lib/python3.10/site-packages/sympy/concrete/expr_with_limits.py +603 -0
- env-llmeval/lib/python3.10/site-packages/sympy/concrete/gosper.py +227 -0
- env-llmeval/lib/python3.10/site-packages/sympy/concrete/guess.py +473 -0
- env-llmeval/lib/python3.10/site-packages/sympy/concrete/products.py +610 -0
- env-llmeval/lib/python3.10/site-packages/sympy/concrete/summations.py +1646 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/complexfield.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/expressionrawdomain.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/fractionfield.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyfinitefield.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyintegerring.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyrationalfield.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/mpelements.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonintegerring.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonrational.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/simpledomain.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/test_basis.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/test_primes.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_basis.py +85 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_galoisgroups.py +143 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_minpoly.py +474 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_modules.py +752 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_primes.py +296 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_subfield.py +304 -0
- env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_utilities.py +113 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_c.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_conventions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_cupy.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_cxx.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_fortran.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_glsl.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_jscode.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_julia.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_latex.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_llvmjit.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_maple.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_mathematica.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_mathml.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_octave.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_python.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_rust.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_str.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_tableform.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_tensorflow.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_tree.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/utilities/__init__.py +30 -0
- env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/codegen.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/sympy/concrete/__init__.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .products import product, Product
|
2 |
+
from .summations import summation, Sum
|
3 |
+
|
4 |
+
__all__ = [
|
5 |
+
'product', 'Product',
|
6 |
+
|
7 |
+
'summation', 'Sum',
|
8 |
+
]
|
env-llmeval/lib/python3.10/site-packages/sympy/concrete/delta.py
ADDED
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module implements sums and products containing the Kronecker Delta function.
|
3 |
+
|
4 |
+
References
|
5 |
+
==========
|
6 |
+
|
7 |
+
.. [1] https://mathworld.wolfram.com/KroneckerDelta.html
|
8 |
+
|
9 |
+
"""
|
10 |
+
from .products import product
|
11 |
+
from .summations import Sum, summation
|
12 |
+
from sympy.core import Add, Mul, S, Dummy
|
13 |
+
from sympy.core.cache import cacheit
|
14 |
+
from sympy.core.sorting import default_sort_key
|
15 |
+
from sympy.functions import KroneckerDelta, Piecewise, piecewise_fold
|
16 |
+
from sympy.polys.polytools import factor
|
17 |
+
from sympy.sets.sets import Interval
|
18 |
+
from sympy.solvers.solvers import solve
|
19 |
+
|
20 |
+
|
21 |
+
@cacheit
|
22 |
+
def _expand_delta(expr, index):
|
23 |
+
"""
|
24 |
+
Expand the first Add containing a simple KroneckerDelta.
|
25 |
+
"""
|
26 |
+
if not expr.is_Mul:
|
27 |
+
return expr
|
28 |
+
delta = None
|
29 |
+
func = Add
|
30 |
+
terms = [S.One]
|
31 |
+
for h in expr.args:
|
32 |
+
if delta is None and h.is_Add and _has_simple_delta(h, index):
|
33 |
+
delta = True
|
34 |
+
func = h.func
|
35 |
+
terms = [terms[0]*t for t in h.args]
|
36 |
+
else:
|
37 |
+
terms = [t*h for t in terms]
|
38 |
+
return func(*terms)
|
39 |
+
|
40 |
+
|
41 |
+
@cacheit
|
42 |
+
def _extract_delta(expr, index):
|
43 |
+
"""
|
44 |
+
Extract a simple KroneckerDelta from the expression.
|
45 |
+
|
46 |
+
Explanation
|
47 |
+
===========
|
48 |
+
|
49 |
+
Returns the tuple ``(delta, newexpr)`` where:
|
50 |
+
|
51 |
+
- ``delta`` is a simple KroneckerDelta expression if one was found,
|
52 |
+
or ``None`` if no simple KroneckerDelta expression was found.
|
53 |
+
|
54 |
+
- ``newexpr`` is a Mul containing the remaining terms; ``expr`` is
|
55 |
+
returned unchanged if no simple KroneckerDelta expression was found.
|
56 |
+
|
57 |
+
Examples
|
58 |
+
========
|
59 |
+
|
60 |
+
>>> from sympy import KroneckerDelta
|
61 |
+
>>> from sympy.concrete.delta import _extract_delta
|
62 |
+
>>> from sympy.abc import x, y, i, j, k
|
63 |
+
>>> _extract_delta(4*x*y*KroneckerDelta(i, j), i)
|
64 |
+
(KroneckerDelta(i, j), 4*x*y)
|
65 |
+
>>> _extract_delta(4*x*y*KroneckerDelta(i, j), k)
|
66 |
+
(None, 4*x*y*KroneckerDelta(i, j))
|
67 |
+
|
68 |
+
See Also
|
69 |
+
========
|
70 |
+
|
71 |
+
sympy.functions.special.tensor_functions.KroneckerDelta
|
72 |
+
deltaproduct
|
73 |
+
deltasummation
|
74 |
+
"""
|
75 |
+
if not _has_simple_delta(expr, index):
|
76 |
+
return (None, expr)
|
77 |
+
if isinstance(expr, KroneckerDelta):
|
78 |
+
return (expr, S.One)
|
79 |
+
if not expr.is_Mul:
|
80 |
+
raise ValueError("Incorrect expr")
|
81 |
+
delta = None
|
82 |
+
terms = []
|
83 |
+
|
84 |
+
for arg in expr.args:
|
85 |
+
if delta is None and _is_simple_delta(arg, index):
|
86 |
+
delta = arg
|
87 |
+
else:
|
88 |
+
terms.append(arg)
|
89 |
+
return (delta, expr.func(*terms))
|
90 |
+
|
91 |
+
|
92 |
+
@cacheit
|
93 |
+
def _has_simple_delta(expr, index):
|
94 |
+
"""
|
95 |
+
Returns True if ``expr`` is an expression that contains a KroneckerDelta
|
96 |
+
that is simple in the index ``index``, meaning that this KroneckerDelta
|
97 |
+
is nonzero for a single value of the index ``index``.
|
98 |
+
"""
|
99 |
+
if expr.has(KroneckerDelta):
|
100 |
+
if _is_simple_delta(expr, index):
|
101 |
+
return True
|
102 |
+
if expr.is_Add or expr.is_Mul:
|
103 |
+
for arg in expr.args:
|
104 |
+
if _has_simple_delta(arg, index):
|
105 |
+
return True
|
106 |
+
return False
|
107 |
+
|
108 |
+
|
109 |
+
@cacheit
|
110 |
+
def _is_simple_delta(delta, index):
|
111 |
+
"""
|
112 |
+
Returns True if ``delta`` is a KroneckerDelta and is nonzero for a single
|
113 |
+
value of the index ``index``.
|
114 |
+
"""
|
115 |
+
if isinstance(delta, KroneckerDelta) and delta.has(index):
|
116 |
+
p = (delta.args[0] - delta.args[1]).as_poly(index)
|
117 |
+
if p:
|
118 |
+
return p.degree() == 1
|
119 |
+
return False
|
120 |
+
|
121 |
+
|
122 |
+
@cacheit
|
123 |
+
def _remove_multiple_delta(expr):
|
124 |
+
"""
|
125 |
+
Evaluate products of KroneckerDelta's.
|
126 |
+
"""
|
127 |
+
if expr.is_Add:
|
128 |
+
return expr.func(*list(map(_remove_multiple_delta, expr.args)))
|
129 |
+
if not expr.is_Mul:
|
130 |
+
return expr
|
131 |
+
eqs = []
|
132 |
+
newargs = []
|
133 |
+
for arg in expr.args:
|
134 |
+
if isinstance(arg, KroneckerDelta):
|
135 |
+
eqs.append(arg.args[0] - arg.args[1])
|
136 |
+
else:
|
137 |
+
newargs.append(arg)
|
138 |
+
if not eqs:
|
139 |
+
return expr
|
140 |
+
solns = solve(eqs, dict=True)
|
141 |
+
if len(solns) == 0:
|
142 |
+
return S.Zero
|
143 |
+
elif len(solns) == 1:
|
144 |
+
for key in solns[0].keys():
|
145 |
+
newargs.append(KroneckerDelta(key, solns[0][key]))
|
146 |
+
expr2 = expr.func(*newargs)
|
147 |
+
if expr != expr2:
|
148 |
+
return _remove_multiple_delta(expr2)
|
149 |
+
return expr
|
150 |
+
|
151 |
+
|
152 |
+
@cacheit
|
153 |
+
def _simplify_delta(expr):
|
154 |
+
"""
|
155 |
+
Rewrite a KroneckerDelta's indices in its simplest form.
|
156 |
+
"""
|
157 |
+
if isinstance(expr, KroneckerDelta):
|
158 |
+
try:
|
159 |
+
slns = solve(expr.args[0] - expr.args[1], dict=True)
|
160 |
+
if slns and len(slns) == 1:
|
161 |
+
return Mul(*[KroneckerDelta(*(key, value))
|
162 |
+
for key, value in slns[0].items()])
|
163 |
+
except NotImplementedError:
|
164 |
+
pass
|
165 |
+
return expr
|
166 |
+
|
167 |
+
|
168 |
+
@cacheit
|
169 |
+
def deltaproduct(f, limit):
|
170 |
+
"""
|
171 |
+
Handle products containing a KroneckerDelta.
|
172 |
+
|
173 |
+
See Also
|
174 |
+
========
|
175 |
+
|
176 |
+
deltasummation
|
177 |
+
sympy.functions.special.tensor_functions.KroneckerDelta
|
178 |
+
sympy.concrete.products.product
|
179 |
+
"""
|
180 |
+
if ((limit[2] - limit[1]) < 0) == True:
|
181 |
+
return S.One
|
182 |
+
|
183 |
+
if not f.has(KroneckerDelta):
|
184 |
+
return product(f, limit)
|
185 |
+
|
186 |
+
if f.is_Add:
|
187 |
+
# Identify the term in the Add that has a simple KroneckerDelta
|
188 |
+
delta = None
|
189 |
+
terms = []
|
190 |
+
for arg in sorted(f.args, key=default_sort_key):
|
191 |
+
if delta is None and _has_simple_delta(arg, limit[0]):
|
192 |
+
delta = arg
|
193 |
+
else:
|
194 |
+
terms.append(arg)
|
195 |
+
newexpr = f.func(*terms)
|
196 |
+
k = Dummy("kprime", integer=True)
|
197 |
+
if isinstance(limit[1], int) and isinstance(limit[2], int):
|
198 |
+
result = deltaproduct(newexpr, limit) + sum([
|
199 |
+
deltaproduct(newexpr, (limit[0], limit[1], ik - 1)) *
|
200 |
+
delta.subs(limit[0], ik) *
|
201 |
+
deltaproduct(newexpr, (limit[0], ik + 1, limit[2])) for ik in range(int(limit[1]), int(limit[2] + 1))]
|
202 |
+
)
|
203 |
+
else:
|
204 |
+
result = deltaproduct(newexpr, limit) + deltasummation(
|
205 |
+
deltaproduct(newexpr, (limit[0], limit[1], k - 1)) *
|
206 |
+
delta.subs(limit[0], k) *
|
207 |
+
deltaproduct(newexpr, (limit[0], k + 1, limit[2])),
|
208 |
+
(k, limit[1], limit[2]),
|
209 |
+
no_piecewise=_has_simple_delta(newexpr, limit[0])
|
210 |
+
)
|
211 |
+
return _remove_multiple_delta(result)
|
212 |
+
|
213 |
+
delta, _ = _extract_delta(f, limit[0])
|
214 |
+
|
215 |
+
if not delta:
|
216 |
+
g = _expand_delta(f, limit[0])
|
217 |
+
if f != g:
|
218 |
+
try:
|
219 |
+
return factor(deltaproduct(g, limit))
|
220 |
+
except AssertionError:
|
221 |
+
return deltaproduct(g, limit)
|
222 |
+
return product(f, limit)
|
223 |
+
|
224 |
+
return _remove_multiple_delta(f.subs(limit[0], limit[1])*KroneckerDelta(limit[2], limit[1])) + \
|
225 |
+
S.One*_simplify_delta(KroneckerDelta(limit[2], limit[1] - 1))
|
226 |
+
|
227 |
+
|
228 |
+
@cacheit
|
229 |
+
def deltasummation(f, limit, no_piecewise=False):
|
230 |
+
"""
|
231 |
+
Handle summations containing a KroneckerDelta.
|
232 |
+
|
233 |
+
Explanation
|
234 |
+
===========
|
235 |
+
|
236 |
+
The idea for summation is the following:
|
237 |
+
|
238 |
+
- If we are dealing with a KroneckerDelta expression, i.e. KroneckerDelta(g(x), j),
|
239 |
+
we try to simplify it.
|
240 |
+
|
241 |
+
If we could simplify it, then we sum the resulting expression.
|
242 |
+
We already know we can sum a simplified expression, because only
|
243 |
+
simple KroneckerDelta expressions are involved.
|
244 |
+
|
245 |
+
If we could not simplify it, there are two cases:
|
246 |
+
|
247 |
+
1) The expression is a simple expression: we return the summation,
|
248 |
+
taking care if we are dealing with a Derivative or with a proper
|
249 |
+
KroneckerDelta.
|
250 |
+
|
251 |
+
2) The expression is not simple (i.e. KroneckerDelta(cos(x))): we can do
|
252 |
+
nothing at all.
|
253 |
+
|
254 |
+
- If the expr is a multiplication expr having a KroneckerDelta term:
|
255 |
+
|
256 |
+
First we expand it.
|
257 |
+
|
258 |
+
If the expansion did work, then we try to sum the expansion.
|
259 |
+
|
260 |
+
If not, we try to extract a simple KroneckerDelta term, then we have two
|
261 |
+
cases:
|
262 |
+
|
263 |
+
1) We have a simple KroneckerDelta term, so we return the summation.
|
264 |
+
|
265 |
+
2) We did not have a simple term, but we do have an expression with
|
266 |
+
simplified KroneckerDelta terms, so we sum this expression.
|
267 |
+
|
268 |
+
Examples
|
269 |
+
========
|
270 |
+
|
271 |
+
>>> from sympy import oo, symbols
|
272 |
+
>>> from sympy.abc import k
|
273 |
+
>>> i, j = symbols('i, j', integer=True, finite=True)
|
274 |
+
>>> from sympy.concrete.delta import deltasummation
|
275 |
+
>>> from sympy import KroneckerDelta
|
276 |
+
>>> deltasummation(KroneckerDelta(i, k), (k, -oo, oo))
|
277 |
+
1
|
278 |
+
>>> deltasummation(KroneckerDelta(i, k), (k, 0, oo))
|
279 |
+
Piecewise((1, i >= 0), (0, True))
|
280 |
+
>>> deltasummation(KroneckerDelta(i, k), (k, 1, 3))
|
281 |
+
Piecewise((1, (i >= 1) & (i <= 3)), (0, True))
|
282 |
+
>>> deltasummation(k*KroneckerDelta(i, j)*KroneckerDelta(j, k), (k, -oo, oo))
|
283 |
+
j*KroneckerDelta(i, j)
|
284 |
+
>>> deltasummation(j*KroneckerDelta(i, j), (j, -oo, oo))
|
285 |
+
i
|
286 |
+
>>> deltasummation(i*KroneckerDelta(i, j), (i, -oo, oo))
|
287 |
+
j
|
288 |
+
|
289 |
+
See Also
|
290 |
+
========
|
291 |
+
|
292 |
+
deltaproduct
|
293 |
+
sympy.functions.special.tensor_functions.KroneckerDelta
|
294 |
+
sympy.concrete.sums.summation
|
295 |
+
"""
|
296 |
+
if ((limit[2] - limit[1]) < 0) == True:
|
297 |
+
return S.Zero
|
298 |
+
|
299 |
+
if not f.has(KroneckerDelta):
|
300 |
+
return summation(f, limit)
|
301 |
+
|
302 |
+
x = limit[0]
|
303 |
+
|
304 |
+
g = _expand_delta(f, x)
|
305 |
+
if g.is_Add:
|
306 |
+
return piecewise_fold(
|
307 |
+
g.func(*[deltasummation(h, limit, no_piecewise) for h in g.args]))
|
308 |
+
|
309 |
+
# try to extract a simple KroneckerDelta term
|
310 |
+
delta, expr = _extract_delta(g, x)
|
311 |
+
|
312 |
+
if (delta is not None) and (delta.delta_range is not None):
|
313 |
+
dinf, dsup = delta.delta_range
|
314 |
+
if (limit[1] - dinf <= 0) == True and (limit[2] - dsup >= 0) == True:
|
315 |
+
no_piecewise = True
|
316 |
+
|
317 |
+
if not delta:
|
318 |
+
return summation(f, limit)
|
319 |
+
|
320 |
+
solns = solve(delta.args[0] - delta.args[1], x)
|
321 |
+
if len(solns) == 0:
|
322 |
+
return S.Zero
|
323 |
+
elif len(solns) != 1:
|
324 |
+
return Sum(f, limit)
|
325 |
+
value = solns[0]
|
326 |
+
if no_piecewise:
|
327 |
+
return expr.subs(x, value)
|
328 |
+
return Piecewise(
|
329 |
+
(expr.subs(x, value), Interval(*limit[1:3]).as_relational(value)),
|
330 |
+
(S.Zero, True)
|
331 |
+
)
|
env-llmeval/lib/python3.10/site-packages/sympy/concrete/expr_with_intlimits.py
ADDED
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.concrete.expr_with_limits import ExprWithLimits
|
2 |
+
from sympy.core.singleton import S
|
3 |
+
from sympy.core.relational import Eq
|
4 |
+
|
5 |
+
class ReorderError(NotImplementedError):
|
6 |
+
"""
|
7 |
+
Exception raised when trying to reorder dependent limits.
|
8 |
+
"""
|
9 |
+
def __init__(self, expr, msg):
|
10 |
+
super().__init__(
|
11 |
+
"%s could not be reordered: %s." % (expr, msg))
|
12 |
+
|
13 |
+
class ExprWithIntLimits(ExprWithLimits):
|
14 |
+
"""
|
15 |
+
Superclass for Product and Sum.
|
16 |
+
|
17 |
+
See Also
|
18 |
+
========
|
19 |
+
|
20 |
+
sympy.concrete.expr_with_limits.ExprWithLimits
|
21 |
+
sympy.concrete.products.Product
|
22 |
+
sympy.concrete.summations.Sum
|
23 |
+
"""
|
24 |
+
__slots__ = ()
|
25 |
+
|
26 |
+
def change_index(self, var, trafo, newvar=None):
|
27 |
+
r"""
|
28 |
+
Change index of a Sum or Product.
|
29 |
+
|
30 |
+
Perform a linear transformation `x \mapsto a x + b` on the index variable
|
31 |
+
`x`. For `a` the only values allowed are `\pm 1`. A new variable to be used
|
32 |
+
after the change of index can also be specified.
|
33 |
+
|
34 |
+
Explanation
|
35 |
+
===========
|
36 |
+
|
37 |
+
``change_index(expr, var, trafo, newvar=None)`` where ``var`` specifies the
|
38 |
+
index variable `x` to transform. The transformation ``trafo`` must be linear
|
39 |
+
and given in terms of ``var``. If the optional argument ``newvar`` is
|
40 |
+
provided then ``var`` gets replaced by ``newvar`` in the final expression.
|
41 |
+
|
42 |
+
Examples
|
43 |
+
========
|
44 |
+
|
45 |
+
>>> from sympy import Sum, Product, simplify
|
46 |
+
>>> from sympy.abc import x, y, a, b, c, d, u, v, i, j, k, l
|
47 |
+
|
48 |
+
>>> S = Sum(x, (x, a, b))
|
49 |
+
>>> S.doit()
|
50 |
+
-a**2/2 + a/2 + b**2/2 + b/2
|
51 |
+
|
52 |
+
>>> Sn = S.change_index(x, x + 1, y)
|
53 |
+
>>> Sn
|
54 |
+
Sum(y - 1, (y, a + 1, b + 1))
|
55 |
+
>>> Sn.doit()
|
56 |
+
-a**2/2 + a/2 + b**2/2 + b/2
|
57 |
+
|
58 |
+
>>> Sn = S.change_index(x, -x, y)
|
59 |
+
>>> Sn
|
60 |
+
Sum(-y, (y, -b, -a))
|
61 |
+
>>> Sn.doit()
|
62 |
+
-a**2/2 + a/2 + b**2/2 + b/2
|
63 |
+
|
64 |
+
>>> Sn = S.change_index(x, x+u)
|
65 |
+
>>> Sn
|
66 |
+
Sum(-u + x, (x, a + u, b + u))
|
67 |
+
>>> Sn.doit()
|
68 |
+
-a**2/2 - a*u + a/2 + b**2/2 + b*u + b/2 - u*(-a + b + 1) + u
|
69 |
+
>>> simplify(Sn.doit())
|
70 |
+
-a**2/2 + a/2 + b**2/2 + b/2
|
71 |
+
|
72 |
+
>>> Sn = S.change_index(x, -x - u, y)
|
73 |
+
>>> Sn
|
74 |
+
Sum(-u - y, (y, -b - u, -a - u))
|
75 |
+
>>> Sn.doit()
|
76 |
+
-a**2/2 - a*u + a/2 + b**2/2 + b*u + b/2 - u*(-a + b + 1) + u
|
77 |
+
>>> simplify(Sn.doit())
|
78 |
+
-a**2/2 + a/2 + b**2/2 + b/2
|
79 |
+
|
80 |
+
>>> P = Product(i*j**2, (i, a, b), (j, c, d))
|
81 |
+
>>> P
|
82 |
+
Product(i*j**2, (i, a, b), (j, c, d))
|
83 |
+
>>> P2 = P.change_index(i, i+3, k)
|
84 |
+
>>> P2
|
85 |
+
Product(j**2*(k - 3), (k, a + 3, b + 3), (j, c, d))
|
86 |
+
>>> P3 = P2.change_index(j, -j, l)
|
87 |
+
>>> P3
|
88 |
+
Product(l**2*(k - 3), (k, a + 3, b + 3), (l, -d, -c))
|
89 |
+
|
90 |
+
When dealing with symbols only, we can make a
|
91 |
+
general linear transformation:
|
92 |
+
|
93 |
+
>>> Sn = S.change_index(x, u*x+v, y)
|
94 |
+
>>> Sn
|
95 |
+
Sum((-v + y)/u, (y, b*u + v, a*u + v))
|
96 |
+
>>> Sn.doit()
|
97 |
+
-v*(a*u - b*u + 1)/u + (a**2*u**2/2 + a*u*v + a*u/2 - b**2*u**2/2 - b*u*v + b*u/2 + v)/u
|
98 |
+
>>> simplify(Sn.doit())
|
99 |
+
a**2*u/2 + a/2 - b**2*u/2 + b/2
|
100 |
+
|
101 |
+
However, the last result can be inconsistent with usual
|
102 |
+
summation where the index increment is always 1. This is
|
103 |
+
obvious as we get back the original value only for ``u``
|
104 |
+
equal +1 or -1.
|
105 |
+
|
106 |
+
See Also
|
107 |
+
========
|
108 |
+
|
109 |
+
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index,
|
110 |
+
reorder_limit,
|
111 |
+
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder,
|
112 |
+
sympy.concrete.summations.Sum.reverse_order,
|
113 |
+
sympy.concrete.products.Product.reverse_order
|
114 |
+
"""
|
115 |
+
if newvar is None:
|
116 |
+
newvar = var
|
117 |
+
|
118 |
+
limits = []
|
119 |
+
for limit in self.limits:
|
120 |
+
if limit[0] == var:
|
121 |
+
p = trafo.as_poly(var)
|
122 |
+
if p.degree() != 1:
|
123 |
+
raise ValueError("Index transformation is not linear")
|
124 |
+
alpha = p.coeff_monomial(var)
|
125 |
+
beta = p.coeff_monomial(S.One)
|
126 |
+
if alpha.is_number:
|
127 |
+
if alpha == S.One:
|
128 |
+
limits.append((newvar, alpha*limit[1] + beta, alpha*limit[2] + beta))
|
129 |
+
elif alpha == S.NegativeOne:
|
130 |
+
limits.append((newvar, alpha*limit[2] + beta, alpha*limit[1] + beta))
|
131 |
+
else:
|
132 |
+
raise ValueError("Linear transformation results in non-linear summation stepsize")
|
133 |
+
else:
|
134 |
+
# Note that the case of alpha being symbolic can give issues if alpha < 0.
|
135 |
+
limits.append((newvar, alpha*limit[2] + beta, alpha*limit[1] + beta))
|
136 |
+
else:
|
137 |
+
limits.append(limit)
|
138 |
+
|
139 |
+
function = self.function.subs(var, (var - beta)/alpha)
|
140 |
+
function = function.subs(var, newvar)
|
141 |
+
|
142 |
+
return self.func(function, *limits)
|
143 |
+
|
144 |
+
|
145 |
+
def index(expr, x):
|
146 |
+
"""
|
147 |
+
Return the index of a dummy variable in the list of limits.
|
148 |
+
|
149 |
+
Explanation
|
150 |
+
===========
|
151 |
+
|
152 |
+
``index(expr, x)`` returns the index of the dummy variable ``x`` in the
|
153 |
+
limits of ``expr``. Note that we start counting with 0 at the inner-most
|
154 |
+
limits tuple.
|
155 |
+
|
156 |
+
Examples
|
157 |
+
========
|
158 |
+
|
159 |
+
>>> from sympy.abc import x, y, a, b, c, d
|
160 |
+
>>> from sympy import Sum, Product
|
161 |
+
>>> Sum(x*y, (x, a, b), (y, c, d)).index(x)
|
162 |
+
0
|
163 |
+
>>> Sum(x*y, (x, a, b), (y, c, d)).index(y)
|
164 |
+
1
|
165 |
+
>>> Product(x*y, (x, a, b), (y, c, d)).index(x)
|
166 |
+
0
|
167 |
+
>>> Product(x*y, (x, a, b), (y, c, d)).index(y)
|
168 |
+
1
|
169 |
+
|
170 |
+
See Also
|
171 |
+
========
|
172 |
+
|
173 |
+
reorder_limit, reorder, sympy.concrete.summations.Sum.reverse_order,
|
174 |
+
sympy.concrete.products.Product.reverse_order
|
175 |
+
"""
|
176 |
+
variables = [limit[0] for limit in expr.limits]
|
177 |
+
|
178 |
+
if variables.count(x) != 1:
|
179 |
+
raise ValueError(expr, "Number of instances of variable not equal to one")
|
180 |
+
else:
|
181 |
+
return variables.index(x)
|
182 |
+
|
183 |
+
def reorder(expr, *arg):
|
184 |
+
"""
|
185 |
+
Reorder limits in a expression containing a Sum or a Product.
|
186 |
+
|
187 |
+
Explanation
|
188 |
+
===========
|
189 |
+
|
190 |
+
``expr.reorder(*arg)`` reorders the limits in the expression ``expr``
|
191 |
+
according to the list of tuples given by ``arg``. These tuples can
|
192 |
+
contain numerical indices or index variable names or involve both.
|
193 |
+
|
194 |
+
Examples
|
195 |
+
========
|
196 |
+
|
197 |
+
>>> from sympy import Sum, Product
|
198 |
+
>>> from sympy.abc import x, y, z, a, b, c, d, e, f
|
199 |
+
|
200 |
+
>>> Sum(x*y, (x, a, b), (y, c, d)).reorder((x, y))
|
201 |
+
Sum(x*y, (y, c, d), (x, a, b))
|
202 |
+
|
203 |
+
>>> Sum(x*y*z, (x, a, b), (y, c, d), (z, e, f)).reorder((x, y), (x, z), (y, z))
|
204 |
+
Sum(x*y*z, (z, e, f), (y, c, d), (x, a, b))
|
205 |
+
|
206 |
+
>>> P = Product(x*y*z, (x, a, b), (y, c, d), (z, e, f))
|
207 |
+
>>> P.reorder((x, y), (x, z), (y, z))
|
208 |
+
Product(x*y*z, (z, e, f), (y, c, d), (x, a, b))
|
209 |
+
|
210 |
+
We can also select the index variables by counting them, starting
|
211 |
+
with the inner-most one:
|
212 |
+
|
213 |
+
>>> Sum(x**2, (x, a, b), (x, c, d)).reorder((0, 1))
|
214 |
+
Sum(x**2, (x, c, d), (x, a, b))
|
215 |
+
|
216 |
+
And of course we can mix both schemes:
|
217 |
+
|
218 |
+
>>> Sum(x*y, (x, a, b), (y, c, d)).reorder((y, x))
|
219 |
+
Sum(x*y, (y, c, d), (x, a, b))
|
220 |
+
>>> Sum(x*y, (x, a, b), (y, c, d)).reorder((y, 0))
|
221 |
+
Sum(x*y, (y, c, d), (x, a, b))
|
222 |
+
|
223 |
+
See Also
|
224 |
+
========
|
225 |
+
|
226 |
+
reorder_limit, index, sympy.concrete.summations.Sum.reverse_order,
|
227 |
+
sympy.concrete.products.Product.reverse_order
|
228 |
+
"""
|
229 |
+
new_expr = expr
|
230 |
+
|
231 |
+
for r in arg:
|
232 |
+
if len(r) != 2:
|
233 |
+
raise ValueError(r, "Invalid number of arguments")
|
234 |
+
|
235 |
+
index1 = r[0]
|
236 |
+
index2 = r[1]
|
237 |
+
|
238 |
+
if not isinstance(r[0], int):
|
239 |
+
index1 = expr.index(r[0])
|
240 |
+
if not isinstance(r[1], int):
|
241 |
+
index2 = expr.index(r[1])
|
242 |
+
|
243 |
+
new_expr = new_expr.reorder_limit(index1, index2)
|
244 |
+
|
245 |
+
return new_expr
|
246 |
+
|
247 |
+
|
248 |
+
def reorder_limit(expr, x, y):
|
249 |
+
"""
|
250 |
+
Interchange two limit tuples of a Sum or Product expression.
|
251 |
+
|
252 |
+
Explanation
|
253 |
+
===========
|
254 |
+
|
255 |
+
``expr.reorder_limit(x, y)`` interchanges two limit tuples. The
|
256 |
+
arguments ``x`` and ``y`` are integers corresponding to the index
|
257 |
+
variables of the two limits which are to be interchanged. The
|
258 |
+
expression ``expr`` has to be either a Sum or a Product.
|
259 |
+
|
260 |
+
Examples
|
261 |
+
========
|
262 |
+
|
263 |
+
>>> from sympy.abc import x, y, z, a, b, c, d, e, f
|
264 |
+
>>> from sympy import Sum, Product
|
265 |
+
|
266 |
+
>>> Sum(x*y*z, (x, a, b), (y, c, d), (z, e, f)).reorder_limit(0, 2)
|
267 |
+
Sum(x*y*z, (z, e, f), (y, c, d), (x, a, b))
|
268 |
+
>>> Sum(x**2, (x, a, b), (x, c, d)).reorder_limit(1, 0)
|
269 |
+
Sum(x**2, (x, c, d), (x, a, b))
|
270 |
+
|
271 |
+
>>> Product(x*y*z, (x, a, b), (y, c, d), (z, e, f)).reorder_limit(0, 2)
|
272 |
+
Product(x*y*z, (z, e, f), (y, c, d), (x, a, b))
|
273 |
+
|
274 |
+
See Also
|
275 |
+
========
|
276 |
+
|
277 |
+
index, reorder, sympy.concrete.summations.Sum.reverse_order,
|
278 |
+
sympy.concrete.products.Product.reverse_order
|
279 |
+
"""
|
280 |
+
var = {limit[0] for limit in expr.limits}
|
281 |
+
limit_x = expr.limits[x]
|
282 |
+
limit_y = expr.limits[y]
|
283 |
+
|
284 |
+
if (len(set(limit_x[1].free_symbols).intersection(var)) == 0 and
|
285 |
+
len(set(limit_x[2].free_symbols).intersection(var)) == 0 and
|
286 |
+
len(set(limit_y[1].free_symbols).intersection(var)) == 0 and
|
287 |
+
len(set(limit_y[2].free_symbols).intersection(var)) == 0):
|
288 |
+
|
289 |
+
limits = []
|
290 |
+
for i, limit in enumerate(expr.limits):
|
291 |
+
if i == x:
|
292 |
+
limits.append(limit_y)
|
293 |
+
elif i == y:
|
294 |
+
limits.append(limit_x)
|
295 |
+
else:
|
296 |
+
limits.append(limit)
|
297 |
+
|
298 |
+
return type(expr)(expr.function, *limits)
|
299 |
+
else:
|
300 |
+
raise ReorderError(expr, "could not interchange the two limits specified")
|
301 |
+
|
302 |
+
@property
|
303 |
+
def has_empty_sequence(self):
|
304 |
+
"""
|
305 |
+
Returns True if the Sum or Product is computed for an empty sequence.
|
306 |
+
|
307 |
+
Examples
|
308 |
+
========
|
309 |
+
|
310 |
+
>>> from sympy import Sum, Product, Symbol
|
311 |
+
>>> m = Symbol('m')
|
312 |
+
>>> Sum(m, (m, 1, 0)).has_empty_sequence
|
313 |
+
True
|
314 |
+
|
315 |
+
>>> Sum(m, (m, 1, 1)).has_empty_sequence
|
316 |
+
False
|
317 |
+
|
318 |
+
>>> M = Symbol('M', integer=True, positive=True)
|
319 |
+
>>> Product(m, (m, 1, M)).has_empty_sequence
|
320 |
+
False
|
321 |
+
|
322 |
+
>>> Product(m, (m, 2, M)).has_empty_sequence
|
323 |
+
|
324 |
+
>>> Product(m, (m, M + 1, M)).has_empty_sequence
|
325 |
+
True
|
326 |
+
|
327 |
+
>>> N = Symbol('N', integer=True, positive=True)
|
328 |
+
>>> Sum(m, (m, N, M)).has_empty_sequence
|
329 |
+
|
330 |
+
>>> N = Symbol('N', integer=True, negative=True)
|
331 |
+
>>> Sum(m, (m, N, M)).has_empty_sequence
|
332 |
+
False
|
333 |
+
|
334 |
+
See Also
|
335 |
+
========
|
336 |
+
|
337 |
+
has_reversed_limits
|
338 |
+
has_finite_limits
|
339 |
+
|
340 |
+
"""
|
341 |
+
ret_None = False
|
342 |
+
for lim in self.limits:
|
343 |
+
dif = lim[1] - lim[2]
|
344 |
+
eq = Eq(dif, 1)
|
345 |
+
if eq == True:
|
346 |
+
return True
|
347 |
+
elif eq == False:
|
348 |
+
continue
|
349 |
+
else:
|
350 |
+
ret_None = True
|
351 |
+
|
352 |
+
if ret_None:
|
353 |
+
return None
|
354 |
+
return False
|
env-llmeval/lib/python3.10/site-packages/sympy/concrete/expr_with_limits.py
ADDED
@@ -0,0 +1,603 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.add import Add
|
2 |
+
from sympy.core.containers import Tuple
|
3 |
+
from sympy.core.expr import Expr
|
4 |
+
from sympy.core.function import AppliedUndef, UndefinedFunction
|
5 |
+
from sympy.core.mul import Mul
|
6 |
+
from sympy.core.relational import Equality, Relational
|
7 |
+
from sympy.core.singleton import S
|
8 |
+
from sympy.core.symbol import Symbol, Dummy
|
9 |
+
from sympy.core.sympify import sympify
|
10 |
+
from sympy.functions.elementary.piecewise import (piecewise_fold,
|
11 |
+
Piecewise)
|
12 |
+
from sympy.logic.boolalg import BooleanFunction
|
13 |
+
from sympy.matrices.matrices import MatrixBase
|
14 |
+
from sympy.sets.sets import Interval, Set
|
15 |
+
from sympy.sets.fancysets import Range
|
16 |
+
from sympy.tensor.indexed import Idx
|
17 |
+
from sympy.utilities import flatten
|
18 |
+
from sympy.utilities.iterables import sift, is_sequence
|
19 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
20 |
+
|
21 |
+
|
22 |
+
def _common_new(cls, function, *symbols, discrete, **assumptions):
|
23 |
+
"""Return either a special return value or the tuple,
|
24 |
+
(function, limits, orientation). This code is common to
|
25 |
+
both ExprWithLimits and AddWithLimits."""
|
26 |
+
function = sympify(function)
|
27 |
+
|
28 |
+
if isinstance(function, Equality):
|
29 |
+
# This transforms e.g. Integral(Eq(x, y)) to Eq(Integral(x), Integral(y))
|
30 |
+
# but that is only valid for definite integrals.
|
31 |
+
limits, orientation = _process_limits(*symbols, discrete=discrete)
|
32 |
+
if not (limits and all(len(limit) == 3 for limit in limits)):
|
33 |
+
sympy_deprecation_warning(
|
34 |
+
"""
|
35 |
+
Creating a indefinite integral with an Eq() argument is
|
36 |
+
deprecated.
|
37 |
+
|
38 |
+
This is because indefinite integrals do not preserve equality
|
39 |
+
due to the arbitrary constants. If you want an equality of
|
40 |
+
indefinite integrals, use Eq(Integral(a, x), Integral(b, x))
|
41 |
+
explicitly.
|
42 |
+
""",
|
43 |
+
deprecated_since_version="1.6",
|
44 |
+
active_deprecations_target="deprecated-indefinite-integral-eq",
|
45 |
+
stacklevel=5,
|
46 |
+
)
|
47 |
+
|
48 |
+
lhs = function.lhs
|
49 |
+
rhs = function.rhs
|
50 |
+
return Equality(cls(lhs, *symbols, **assumptions), \
|
51 |
+
cls(rhs, *symbols, **assumptions))
|
52 |
+
|
53 |
+
if function is S.NaN:
|
54 |
+
return S.NaN
|
55 |
+
|
56 |
+
if symbols:
|
57 |
+
limits, orientation = _process_limits(*symbols, discrete=discrete)
|
58 |
+
for i, li in enumerate(limits):
|
59 |
+
if len(li) == 4:
|
60 |
+
function = function.subs(li[0], li[-1])
|
61 |
+
limits[i] = Tuple(*li[:-1])
|
62 |
+
else:
|
63 |
+
# symbol not provided -- we can still try to compute a general form
|
64 |
+
free = function.free_symbols
|
65 |
+
if len(free) != 1:
|
66 |
+
raise ValueError(
|
67 |
+
"specify dummy variables for %s" % function)
|
68 |
+
limits, orientation = [Tuple(s) for s in free], 1
|
69 |
+
|
70 |
+
# denest any nested calls
|
71 |
+
while cls == type(function):
|
72 |
+
limits = list(function.limits) + limits
|
73 |
+
function = function.function
|
74 |
+
|
75 |
+
# Any embedded piecewise functions need to be brought out to the
|
76 |
+
# top level. We only fold Piecewise that contain the integration
|
77 |
+
# variable.
|
78 |
+
reps = {}
|
79 |
+
symbols_of_integration = {i[0] for i in limits}
|
80 |
+
for p in function.atoms(Piecewise):
|
81 |
+
if not p.has(*symbols_of_integration):
|
82 |
+
reps[p] = Dummy()
|
83 |
+
# mask off those that don't
|
84 |
+
function = function.xreplace(reps)
|
85 |
+
# do the fold
|
86 |
+
function = piecewise_fold(function)
|
87 |
+
# remove the masking
|
88 |
+
function = function.xreplace({v: k for k, v in reps.items()})
|
89 |
+
|
90 |
+
return function, limits, orientation
|
91 |
+
|
92 |
+
|
93 |
+
def _process_limits(*symbols, discrete=None):
|
94 |
+
"""Process the list of symbols and convert them to canonical limits,
|
95 |
+
storing them as Tuple(symbol, lower, upper). The orientation of
|
96 |
+
the function is also returned when the upper limit is missing
|
97 |
+
so (x, 1, None) becomes (x, None, 1) and the orientation is changed.
|
98 |
+
In the case that a limit is specified as (symbol, Range), a list of
|
99 |
+
length 4 may be returned if a change of variables is needed; the
|
100 |
+
expression that should replace the symbol in the expression is
|
101 |
+
the fourth element in the list.
|
102 |
+
"""
|
103 |
+
limits = []
|
104 |
+
orientation = 1
|
105 |
+
if discrete is None:
|
106 |
+
err_msg = 'discrete must be True or False'
|
107 |
+
elif discrete:
|
108 |
+
err_msg = 'use Range, not Interval or Relational'
|
109 |
+
else:
|
110 |
+
err_msg = 'use Interval or Relational, not Range'
|
111 |
+
for V in symbols:
|
112 |
+
if isinstance(V, (Relational, BooleanFunction)):
|
113 |
+
if discrete:
|
114 |
+
raise TypeError(err_msg)
|
115 |
+
variable = V.atoms(Symbol).pop()
|
116 |
+
V = (variable, V.as_set())
|
117 |
+
elif isinstance(V, Symbol) or getattr(V, '_diff_wrt', False):
|
118 |
+
if isinstance(V, Idx):
|
119 |
+
if V.lower is None or V.upper is None:
|
120 |
+
limits.append(Tuple(V))
|
121 |
+
else:
|
122 |
+
limits.append(Tuple(V, V.lower, V.upper))
|
123 |
+
else:
|
124 |
+
limits.append(Tuple(V))
|
125 |
+
continue
|
126 |
+
if is_sequence(V) and not isinstance(V, Set):
|
127 |
+
if len(V) == 2 and isinstance(V[1], Set):
|
128 |
+
V = list(V)
|
129 |
+
if isinstance(V[1], Interval): # includes Reals
|
130 |
+
if discrete:
|
131 |
+
raise TypeError(err_msg)
|
132 |
+
V[1:] = V[1].inf, V[1].sup
|
133 |
+
elif isinstance(V[1], Range):
|
134 |
+
if not discrete:
|
135 |
+
raise TypeError(err_msg)
|
136 |
+
lo = V[1].inf
|
137 |
+
hi = V[1].sup
|
138 |
+
dx = abs(V[1].step) # direction doesn't matter
|
139 |
+
if dx == 1:
|
140 |
+
V[1:] = [lo, hi]
|
141 |
+
else:
|
142 |
+
if lo is not S.NegativeInfinity:
|
143 |
+
V = [V[0]] + [0, (hi - lo)//dx, dx*V[0] + lo]
|
144 |
+
else:
|
145 |
+
V = [V[0]] + [0, S.Infinity, -dx*V[0] + hi]
|
146 |
+
else:
|
147 |
+
# more complicated sets would require splitting, e.g.
|
148 |
+
# Union(Interval(1, 3), interval(6,10))
|
149 |
+
raise NotImplementedError(
|
150 |
+
'expecting Range' if discrete else
|
151 |
+
'Relational or single Interval' )
|
152 |
+
V = sympify(flatten(V)) # list of sympified elements/None
|
153 |
+
if isinstance(V[0], (Symbol, Idx)) or getattr(V[0], '_diff_wrt', False):
|
154 |
+
newsymbol = V[0]
|
155 |
+
if len(V) == 3:
|
156 |
+
# general case
|
157 |
+
if V[2] is None and V[1] is not None:
|
158 |
+
orientation *= -1
|
159 |
+
V = [newsymbol] + [i for i in V[1:] if i is not None]
|
160 |
+
|
161 |
+
lenV = len(V)
|
162 |
+
if not isinstance(newsymbol, Idx) or lenV == 3:
|
163 |
+
if lenV == 4:
|
164 |
+
limits.append(Tuple(*V))
|
165 |
+
continue
|
166 |
+
if lenV == 3:
|
167 |
+
if isinstance(newsymbol, Idx):
|
168 |
+
# Idx represents an integer which may have
|
169 |
+
# specified values it can take on; if it is
|
170 |
+
# given such a value, an error is raised here
|
171 |
+
# if the summation would try to give it a larger
|
172 |
+
# or smaller value than permitted. None and Symbolic
|
173 |
+
# values will not raise an error.
|
174 |
+
lo, hi = newsymbol.lower, newsymbol.upper
|
175 |
+
try:
|
176 |
+
if lo is not None and not bool(V[1] >= lo):
|
177 |
+
raise ValueError("Summation will set Idx value too low.")
|
178 |
+
except TypeError:
|
179 |
+
pass
|
180 |
+
try:
|
181 |
+
if hi is not None and not bool(V[2] <= hi):
|
182 |
+
raise ValueError("Summation will set Idx value too high.")
|
183 |
+
except TypeError:
|
184 |
+
pass
|
185 |
+
limits.append(Tuple(*V))
|
186 |
+
continue
|
187 |
+
if lenV == 1 or (lenV == 2 and V[1] is None):
|
188 |
+
limits.append(Tuple(newsymbol))
|
189 |
+
continue
|
190 |
+
elif lenV == 2:
|
191 |
+
limits.append(Tuple(newsymbol, V[1]))
|
192 |
+
continue
|
193 |
+
|
194 |
+
raise ValueError('Invalid limits given: %s' % str(symbols))
|
195 |
+
|
196 |
+
return limits, orientation
|
197 |
+
|
198 |
+
|
199 |
+
class ExprWithLimits(Expr):
|
200 |
+
__slots__ = ('is_commutative',)
|
201 |
+
|
202 |
+
def __new__(cls, function, *symbols, **assumptions):
|
203 |
+
from sympy.concrete.products import Product
|
204 |
+
pre = _common_new(cls, function, *symbols,
|
205 |
+
discrete=issubclass(cls, Product), **assumptions)
|
206 |
+
if isinstance(pre, tuple):
|
207 |
+
function, limits, _ = pre
|
208 |
+
else:
|
209 |
+
return pre
|
210 |
+
|
211 |
+
# limits must have upper and lower bounds; the indefinite form
|
212 |
+
# is not supported. This restriction does not apply to AddWithLimits
|
213 |
+
if any(len(l) != 3 or None in l for l in limits):
|
214 |
+
raise ValueError('ExprWithLimits requires values for lower and upper bounds.')
|
215 |
+
|
216 |
+
obj = Expr.__new__(cls, **assumptions)
|
217 |
+
arglist = [function]
|
218 |
+
arglist.extend(limits)
|
219 |
+
obj._args = tuple(arglist)
|
220 |
+
obj.is_commutative = function.is_commutative # limits already checked
|
221 |
+
|
222 |
+
return obj
|
223 |
+
|
224 |
+
@property
|
225 |
+
def function(self):
|
226 |
+
"""Return the function applied across limits.
|
227 |
+
|
228 |
+
Examples
|
229 |
+
========
|
230 |
+
|
231 |
+
>>> from sympy import Integral
|
232 |
+
>>> from sympy.abc import x
|
233 |
+
>>> Integral(x**2, (x,)).function
|
234 |
+
x**2
|
235 |
+
|
236 |
+
See Also
|
237 |
+
========
|
238 |
+
|
239 |
+
limits, variables, free_symbols
|
240 |
+
"""
|
241 |
+
return self._args[0]
|
242 |
+
|
243 |
+
@property
|
244 |
+
def kind(self):
|
245 |
+
return self.function.kind
|
246 |
+
|
247 |
+
@property
|
248 |
+
def limits(self):
|
249 |
+
"""Return the limits of expression.
|
250 |
+
|
251 |
+
Examples
|
252 |
+
========
|
253 |
+
|
254 |
+
>>> from sympy import Integral
|
255 |
+
>>> from sympy.abc import x, i
|
256 |
+
>>> Integral(x**i, (i, 1, 3)).limits
|
257 |
+
((i, 1, 3),)
|
258 |
+
|
259 |
+
See Also
|
260 |
+
========
|
261 |
+
|
262 |
+
function, variables, free_symbols
|
263 |
+
"""
|
264 |
+
return self._args[1:]
|
265 |
+
|
266 |
+
@property
|
267 |
+
def variables(self):
|
268 |
+
"""Return a list of the limit variables.
|
269 |
+
|
270 |
+
>>> from sympy import Sum
|
271 |
+
>>> from sympy.abc import x, i
|
272 |
+
>>> Sum(x**i, (i, 1, 3)).variables
|
273 |
+
[i]
|
274 |
+
|
275 |
+
See Also
|
276 |
+
========
|
277 |
+
|
278 |
+
function, limits, free_symbols
|
279 |
+
as_dummy : Rename dummy variables
|
280 |
+
sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable
|
281 |
+
"""
|
282 |
+
return [l[0] for l in self.limits]
|
283 |
+
|
284 |
+
@property
|
285 |
+
def bound_symbols(self):
|
286 |
+
"""Return only variables that are dummy variables.
|
287 |
+
|
288 |
+
Examples
|
289 |
+
========
|
290 |
+
|
291 |
+
>>> from sympy import Integral
|
292 |
+
>>> from sympy.abc import x, i, j, k
|
293 |
+
>>> Integral(x**i, (i, 1, 3), (j, 2), k).bound_symbols
|
294 |
+
[i, j]
|
295 |
+
|
296 |
+
See Also
|
297 |
+
========
|
298 |
+
|
299 |
+
function, limits, free_symbols
|
300 |
+
as_dummy : Rename dummy variables
|
301 |
+
sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable
|
302 |
+
"""
|
303 |
+
return [l[0] for l in self.limits if len(l) != 1]
|
304 |
+
|
305 |
+
@property
|
306 |
+
def free_symbols(self):
|
307 |
+
"""
|
308 |
+
This method returns the symbols in the object, excluding those
|
309 |
+
that take on a specific value (i.e. the dummy symbols).
|
310 |
+
|
311 |
+
Examples
|
312 |
+
========
|
313 |
+
|
314 |
+
>>> from sympy import Sum
|
315 |
+
>>> from sympy.abc import x, y
|
316 |
+
>>> Sum(x, (x, y, 1)).free_symbols
|
317 |
+
{y}
|
318 |
+
"""
|
319 |
+
# don't test for any special values -- nominal free symbols
|
320 |
+
# should be returned, e.g. don't return set() if the
|
321 |
+
# function is zero -- treat it like an unevaluated expression.
|
322 |
+
function, limits = self.function, self.limits
|
323 |
+
# mask off non-symbol integration variables that have
|
324 |
+
# more than themself as a free symbol
|
325 |
+
reps = {i[0]: i[0] if i[0].free_symbols == {i[0]} else Dummy()
|
326 |
+
for i in self.limits}
|
327 |
+
function = function.xreplace(reps)
|
328 |
+
isyms = function.free_symbols
|
329 |
+
for xab in limits:
|
330 |
+
v = reps[xab[0]]
|
331 |
+
if len(xab) == 1:
|
332 |
+
isyms.add(v)
|
333 |
+
continue
|
334 |
+
# take out the target symbol
|
335 |
+
if v in isyms:
|
336 |
+
isyms.remove(v)
|
337 |
+
# add in the new symbols
|
338 |
+
for i in xab[1:]:
|
339 |
+
isyms.update(i.free_symbols)
|
340 |
+
reps = {v: k for k, v in reps.items()}
|
341 |
+
return {reps.get(_, _) for _ in isyms}
|
342 |
+
|
343 |
+
@property
|
344 |
+
def is_number(self):
|
345 |
+
"""Return True if the Sum has no free symbols, else False."""
|
346 |
+
return not self.free_symbols
|
347 |
+
|
348 |
+
def _eval_interval(self, x, a, b):
|
349 |
+
limits = [(i if i[0] != x else (x, a, b)) for i in self.limits]
|
350 |
+
integrand = self.function
|
351 |
+
return self.func(integrand, *limits)
|
352 |
+
|
353 |
+
def _eval_subs(self, old, new):
|
354 |
+
"""
|
355 |
+
Perform substitutions over non-dummy variables
|
356 |
+
of an expression with limits. Also, can be used
|
357 |
+
to specify point-evaluation of an abstract antiderivative.
|
358 |
+
|
359 |
+
Examples
|
360 |
+
========
|
361 |
+
|
362 |
+
>>> from sympy import Sum, oo
|
363 |
+
>>> from sympy.abc import s, n
|
364 |
+
>>> Sum(1/n**s, (n, 1, oo)).subs(s, 2)
|
365 |
+
Sum(n**(-2), (n, 1, oo))
|
366 |
+
|
367 |
+
>>> from sympy import Integral
|
368 |
+
>>> from sympy.abc import x, a
|
369 |
+
>>> Integral(a*x**2, x).subs(x, 4)
|
370 |
+
Integral(a*x**2, (x, 4))
|
371 |
+
|
372 |
+
See Also
|
373 |
+
========
|
374 |
+
|
375 |
+
variables : Lists the integration variables
|
376 |
+
transform : Perform mapping on the dummy variable for integrals
|
377 |
+
change_index : Perform mapping on the sum and product dummy variables
|
378 |
+
|
379 |
+
"""
|
380 |
+
func, limits = self.function, list(self.limits)
|
381 |
+
|
382 |
+
# If one of the expressions we are replacing is used as a func index
|
383 |
+
# one of two things happens.
|
384 |
+
# - the old variable first appears as a free variable
|
385 |
+
# so we perform all free substitutions before it becomes
|
386 |
+
# a func index.
|
387 |
+
# - the old variable first appears as a func index, in
|
388 |
+
# which case we ignore. See change_index.
|
389 |
+
|
390 |
+
# Reorder limits to match standard mathematical practice for scoping
|
391 |
+
limits.reverse()
|
392 |
+
|
393 |
+
if not isinstance(old, Symbol) or \
|
394 |
+
old.free_symbols.intersection(self.free_symbols):
|
395 |
+
sub_into_func = True
|
396 |
+
for i, xab in enumerate(limits):
|
397 |
+
if 1 == len(xab) and old == xab[0]:
|
398 |
+
if new._diff_wrt:
|
399 |
+
xab = (new,)
|
400 |
+
else:
|
401 |
+
xab = (old, old)
|
402 |
+
limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]])
|
403 |
+
if len(xab[0].free_symbols.intersection(old.free_symbols)) != 0:
|
404 |
+
sub_into_func = False
|
405 |
+
break
|
406 |
+
if isinstance(old, (AppliedUndef, UndefinedFunction)):
|
407 |
+
sy2 = set(self.variables).intersection(set(new.atoms(Symbol)))
|
408 |
+
sy1 = set(self.variables).intersection(set(old.args))
|
409 |
+
if not sy2.issubset(sy1):
|
410 |
+
raise ValueError(
|
411 |
+
"substitution cannot create dummy dependencies")
|
412 |
+
sub_into_func = True
|
413 |
+
if sub_into_func:
|
414 |
+
func = func.subs(old, new)
|
415 |
+
else:
|
416 |
+
# old is a Symbol and a dummy variable of some limit
|
417 |
+
for i, xab in enumerate(limits):
|
418 |
+
if len(xab) == 3:
|
419 |
+
limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]])
|
420 |
+
if old == xab[0]:
|
421 |
+
break
|
422 |
+
# simplify redundant limits (x, x) to (x, )
|
423 |
+
for i, xab in enumerate(limits):
|
424 |
+
if len(xab) == 2 and (xab[0] - xab[1]).is_zero:
|
425 |
+
limits[i] = Tuple(xab[0], )
|
426 |
+
|
427 |
+
# Reorder limits back to representation-form
|
428 |
+
limits.reverse()
|
429 |
+
|
430 |
+
return self.func(func, *limits)
|
431 |
+
|
432 |
+
@property
|
433 |
+
def has_finite_limits(self):
|
434 |
+
"""
|
435 |
+
Returns True if the limits are known to be finite, either by the
|
436 |
+
explicit bounds, assumptions on the bounds, or assumptions on the
|
437 |
+
variables. False if known to be infinite, based on the bounds.
|
438 |
+
None if not enough information is available to determine.
|
439 |
+
|
440 |
+
Examples
|
441 |
+
========
|
442 |
+
|
443 |
+
>>> from sympy import Sum, Integral, Product, oo, Symbol
|
444 |
+
>>> x = Symbol('x')
|
445 |
+
>>> Sum(x, (x, 1, 8)).has_finite_limits
|
446 |
+
True
|
447 |
+
|
448 |
+
>>> Integral(x, (x, 1, oo)).has_finite_limits
|
449 |
+
False
|
450 |
+
|
451 |
+
>>> M = Symbol('M')
|
452 |
+
>>> Sum(x, (x, 1, M)).has_finite_limits
|
453 |
+
|
454 |
+
>>> N = Symbol('N', integer=True)
|
455 |
+
>>> Product(x, (x, 1, N)).has_finite_limits
|
456 |
+
True
|
457 |
+
|
458 |
+
See Also
|
459 |
+
========
|
460 |
+
|
461 |
+
has_reversed_limits
|
462 |
+
|
463 |
+
"""
|
464 |
+
|
465 |
+
ret_None = False
|
466 |
+
for lim in self.limits:
|
467 |
+
if len(lim) == 3:
|
468 |
+
if any(l.is_infinite for l in lim[1:]):
|
469 |
+
# Any of the bounds are +/-oo
|
470 |
+
return False
|
471 |
+
elif any(l.is_infinite is None for l in lim[1:]):
|
472 |
+
# Maybe there are assumptions on the variable?
|
473 |
+
if lim[0].is_infinite is None:
|
474 |
+
ret_None = True
|
475 |
+
else:
|
476 |
+
if lim[0].is_infinite is None:
|
477 |
+
ret_None = True
|
478 |
+
|
479 |
+
if ret_None:
|
480 |
+
return None
|
481 |
+
return True
|
482 |
+
|
483 |
+
@property
|
484 |
+
def has_reversed_limits(self):
|
485 |
+
"""
|
486 |
+
Returns True if the limits are known to be in reversed order, either
|
487 |
+
by the explicit bounds, assumptions on the bounds, or assumptions on the
|
488 |
+
variables. False if known to be in normal order, based on the bounds.
|
489 |
+
None if not enough information is available to determine.
|
490 |
+
|
491 |
+
Examples
|
492 |
+
========
|
493 |
+
|
494 |
+
>>> from sympy import Sum, Integral, Product, oo, Symbol
|
495 |
+
>>> x = Symbol('x')
|
496 |
+
>>> Sum(x, (x, 8, 1)).has_reversed_limits
|
497 |
+
True
|
498 |
+
|
499 |
+
>>> Sum(x, (x, 1, oo)).has_reversed_limits
|
500 |
+
False
|
501 |
+
|
502 |
+
>>> M = Symbol('M')
|
503 |
+
>>> Integral(x, (x, 1, M)).has_reversed_limits
|
504 |
+
|
505 |
+
>>> N = Symbol('N', integer=True, positive=True)
|
506 |
+
>>> Sum(x, (x, 1, N)).has_reversed_limits
|
507 |
+
False
|
508 |
+
|
509 |
+
>>> Product(x, (x, 2, N)).has_reversed_limits
|
510 |
+
|
511 |
+
>>> Product(x, (x, 2, N)).subs(N, N + 2).has_reversed_limits
|
512 |
+
False
|
513 |
+
|
514 |
+
See Also
|
515 |
+
========
|
516 |
+
|
517 |
+
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.has_empty_sequence
|
518 |
+
|
519 |
+
"""
|
520 |
+
ret_None = False
|
521 |
+
for lim in self.limits:
|
522 |
+
if len(lim) == 3:
|
523 |
+
var, a, b = lim
|
524 |
+
dif = b - a
|
525 |
+
if dif.is_extended_negative:
|
526 |
+
return True
|
527 |
+
elif dif.is_extended_nonnegative:
|
528 |
+
continue
|
529 |
+
else:
|
530 |
+
ret_None = True
|
531 |
+
else:
|
532 |
+
return None
|
533 |
+
if ret_None:
|
534 |
+
return None
|
535 |
+
return False
|
536 |
+
|
537 |
+
|
538 |
+
class AddWithLimits(ExprWithLimits):
|
539 |
+
r"""Represents unevaluated oriented additions.
|
540 |
+
Parent class for Integral and Sum.
|
541 |
+
"""
|
542 |
+
|
543 |
+
__slots__ = ()
|
544 |
+
|
545 |
+
def __new__(cls, function, *symbols, **assumptions):
|
546 |
+
from sympy.concrete.summations import Sum
|
547 |
+
pre = _common_new(cls, function, *symbols,
|
548 |
+
discrete=issubclass(cls, Sum), **assumptions)
|
549 |
+
if isinstance(pre, tuple):
|
550 |
+
function, limits, orientation = pre
|
551 |
+
else:
|
552 |
+
return pre
|
553 |
+
|
554 |
+
obj = Expr.__new__(cls, **assumptions)
|
555 |
+
arglist = [orientation*function] # orientation not used in ExprWithLimits
|
556 |
+
arglist.extend(limits)
|
557 |
+
obj._args = tuple(arglist)
|
558 |
+
obj.is_commutative = function.is_commutative # limits already checked
|
559 |
+
|
560 |
+
return obj
|
561 |
+
|
562 |
+
def _eval_adjoint(self):
|
563 |
+
if all(x.is_real for x in flatten(self.limits)):
|
564 |
+
return self.func(self.function.adjoint(), *self.limits)
|
565 |
+
return None
|
566 |
+
|
567 |
+
def _eval_conjugate(self):
|
568 |
+
if all(x.is_real for x in flatten(self.limits)):
|
569 |
+
return self.func(self.function.conjugate(), *self.limits)
|
570 |
+
return None
|
571 |
+
|
572 |
+
def _eval_transpose(self):
|
573 |
+
if all(x.is_real for x in flatten(self.limits)):
|
574 |
+
return self.func(self.function.transpose(), *self.limits)
|
575 |
+
return None
|
576 |
+
|
577 |
+
def _eval_factor(self, **hints):
|
578 |
+
if 1 == len(self.limits):
|
579 |
+
summand = self.function.factor(**hints)
|
580 |
+
if summand.is_Mul:
|
581 |
+
out = sift(summand.args, lambda w: w.is_commutative \
|
582 |
+
and not set(self.variables) & w.free_symbols)
|
583 |
+
return Mul(*out[True])*self.func(Mul(*out[False]), \
|
584 |
+
*self.limits)
|
585 |
+
else:
|
586 |
+
summand = self.func(self.function, *self.limits[0:-1]).factor()
|
587 |
+
if not summand.has(self.variables[-1]):
|
588 |
+
return self.func(1, [self.limits[-1]]).doit()*summand
|
589 |
+
elif isinstance(summand, Mul):
|
590 |
+
return self.func(summand, self.limits[-1]).factor()
|
591 |
+
return self
|
592 |
+
|
593 |
+
def _eval_expand_basic(self, **hints):
|
594 |
+
summand = self.function.expand(**hints)
|
595 |
+
force = hints.get('force', False)
|
596 |
+
if (summand.is_Add and (force or summand.is_commutative and
|
597 |
+
self.has_finite_limits is not False)):
|
598 |
+
return Add(*[self.func(i, *self.limits) for i in summand.args])
|
599 |
+
elif isinstance(summand, MatrixBase):
|
600 |
+
return summand.applyfunc(lambda x: self.func(x, *self.limits))
|
601 |
+
elif summand != self.function:
|
602 |
+
return self.func(summand, *self.limits)
|
603 |
+
return self
|
env-llmeval/lib/python3.10/site-packages/sympy/concrete/gosper.py
ADDED
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Gosper's algorithm for hypergeometric summation. """
|
2 |
+
|
3 |
+
from sympy.core import S, Dummy, symbols
|
4 |
+
from sympy.polys import Poly, parallel_poly_from_expr, factor
|
5 |
+
from sympy.utilities.iterables import is_sequence
|
6 |
+
|
7 |
+
|
8 |
+
def gosper_normal(f, g, n, polys=True):
|
9 |
+
r"""
|
10 |
+
Compute the Gosper's normal form of ``f`` and ``g``.
|
11 |
+
|
12 |
+
Explanation
|
13 |
+
===========
|
14 |
+
|
15 |
+
Given relatively prime univariate polynomials ``f`` and ``g``,
|
16 |
+
rewrite their quotient to a normal form defined as follows:
|
17 |
+
|
18 |
+
.. math::
|
19 |
+
\frac{f(n)}{g(n)} = Z \cdot \frac{A(n) C(n+1)}{B(n) C(n)}
|
20 |
+
|
21 |
+
where ``Z`` is an arbitrary constant and ``A``, ``B``, ``C`` are
|
22 |
+
monic polynomials in ``n`` with the following properties:
|
23 |
+
|
24 |
+
1. `\gcd(A(n), B(n+h)) = 1 \forall h \in \mathbb{N}`
|
25 |
+
2. `\gcd(B(n), C(n+1)) = 1`
|
26 |
+
3. `\gcd(A(n), C(n)) = 1`
|
27 |
+
|
28 |
+
This normal form, or rational factorization in other words, is a
|
29 |
+
crucial step in Gosper's algorithm and in solving of difference
|
30 |
+
equations. It can be also used to decide if two hypergeometric
|
31 |
+
terms are similar or not.
|
32 |
+
|
33 |
+
This procedure will return a tuple containing elements of this
|
34 |
+
factorization in the form ``(Z*A, B, C)``.
|
35 |
+
|
36 |
+
Examples
|
37 |
+
========
|
38 |
+
|
39 |
+
>>> from sympy.concrete.gosper import gosper_normal
|
40 |
+
>>> from sympy.abc import n
|
41 |
+
|
42 |
+
>>> gosper_normal(4*n+5, 2*(4*n+1)*(2*n+3), n, polys=False)
|
43 |
+
(1/4, n + 3/2, n + 1/4)
|
44 |
+
|
45 |
+
"""
|
46 |
+
(p, q), opt = parallel_poly_from_expr(
|
47 |
+
(f, g), n, field=True, extension=True)
|
48 |
+
|
49 |
+
a, A = p.LC(), p.monic()
|
50 |
+
b, B = q.LC(), q.monic()
|
51 |
+
|
52 |
+
C, Z = A.one, a/b
|
53 |
+
h = Dummy('h')
|
54 |
+
|
55 |
+
D = Poly(n + h, n, h, domain=opt.domain)
|
56 |
+
|
57 |
+
R = A.resultant(B.compose(D))
|
58 |
+
roots = set(R.ground_roots().keys())
|
59 |
+
|
60 |
+
for r in set(roots):
|
61 |
+
if not r.is_Integer or r < 0:
|
62 |
+
roots.remove(r)
|
63 |
+
|
64 |
+
for i in sorted(roots):
|
65 |
+
d = A.gcd(B.shift(+i))
|
66 |
+
|
67 |
+
A = A.quo(d)
|
68 |
+
B = B.quo(d.shift(-i))
|
69 |
+
|
70 |
+
for j in range(1, i + 1):
|
71 |
+
C *= d.shift(-j)
|
72 |
+
|
73 |
+
A = A.mul_ground(Z)
|
74 |
+
|
75 |
+
if not polys:
|
76 |
+
A = A.as_expr()
|
77 |
+
B = B.as_expr()
|
78 |
+
C = C.as_expr()
|
79 |
+
|
80 |
+
return A, B, C
|
81 |
+
|
82 |
+
|
83 |
+
def gosper_term(f, n):
|
84 |
+
r"""
|
85 |
+
Compute Gosper's hypergeometric term for ``f``.
|
86 |
+
|
87 |
+
Explanation
|
88 |
+
===========
|
89 |
+
|
90 |
+
Suppose ``f`` is a hypergeometric term such that:
|
91 |
+
|
92 |
+
.. math::
|
93 |
+
s_n = \sum_{k=0}^{n-1} f_k
|
94 |
+
|
95 |
+
and `f_k` does not depend on `n`. Returns a hypergeometric
|
96 |
+
term `g_n` such that `g_{n+1} - g_n = f_n`.
|
97 |
+
|
98 |
+
Examples
|
99 |
+
========
|
100 |
+
|
101 |
+
>>> from sympy.concrete.gosper import gosper_term
|
102 |
+
>>> from sympy import factorial
|
103 |
+
>>> from sympy.abc import n
|
104 |
+
|
105 |
+
>>> gosper_term((4*n + 1)*factorial(n)/factorial(2*n + 1), n)
|
106 |
+
(-n - 1/2)/(n + 1/4)
|
107 |
+
|
108 |
+
"""
|
109 |
+
from sympy.simplify import hypersimp
|
110 |
+
r = hypersimp(f, n)
|
111 |
+
|
112 |
+
if r is None:
|
113 |
+
return None # 'f' is *not* a hypergeometric term
|
114 |
+
|
115 |
+
p, q = r.as_numer_denom()
|
116 |
+
|
117 |
+
A, B, C = gosper_normal(p, q, n)
|
118 |
+
B = B.shift(-1)
|
119 |
+
|
120 |
+
N = S(A.degree())
|
121 |
+
M = S(B.degree())
|
122 |
+
K = S(C.degree())
|
123 |
+
|
124 |
+
if (N != M) or (A.LC() != B.LC()):
|
125 |
+
D = {K - max(N, M)}
|
126 |
+
elif not N:
|
127 |
+
D = {K - N + 1, S.Zero}
|
128 |
+
else:
|
129 |
+
D = {K - N + 1, (B.nth(N - 1) - A.nth(N - 1))/A.LC()}
|
130 |
+
|
131 |
+
for d in set(D):
|
132 |
+
if not d.is_Integer or d < 0:
|
133 |
+
D.remove(d)
|
134 |
+
|
135 |
+
if not D:
|
136 |
+
return None # 'f(n)' is *not* Gosper-summable
|
137 |
+
|
138 |
+
d = max(D)
|
139 |
+
|
140 |
+
coeffs = symbols('c:%s' % (d + 1), cls=Dummy)
|
141 |
+
domain = A.get_domain().inject(*coeffs)
|
142 |
+
|
143 |
+
x = Poly(coeffs, n, domain=domain)
|
144 |
+
H = A*x.shift(1) - B*x - C
|
145 |
+
|
146 |
+
from sympy.solvers.solvers import solve
|
147 |
+
solution = solve(H.coeffs(), coeffs)
|
148 |
+
|
149 |
+
if solution is None:
|
150 |
+
return None # 'f(n)' is *not* Gosper-summable
|
151 |
+
|
152 |
+
x = x.as_expr().subs(solution)
|
153 |
+
|
154 |
+
for coeff in coeffs:
|
155 |
+
if coeff not in solution:
|
156 |
+
x = x.subs(coeff, 0)
|
157 |
+
|
158 |
+
if x.is_zero:
|
159 |
+
return None # 'f(n)' is *not* Gosper-summable
|
160 |
+
else:
|
161 |
+
return B.as_expr()*x/C.as_expr()
|
162 |
+
|
163 |
+
|
164 |
+
def gosper_sum(f, k):
|
165 |
+
r"""
|
166 |
+
Gosper's hypergeometric summation algorithm.
|
167 |
+
|
168 |
+
Explanation
|
169 |
+
===========
|
170 |
+
|
171 |
+
Given a hypergeometric term ``f`` such that:
|
172 |
+
|
173 |
+
.. math ::
|
174 |
+
s_n = \sum_{k=0}^{n-1} f_k
|
175 |
+
|
176 |
+
and `f(n)` does not depend on `n`, returns `g_{n} - g(0)` where
|
177 |
+
`g_{n+1} - g_n = f_n`, or ``None`` if `s_n` cannot be expressed
|
178 |
+
in closed form as a sum of hypergeometric terms.
|
179 |
+
|
180 |
+
Examples
|
181 |
+
========
|
182 |
+
|
183 |
+
>>> from sympy.concrete.gosper import gosper_sum
|
184 |
+
>>> from sympy import factorial
|
185 |
+
>>> from sympy.abc import n, k
|
186 |
+
|
187 |
+
>>> f = (4*k + 1)*factorial(k)/factorial(2*k + 1)
|
188 |
+
>>> gosper_sum(f, (k, 0, n))
|
189 |
+
(-factorial(n) + 2*factorial(2*n + 1))/factorial(2*n + 1)
|
190 |
+
>>> _.subs(n, 2) == sum(f.subs(k, i) for i in [0, 1, 2])
|
191 |
+
True
|
192 |
+
>>> gosper_sum(f, (k, 3, n))
|
193 |
+
(-60*factorial(n) + factorial(2*n + 1))/(60*factorial(2*n + 1))
|
194 |
+
>>> _.subs(n, 5) == sum(f.subs(k, i) for i in [3, 4, 5])
|
195 |
+
True
|
196 |
+
|
197 |
+
References
|
198 |
+
==========
|
199 |
+
|
200 |
+
.. [1] Marko Petkovsek, Herbert S. Wilf, Doron Zeilberger, A = B,
|
201 |
+
AK Peters, Ltd., Wellesley, MA, USA, 1997, pp. 73--100
|
202 |
+
|
203 |
+
"""
|
204 |
+
indefinite = False
|
205 |
+
|
206 |
+
if is_sequence(k):
|
207 |
+
k, a, b = k
|
208 |
+
else:
|
209 |
+
indefinite = True
|
210 |
+
|
211 |
+
g = gosper_term(f, k)
|
212 |
+
|
213 |
+
if g is None:
|
214 |
+
return None
|
215 |
+
|
216 |
+
if indefinite:
|
217 |
+
result = f*g
|
218 |
+
else:
|
219 |
+
result = (f*(g + 1)).subs(k, b) - (f*g).subs(k, a)
|
220 |
+
|
221 |
+
if result is S.NaN:
|
222 |
+
try:
|
223 |
+
result = (f*(g + 1)).limit(k, b) - (f*g).limit(k, a)
|
224 |
+
except NotImplementedError:
|
225 |
+
result = None
|
226 |
+
|
227 |
+
return factor(result)
|
env-llmeval/lib/python3.10/site-packages/sympy/concrete/guess.py
ADDED
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Various algorithms for helping identifying numbers and sequences."""
|
2 |
+
|
3 |
+
|
4 |
+
from sympy.concrete.products import (Product, product)
|
5 |
+
from sympy.core import Function, S
|
6 |
+
from sympy.core.add import Add
|
7 |
+
from sympy.core.numbers import Integer, Rational
|
8 |
+
from sympy.core.symbol import Symbol, symbols
|
9 |
+
from sympy.core.sympify import sympify
|
10 |
+
from sympy.functions.elementary.exponential import exp
|
11 |
+
from sympy.functions.elementary.integers import floor
|
12 |
+
from sympy.integrals.integrals import integrate
|
13 |
+
from sympy.polys.polyfuncs import rational_interpolate as rinterp
|
14 |
+
from sympy.polys.polytools import lcm
|
15 |
+
from sympy.simplify.radsimp import denom
|
16 |
+
from sympy.utilities import public
|
17 |
+
|
18 |
+
|
19 |
+
@public
|
20 |
+
def find_simple_recurrence_vector(l):
|
21 |
+
"""
|
22 |
+
This function is used internally by other functions from the
|
23 |
+
sympy.concrete.guess module. While most users may want to rather use the
|
24 |
+
function find_simple_recurrence when looking for recurrence relations
|
25 |
+
among rational numbers, the current function may still be useful when
|
26 |
+
some post-processing has to be done.
|
27 |
+
|
28 |
+
Explanation
|
29 |
+
===========
|
30 |
+
|
31 |
+
The function returns a vector of length n when a recurrence relation of
|
32 |
+
order n is detected in the sequence of rational numbers v.
|
33 |
+
|
34 |
+
If the returned vector has a length 1, then the returned value is always
|
35 |
+
the list [0], which means that no relation has been found.
|
36 |
+
|
37 |
+
While the functions is intended to be used with rational numbers, it should
|
38 |
+
work for other kinds of real numbers except for some cases involving
|
39 |
+
quadratic numbers; for that reason it should be used with some caution when
|
40 |
+
the argument is not a list of rational numbers.
|
41 |
+
|
42 |
+
Examples
|
43 |
+
========
|
44 |
+
|
45 |
+
>>> from sympy.concrete.guess import find_simple_recurrence_vector
|
46 |
+
>>> from sympy import fibonacci
|
47 |
+
>>> find_simple_recurrence_vector([fibonacci(k) for k in range(12)])
|
48 |
+
[1, -1, -1]
|
49 |
+
|
50 |
+
See Also
|
51 |
+
========
|
52 |
+
|
53 |
+
See the function sympy.concrete.guess.find_simple_recurrence which is more
|
54 |
+
user-friendly.
|
55 |
+
|
56 |
+
"""
|
57 |
+
q1 = [0]
|
58 |
+
q2 = [1]
|
59 |
+
b, z = 0, len(l) >> 1
|
60 |
+
while len(q2) <= z:
|
61 |
+
while l[b]==0:
|
62 |
+
b += 1
|
63 |
+
if b == len(l):
|
64 |
+
c = 1
|
65 |
+
for x in q2:
|
66 |
+
c = lcm(c, denom(x))
|
67 |
+
if q2[0]*c < 0: c = -c
|
68 |
+
for k in range(len(q2)):
|
69 |
+
q2[k] = int(q2[k]*c)
|
70 |
+
return q2
|
71 |
+
a = S.One/l[b]
|
72 |
+
m = [a]
|
73 |
+
for k in range(b+1, len(l)):
|
74 |
+
m.append(-sum(l[j+1]*m[b-j-1] for j in range(b, k))*a)
|
75 |
+
l, m = m, [0] * max(len(q2), b+len(q1))
|
76 |
+
for k, q in enumerate(q2):
|
77 |
+
m[k] = a*q
|
78 |
+
for k, q in enumerate(q1):
|
79 |
+
m[k+b] += q
|
80 |
+
while m[-1]==0: m.pop() # because trailing zeros can occur
|
81 |
+
q1, q2, b = q2, m, 1
|
82 |
+
return [0]
|
83 |
+
|
84 |
+
@public
|
85 |
+
def find_simple_recurrence(v, A=Function('a'), N=Symbol('n')):
|
86 |
+
"""
|
87 |
+
Detects and returns a recurrence relation from a sequence of several integer
|
88 |
+
(or rational) terms. The name of the function in the returned expression is
|
89 |
+
'a' by default; the main variable is 'n' by default. The smallest index in
|
90 |
+
the returned expression is always n (and never n-1, n-2, etc.).
|
91 |
+
|
92 |
+
Examples
|
93 |
+
========
|
94 |
+
|
95 |
+
>>> from sympy.concrete.guess import find_simple_recurrence
|
96 |
+
>>> from sympy import fibonacci
|
97 |
+
>>> find_simple_recurrence([fibonacci(k) for k in range(12)])
|
98 |
+
-a(n) - a(n + 1) + a(n + 2)
|
99 |
+
|
100 |
+
>>> from sympy import Function, Symbol
|
101 |
+
>>> a = [1, 1, 1]
|
102 |
+
>>> for k in range(15): a.append(5*a[-1]-3*a[-2]+8*a[-3])
|
103 |
+
>>> find_simple_recurrence(a, A=Function('f'), N=Symbol('i'))
|
104 |
+
-8*f(i) + 3*f(i + 1) - 5*f(i + 2) + f(i + 3)
|
105 |
+
|
106 |
+
"""
|
107 |
+
p = find_simple_recurrence_vector(v)
|
108 |
+
n = len(p)
|
109 |
+
if n <= 1: return S.Zero
|
110 |
+
|
111 |
+
return Add(*[A(N+n-1-k)*p[k] for k in range(n)])
|
112 |
+
|
113 |
+
|
114 |
+
@public
|
115 |
+
def rationalize(x, maxcoeff=10000):
|
116 |
+
"""
|
117 |
+
Helps identifying a rational number from a float (or mpmath.mpf) value by
|
118 |
+
using a continued fraction. The algorithm stops as soon as a large partial
|
119 |
+
quotient is detected (greater than 10000 by default).
|
120 |
+
|
121 |
+
Examples
|
122 |
+
========
|
123 |
+
|
124 |
+
>>> from sympy.concrete.guess import rationalize
|
125 |
+
>>> from mpmath import cos, pi
|
126 |
+
>>> rationalize(cos(pi/3))
|
127 |
+
1/2
|
128 |
+
|
129 |
+
>>> from mpmath import mpf
|
130 |
+
>>> rationalize(mpf("0.333333333333333"))
|
131 |
+
1/3
|
132 |
+
|
133 |
+
While the function is rather intended to help 'identifying' rational
|
134 |
+
values, it may be used in some cases for approximating real numbers.
|
135 |
+
(Though other functions may be more relevant in that case.)
|
136 |
+
|
137 |
+
>>> rationalize(pi, maxcoeff = 250)
|
138 |
+
355/113
|
139 |
+
|
140 |
+
See Also
|
141 |
+
========
|
142 |
+
|
143 |
+
Several other methods can approximate a real number as a rational, like:
|
144 |
+
|
145 |
+
* fractions.Fraction.from_decimal
|
146 |
+
* fractions.Fraction.from_float
|
147 |
+
* mpmath.identify
|
148 |
+
* mpmath.pslq by using the following syntax: mpmath.pslq([x, 1])
|
149 |
+
* mpmath.findpoly by using the following syntax: mpmath.findpoly(x, 1)
|
150 |
+
* sympy.simplify.nsimplify (which is a more general function)
|
151 |
+
|
152 |
+
The main difference between the current function and all these variants is
|
153 |
+
that control focuses on magnitude of partial quotients here rather than on
|
154 |
+
global precision of the approximation. If the real is "known to be" a
|
155 |
+
rational number, the current function should be able to detect it correctly
|
156 |
+
with the default settings even when denominator is great (unless its
|
157 |
+
expansion contains unusually big partial quotients) which may occur
|
158 |
+
when studying sequences of increasing numbers. If the user cares more
|
159 |
+
on getting simple fractions, other methods may be more convenient.
|
160 |
+
|
161 |
+
"""
|
162 |
+
p0, p1 = 0, 1
|
163 |
+
q0, q1 = 1, 0
|
164 |
+
a = floor(x)
|
165 |
+
while a < maxcoeff or q1==0:
|
166 |
+
p = a*p1 + p0
|
167 |
+
q = a*q1 + q0
|
168 |
+
p0, p1 = p1, p
|
169 |
+
q0, q1 = q1, q
|
170 |
+
if x==a: break
|
171 |
+
x = 1/(x-a)
|
172 |
+
a = floor(x)
|
173 |
+
return sympify(p) / q
|
174 |
+
|
175 |
+
|
176 |
+
@public
|
177 |
+
def guess_generating_function_rational(v, X=Symbol('x')):
|
178 |
+
"""
|
179 |
+
Tries to "guess" a rational generating function for a sequence of rational
|
180 |
+
numbers v.
|
181 |
+
|
182 |
+
Examples
|
183 |
+
========
|
184 |
+
|
185 |
+
>>> from sympy.concrete.guess import guess_generating_function_rational
|
186 |
+
>>> from sympy import fibonacci
|
187 |
+
>>> l = [fibonacci(k) for k in range(5,15)]
|
188 |
+
>>> guess_generating_function_rational(l)
|
189 |
+
(3*x + 5)/(-x**2 - x + 1)
|
190 |
+
|
191 |
+
See Also
|
192 |
+
========
|
193 |
+
|
194 |
+
sympy.series.approximants
|
195 |
+
mpmath.pade
|
196 |
+
|
197 |
+
"""
|
198 |
+
# a) compute the denominator as q
|
199 |
+
q = find_simple_recurrence_vector(v)
|
200 |
+
n = len(q)
|
201 |
+
if n <= 1: return None
|
202 |
+
# b) compute the numerator as p
|
203 |
+
p = [sum(v[i-k]*q[k] for k in range(min(i+1, n)))
|
204 |
+
for i in range(len(v)>>1)]
|
205 |
+
return (sum(p[k]*X**k for k in range(len(p)))
|
206 |
+
/ sum(q[k]*X**k for k in range(n)))
|
207 |
+
|
208 |
+
|
209 |
+
@public
|
210 |
+
def guess_generating_function(v, X=Symbol('x'), types=['all'], maxsqrtn=2):
|
211 |
+
"""
|
212 |
+
Tries to "guess" a generating function for a sequence of rational numbers v.
|
213 |
+
Only a few patterns are implemented yet.
|
214 |
+
|
215 |
+
Explanation
|
216 |
+
===========
|
217 |
+
|
218 |
+
The function returns a dictionary where keys are the name of a given type of
|
219 |
+
generating function. Six types are currently implemented:
|
220 |
+
|
221 |
+
type | formal definition
|
222 |
+
-------+----------------------------------------------------------------
|
223 |
+
ogf | f(x) = Sum( a_k * x^k , k: 0..infinity )
|
224 |
+
egf | f(x) = Sum( a_k * x^k / k! , k: 0..infinity )
|
225 |
+
lgf | f(x) = Sum( (-1)^(k+1) a_k * x^k / k , k: 1..infinity )
|
226 |
+
| (with initial index being hold as 1 rather than 0)
|
227 |
+
hlgf | f(x) = Sum( a_k * x^k / k , k: 1..infinity )
|
228 |
+
| (with initial index being hold as 1 rather than 0)
|
229 |
+
lgdogf | f(x) = derivate( log(Sum( a_k * x^k, k: 0..infinity )), x)
|
230 |
+
lgdegf | f(x) = derivate( log(Sum( a_k * x^k / k!, k: 0..infinity )), x)
|
231 |
+
|
232 |
+
In order to spare time, the user can select only some types of generating
|
233 |
+
functions (default being ['all']). While forgetting to use a list in the
|
234 |
+
case of a single type may seem to work most of the time as in: types='ogf'
|
235 |
+
this (convenient) syntax may lead to unexpected extra results in some cases.
|
236 |
+
|
237 |
+
Discarding a type when calling the function does not mean that the type will
|
238 |
+
not be present in the returned dictionary; it only means that no extra
|
239 |
+
computation will be performed for that type, but the function may still add
|
240 |
+
it in the result when it can be easily converted from another type.
|
241 |
+
|
242 |
+
Two generating functions (lgdogf and lgdegf) are not even computed if the
|
243 |
+
initial term of the sequence is 0; it may be useful in that case to try
|
244 |
+
again after having removed the leading zeros.
|
245 |
+
|
246 |
+
Examples
|
247 |
+
========
|
248 |
+
|
249 |
+
>>> from sympy.concrete.guess import guess_generating_function as ggf
|
250 |
+
>>> ggf([k+1 for k in range(12)], types=['ogf', 'lgf', 'hlgf'])
|
251 |
+
{'hlgf': 1/(1 - x), 'lgf': 1/(x + 1), 'ogf': 1/(x**2 - 2*x + 1)}
|
252 |
+
|
253 |
+
>>> from sympy import sympify
|
254 |
+
>>> l = sympify("[3/2, 11/2, 0, -121/2, -363/2, 121]")
|
255 |
+
>>> ggf(l)
|
256 |
+
{'ogf': (x + 3/2)/(11*x**2 - 3*x + 1)}
|
257 |
+
|
258 |
+
>>> from sympy import fibonacci
|
259 |
+
>>> ggf([fibonacci(k) for k in range(5, 15)], types=['ogf'])
|
260 |
+
{'ogf': (3*x + 5)/(-x**2 - x + 1)}
|
261 |
+
|
262 |
+
>>> from sympy import factorial
|
263 |
+
>>> ggf([factorial(k) for k in range(12)], types=['ogf', 'egf', 'lgf'])
|
264 |
+
{'egf': 1/(1 - x)}
|
265 |
+
|
266 |
+
>>> ggf([k+1 for k in range(12)], types=['egf'])
|
267 |
+
{'egf': (x + 1)*exp(x), 'lgdegf': (x + 2)/(x + 1)}
|
268 |
+
|
269 |
+
N-th root of a rational function can also be detected (below is an example
|
270 |
+
coming from the sequence A108626 from https://oeis.org).
|
271 |
+
The greatest n-th root to be tested is specified as maxsqrtn (default 2).
|
272 |
+
|
273 |
+
>>> ggf([1, 2, 5, 14, 41, 124, 383, 1200, 3799, 12122, 38919])['ogf']
|
274 |
+
sqrt(1/(x**4 + 2*x**2 - 4*x + 1))
|
275 |
+
|
276 |
+
References
|
277 |
+
==========
|
278 |
+
|
279 |
+
.. [1] "Concrete Mathematics", R.L. Graham, D.E. Knuth, O. Patashnik
|
280 |
+
.. [2] https://oeis.org/wiki/Generating_functions
|
281 |
+
|
282 |
+
"""
|
283 |
+
# List of all types of all g.f. known by the algorithm
|
284 |
+
if 'all' in types:
|
285 |
+
types = ('ogf', 'egf', 'lgf', 'hlgf', 'lgdogf', 'lgdegf')
|
286 |
+
|
287 |
+
result = {}
|
288 |
+
|
289 |
+
# Ordinary Generating Function (ogf)
|
290 |
+
if 'ogf' in types:
|
291 |
+
# Perform some convolutions of the sequence with itself
|
292 |
+
t = [1] + [0]*(len(v) - 1)
|
293 |
+
for d in range(max(1, maxsqrtn)):
|
294 |
+
t = [sum(t[n-i]*v[i] for i in range(n+1)) for n in range(len(v))]
|
295 |
+
g = guess_generating_function_rational(t, X=X)
|
296 |
+
if g:
|
297 |
+
result['ogf'] = g**Rational(1, d+1)
|
298 |
+
break
|
299 |
+
|
300 |
+
# Exponential Generating Function (egf)
|
301 |
+
if 'egf' in types:
|
302 |
+
# Transform sequence (division by factorial)
|
303 |
+
w, f = [], S.One
|
304 |
+
for i, k in enumerate(v):
|
305 |
+
f *= i if i else 1
|
306 |
+
w.append(k/f)
|
307 |
+
# Perform some convolutions of the sequence with itself
|
308 |
+
t = [1] + [0]*(len(w) - 1)
|
309 |
+
for d in range(max(1, maxsqrtn)):
|
310 |
+
t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
|
311 |
+
g = guess_generating_function_rational(t, X=X)
|
312 |
+
if g:
|
313 |
+
result['egf'] = g**Rational(1, d+1)
|
314 |
+
break
|
315 |
+
|
316 |
+
# Logarithmic Generating Function (lgf)
|
317 |
+
if 'lgf' in types:
|
318 |
+
# Transform sequence (multiplication by (-1)^(n+1) / n)
|
319 |
+
w, f = [], S.NegativeOne
|
320 |
+
for i, k in enumerate(v):
|
321 |
+
f = -f
|
322 |
+
w.append(f*k/Integer(i+1))
|
323 |
+
# Perform some convolutions of the sequence with itself
|
324 |
+
t = [1] + [0]*(len(w) - 1)
|
325 |
+
for d in range(max(1, maxsqrtn)):
|
326 |
+
t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
|
327 |
+
g = guess_generating_function_rational(t, X=X)
|
328 |
+
if g:
|
329 |
+
result['lgf'] = g**Rational(1, d+1)
|
330 |
+
break
|
331 |
+
|
332 |
+
# Hyperbolic logarithmic Generating Function (hlgf)
|
333 |
+
if 'hlgf' in types:
|
334 |
+
# Transform sequence (division by n+1)
|
335 |
+
w = []
|
336 |
+
for i, k in enumerate(v):
|
337 |
+
w.append(k/Integer(i+1))
|
338 |
+
# Perform some convolutions of the sequence with itself
|
339 |
+
t = [1] + [0]*(len(w) - 1)
|
340 |
+
for d in range(max(1, maxsqrtn)):
|
341 |
+
t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
|
342 |
+
g = guess_generating_function_rational(t, X=X)
|
343 |
+
if g:
|
344 |
+
result['hlgf'] = g**Rational(1, d+1)
|
345 |
+
break
|
346 |
+
|
347 |
+
# Logarithmic derivative of ordinary generating Function (lgdogf)
|
348 |
+
if v[0] != 0 and ('lgdogf' in types
|
349 |
+
or ('ogf' in types and 'ogf' not in result)):
|
350 |
+
# Transform sequence by computing f'(x)/f(x)
|
351 |
+
# because log(f(x)) = integrate( f'(x)/f(x) )
|
352 |
+
a, w = sympify(v[0]), []
|
353 |
+
for n in range(len(v)-1):
|
354 |
+
w.append(
|
355 |
+
(v[n+1]*(n+1) - sum(w[-i-1]*v[i+1] for i in range(n)))/a)
|
356 |
+
# Perform some convolutions of the sequence with itself
|
357 |
+
t = [1] + [0]*(len(w) - 1)
|
358 |
+
for d in range(max(1, maxsqrtn)):
|
359 |
+
t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
|
360 |
+
g = guess_generating_function_rational(t, X=X)
|
361 |
+
if g:
|
362 |
+
result['lgdogf'] = g**Rational(1, d+1)
|
363 |
+
if 'ogf' not in result:
|
364 |
+
result['ogf'] = exp(integrate(result['lgdogf'], X))
|
365 |
+
break
|
366 |
+
|
367 |
+
# Logarithmic derivative of exponential generating Function (lgdegf)
|
368 |
+
if v[0] != 0 and ('lgdegf' in types
|
369 |
+
or ('egf' in types and 'egf' not in result)):
|
370 |
+
# Transform sequence / step 1 (division by factorial)
|
371 |
+
z, f = [], S.One
|
372 |
+
for i, k in enumerate(v):
|
373 |
+
f *= i if i else 1
|
374 |
+
z.append(k/f)
|
375 |
+
# Transform sequence / step 2 by computing f'(x)/f(x)
|
376 |
+
# because log(f(x)) = integrate( f'(x)/f(x) )
|
377 |
+
a, w = z[0], []
|
378 |
+
for n in range(len(z)-1):
|
379 |
+
w.append(
|
380 |
+
(z[n+1]*(n+1) - sum(w[-i-1]*z[i+1] for i in range(n)))/a)
|
381 |
+
# Perform some convolutions of the sequence with itself
|
382 |
+
t = [1] + [0]*(len(w) - 1)
|
383 |
+
for d in range(max(1, maxsqrtn)):
|
384 |
+
t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))]
|
385 |
+
g = guess_generating_function_rational(t, X=X)
|
386 |
+
if g:
|
387 |
+
result['lgdegf'] = g**Rational(1, d+1)
|
388 |
+
if 'egf' not in result:
|
389 |
+
result['egf'] = exp(integrate(result['lgdegf'], X))
|
390 |
+
break
|
391 |
+
|
392 |
+
return result
|
393 |
+
|
394 |
+
|
395 |
+
@public
|
396 |
+
def guess(l, all=False, evaluate=True, niter=2, variables=None):
|
397 |
+
"""
|
398 |
+
This function is adapted from the Rate.m package for Mathematica
|
399 |
+
written by Christian Krattenthaler.
|
400 |
+
It tries to guess a formula from a given sequence of rational numbers.
|
401 |
+
|
402 |
+
Explanation
|
403 |
+
===========
|
404 |
+
|
405 |
+
In order to speed up the process, the 'all' variable is set to False by
|
406 |
+
default, stopping the computation as some results are returned during an
|
407 |
+
iteration; the variable can be set to True if more iterations are needed
|
408 |
+
(other formulas may be found; however they may be equivalent to the first
|
409 |
+
ones).
|
410 |
+
|
411 |
+
Another option is the 'evaluate' variable (default is True); setting it
|
412 |
+
to False will leave the involved products unevaluated.
|
413 |
+
|
414 |
+
By default, the number of iterations is set to 2 but a greater value (up
|
415 |
+
to len(l)-1) can be specified with the optional 'niter' variable.
|
416 |
+
More and more convoluted results are found when the order of the
|
417 |
+
iteration gets higher:
|
418 |
+
|
419 |
+
* first iteration returns polynomial or rational functions;
|
420 |
+
* second iteration returns products of rising factorials and their
|
421 |
+
inverses;
|
422 |
+
* third iteration returns products of products of rising factorials
|
423 |
+
and their inverses;
|
424 |
+
* etc.
|
425 |
+
|
426 |
+
The returned formulas contain symbols i0, i1, i2, ... where the main
|
427 |
+
variables is i0 (and auxiliary variables are i1, i2, ...). A list of
|
428 |
+
other symbols can be provided in the 'variables' option; the length of
|
429 |
+
the least should be the value of 'niter' (more is acceptable but only
|
430 |
+
the first symbols will be used); in this case, the main variable will be
|
431 |
+
the first symbol in the list.
|
432 |
+
|
433 |
+
Examples
|
434 |
+
========
|
435 |
+
|
436 |
+
>>> from sympy.concrete.guess import guess
|
437 |
+
>>> guess([1,2,6,24,120], evaluate=False)
|
438 |
+
[Product(i1 + 1, (i1, 1, i0 - 1))]
|
439 |
+
|
440 |
+
>>> from sympy import symbols
|
441 |
+
>>> r = guess([1,2,7,42,429,7436,218348,10850216], niter=4)
|
442 |
+
>>> i0 = symbols("i0")
|
443 |
+
>>> [r[0].subs(i0,n).doit() for n in range(1,10)]
|
444 |
+
[1, 2, 7, 42, 429, 7436, 218348, 10850216, 911835460]
|
445 |
+
"""
|
446 |
+
if any(a==0 for a in l[:-1]):
|
447 |
+
return []
|
448 |
+
N = len(l)
|
449 |
+
niter = min(N-1, niter)
|
450 |
+
myprod = product if evaluate else Product
|
451 |
+
g = []
|
452 |
+
res = []
|
453 |
+
if variables is None:
|
454 |
+
symb = symbols('i:'+str(niter))
|
455 |
+
else:
|
456 |
+
symb = variables
|
457 |
+
for k, s in enumerate(symb):
|
458 |
+
g.append(l)
|
459 |
+
n, r = len(l), []
|
460 |
+
for i in range(n-2-1, -1, -1):
|
461 |
+
ri = rinterp(enumerate(g[k][:-1], start=1), i, X=s)
|
462 |
+
if ((denom(ri).subs({s:n}) != 0)
|
463 |
+
and (ri.subs({s:n}) - g[k][-1] == 0)
|
464 |
+
and ri not in r):
|
465 |
+
r.append(ri)
|
466 |
+
if r:
|
467 |
+
for i in range(k-1, -1, -1):
|
468 |
+
r = [g[i][0]
|
469 |
+
* myprod(v, (symb[i+1], 1, symb[i]-1)) for v in r]
|
470 |
+
if not all: return r
|
471 |
+
res += r
|
472 |
+
l = [Rational(l[i+1], l[i]) for i in range(N-k-1)]
|
473 |
+
return res
|
env-llmeval/lib/python3.10/site-packages/sympy/concrete/products.py
ADDED
@@ -0,0 +1,610 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Tuple as tTuple
|
2 |
+
|
3 |
+
from .expr_with_intlimits import ExprWithIntLimits
|
4 |
+
from .summations import Sum, summation, _dummy_with_inherited_properties_concrete
|
5 |
+
from sympy.core.expr import Expr
|
6 |
+
from sympy.core.exprtools import factor_terms
|
7 |
+
from sympy.core.function import Derivative
|
8 |
+
from sympy.core.mul import Mul
|
9 |
+
from sympy.core.singleton import S
|
10 |
+
from sympy.core.symbol import Dummy, Symbol
|
11 |
+
from sympy.functions.combinatorial.factorials import RisingFactorial
|
12 |
+
from sympy.functions.elementary.exponential import exp, log
|
13 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
14 |
+
from sympy.polys import quo, roots
|
15 |
+
|
16 |
+
|
17 |
+
class Product(ExprWithIntLimits):
|
18 |
+
r"""
|
19 |
+
Represents unevaluated products.
|
20 |
+
|
21 |
+
Explanation
|
22 |
+
===========
|
23 |
+
|
24 |
+
``Product`` represents a finite or infinite product, with the first
|
25 |
+
argument being the general form of terms in the series, and the second
|
26 |
+
argument being ``(dummy_variable, start, end)``, with ``dummy_variable``
|
27 |
+
taking all integer values from ``start`` through ``end``. In accordance
|
28 |
+
with long-standing mathematical convention, the end term is included in
|
29 |
+
the product.
|
30 |
+
|
31 |
+
Finite products
|
32 |
+
===============
|
33 |
+
|
34 |
+
For finite products (and products with symbolic limits assumed to be finite)
|
35 |
+
we follow the analogue of the summation convention described by Karr [1],
|
36 |
+
especially definition 3 of section 1.4. The product:
|
37 |
+
|
38 |
+
.. math::
|
39 |
+
|
40 |
+
\prod_{m \leq i < n} f(i)
|
41 |
+
|
42 |
+
has *the obvious meaning* for `m < n`, namely:
|
43 |
+
|
44 |
+
.. math::
|
45 |
+
|
46 |
+
\prod_{m \leq i < n} f(i) = f(m) f(m+1) \cdot \ldots \cdot f(n-2) f(n-1)
|
47 |
+
|
48 |
+
with the upper limit value `f(n)` excluded. The product over an empty set is
|
49 |
+
one if and only if `m = n`:
|
50 |
+
|
51 |
+
.. math::
|
52 |
+
|
53 |
+
\prod_{m \leq i < n} f(i) = 1 \quad \mathrm{for} \quad m = n
|
54 |
+
|
55 |
+
Finally, for all other products over empty sets we assume the following
|
56 |
+
definition:
|
57 |
+
|
58 |
+
.. math::
|
59 |
+
|
60 |
+
\prod_{m \leq i < n} f(i) = \frac{1}{\prod_{n \leq i < m} f(i)} \quad \mathrm{for} \quad m > n
|
61 |
+
|
62 |
+
It is important to note that above we define all products with the upper
|
63 |
+
limit being exclusive. This is in contrast to the usual mathematical notation,
|
64 |
+
but does not affect the product convention. Indeed we have:
|
65 |
+
|
66 |
+
.. math::
|
67 |
+
|
68 |
+
\prod_{m \leq i < n} f(i) = \prod_{i = m}^{n - 1} f(i)
|
69 |
+
|
70 |
+
where the difference in notation is intentional to emphasize the meaning,
|
71 |
+
with limits typeset on the top being inclusive.
|
72 |
+
|
73 |
+
Examples
|
74 |
+
========
|
75 |
+
|
76 |
+
>>> from sympy.abc import a, b, i, k, m, n, x
|
77 |
+
>>> from sympy import Product, oo
|
78 |
+
>>> Product(k, (k, 1, m))
|
79 |
+
Product(k, (k, 1, m))
|
80 |
+
>>> Product(k, (k, 1, m)).doit()
|
81 |
+
factorial(m)
|
82 |
+
>>> Product(k**2,(k, 1, m))
|
83 |
+
Product(k**2, (k, 1, m))
|
84 |
+
>>> Product(k**2,(k, 1, m)).doit()
|
85 |
+
factorial(m)**2
|
86 |
+
|
87 |
+
Wallis' product for pi:
|
88 |
+
|
89 |
+
>>> W = Product(2*i/(2*i-1) * 2*i/(2*i+1), (i, 1, oo))
|
90 |
+
>>> W
|
91 |
+
Product(4*i**2/((2*i - 1)*(2*i + 1)), (i, 1, oo))
|
92 |
+
|
93 |
+
Direct computation currently fails:
|
94 |
+
|
95 |
+
>>> W.doit()
|
96 |
+
Product(4*i**2/((2*i - 1)*(2*i + 1)), (i, 1, oo))
|
97 |
+
|
98 |
+
But we can approach the infinite product by a limit of finite products:
|
99 |
+
|
100 |
+
>>> from sympy import limit
|
101 |
+
>>> W2 = Product(2*i/(2*i-1)*2*i/(2*i+1), (i, 1, n))
|
102 |
+
>>> W2
|
103 |
+
Product(4*i**2/((2*i - 1)*(2*i + 1)), (i, 1, n))
|
104 |
+
>>> W2e = W2.doit()
|
105 |
+
>>> W2e
|
106 |
+
4**n*factorial(n)**2/(2**(2*n)*RisingFactorial(1/2, n)*RisingFactorial(3/2, n))
|
107 |
+
>>> limit(W2e, n, oo)
|
108 |
+
pi/2
|
109 |
+
|
110 |
+
By the same formula we can compute sin(pi/2):
|
111 |
+
|
112 |
+
>>> from sympy import combsimp, pi, gamma, simplify
|
113 |
+
>>> P = pi * x * Product(1 - x**2/k**2, (k, 1, n))
|
114 |
+
>>> P = P.subs(x, pi/2)
|
115 |
+
>>> P
|
116 |
+
pi**2*Product(1 - pi**2/(4*k**2), (k, 1, n))/2
|
117 |
+
>>> Pe = P.doit()
|
118 |
+
>>> Pe
|
119 |
+
pi**2*RisingFactorial(1 - pi/2, n)*RisingFactorial(1 + pi/2, n)/(2*factorial(n)**2)
|
120 |
+
>>> limit(Pe, n, oo).gammasimp()
|
121 |
+
sin(pi**2/2)
|
122 |
+
>>> Pe.rewrite(gamma)
|
123 |
+
(-1)**n*pi**2*gamma(pi/2)*gamma(n + 1 + pi/2)/(2*gamma(1 + pi/2)*gamma(-n + pi/2)*gamma(n + 1)**2)
|
124 |
+
|
125 |
+
Products with the lower limit being larger than the upper one:
|
126 |
+
|
127 |
+
>>> Product(1/i, (i, 6, 1)).doit()
|
128 |
+
120
|
129 |
+
>>> Product(i, (i, 2, 5)).doit()
|
130 |
+
120
|
131 |
+
|
132 |
+
The empty product:
|
133 |
+
|
134 |
+
>>> Product(i, (i, n, n-1)).doit()
|
135 |
+
1
|
136 |
+
|
137 |
+
An example showing that the symbolic result of a product is still
|
138 |
+
valid for seemingly nonsensical values of the limits. Then the Karr
|
139 |
+
convention allows us to give a perfectly valid interpretation to
|
140 |
+
those products by interchanging the limits according to the above rules:
|
141 |
+
|
142 |
+
>>> P = Product(2, (i, 10, n)).doit()
|
143 |
+
>>> P
|
144 |
+
2**(n - 9)
|
145 |
+
>>> P.subs(n, 5)
|
146 |
+
1/16
|
147 |
+
>>> Product(2, (i, 10, 5)).doit()
|
148 |
+
1/16
|
149 |
+
>>> 1/Product(2, (i, 6, 9)).doit()
|
150 |
+
1/16
|
151 |
+
|
152 |
+
An explicit example of the Karr summation convention applied to products:
|
153 |
+
|
154 |
+
>>> P1 = Product(x, (i, a, b)).doit()
|
155 |
+
>>> P1
|
156 |
+
x**(-a + b + 1)
|
157 |
+
>>> P2 = Product(x, (i, b+1, a-1)).doit()
|
158 |
+
>>> P2
|
159 |
+
x**(a - b - 1)
|
160 |
+
>>> simplify(P1 * P2)
|
161 |
+
1
|
162 |
+
|
163 |
+
And another one:
|
164 |
+
|
165 |
+
>>> P1 = Product(i, (i, b, a)).doit()
|
166 |
+
>>> P1
|
167 |
+
RisingFactorial(b, a - b + 1)
|
168 |
+
>>> P2 = Product(i, (i, a+1, b-1)).doit()
|
169 |
+
>>> P2
|
170 |
+
RisingFactorial(a + 1, -a + b - 1)
|
171 |
+
>>> P1 * P2
|
172 |
+
RisingFactorial(b, a - b + 1)*RisingFactorial(a + 1, -a + b - 1)
|
173 |
+
>>> combsimp(P1 * P2)
|
174 |
+
1
|
175 |
+
|
176 |
+
See Also
|
177 |
+
========
|
178 |
+
|
179 |
+
Sum, summation
|
180 |
+
product
|
181 |
+
|
182 |
+
References
|
183 |
+
==========
|
184 |
+
|
185 |
+
.. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
|
186 |
+
Volume 28 Issue 2, April 1981, Pages 305-350
|
187 |
+
https://dl.acm.org/doi/10.1145/322248.322255
|
188 |
+
.. [2] https://en.wikipedia.org/wiki/Multiplication#Capital_Pi_notation
|
189 |
+
.. [3] https://en.wikipedia.org/wiki/Empty_product
|
190 |
+
"""
|
191 |
+
|
192 |
+
__slots__ = ()
|
193 |
+
|
194 |
+
limits: tTuple[tTuple[Symbol, Expr, Expr]]
|
195 |
+
|
196 |
+
def __new__(cls, function, *symbols, **assumptions):
|
197 |
+
obj = ExprWithIntLimits.__new__(cls, function, *symbols, **assumptions)
|
198 |
+
return obj
|
199 |
+
|
200 |
+
def _eval_rewrite_as_Sum(self, *args, **kwargs):
|
201 |
+
return exp(Sum(log(self.function), *self.limits))
|
202 |
+
|
203 |
+
@property
|
204 |
+
def term(self):
|
205 |
+
return self._args[0]
|
206 |
+
function = term
|
207 |
+
|
208 |
+
def _eval_is_zero(self):
|
209 |
+
if self.has_empty_sequence:
|
210 |
+
return False
|
211 |
+
|
212 |
+
z = self.term.is_zero
|
213 |
+
if z is True:
|
214 |
+
return True
|
215 |
+
if self.has_finite_limits:
|
216 |
+
# A Product is zero only if its term is zero assuming finite limits.
|
217 |
+
return z
|
218 |
+
|
219 |
+
def _eval_is_extended_real(self):
|
220 |
+
if self.has_empty_sequence:
|
221 |
+
return True
|
222 |
+
|
223 |
+
return self.function.is_extended_real
|
224 |
+
|
225 |
+
def _eval_is_positive(self):
|
226 |
+
if self.has_empty_sequence:
|
227 |
+
return True
|
228 |
+
if self.function.is_positive and self.has_finite_limits:
|
229 |
+
return True
|
230 |
+
|
231 |
+
def _eval_is_nonnegative(self):
|
232 |
+
if self.has_empty_sequence:
|
233 |
+
return True
|
234 |
+
if self.function.is_nonnegative and self.has_finite_limits:
|
235 |
+
return True
|
236 |
+
|
237 |
+
def _eval_is_extended_nonnegative(self):
|
238 |
+
if self.has_empty_sequence:
|
239 |
+
return True
|
240 |
+
if self.function.is_extended_nonnegative:
|
241 |
+
return True
|
242 |
+
|
243 |
+
def _eval_is_extended_nonpositive(self):
|
244 |
+
if self.has_empty_sequence:
|
245 |
+
return True
|
246 |
+
|
247 |
+
def _eval_is_finite(self):
|
248 |
+
if self.has_finite_limits and self.function.is_finite:
|
249 |
+
return True
|
250 |
+
|
251 |
+
def doit(self, **hints):
|
252 |
+
# first make sure any definite limits have product
|
253 |
+
# variables with matching assumptions
|
254 |
+
reps = {}
|
255 |
+
for xab in self.limits:
|
256 |
+
d = _dummy_with_inherited_properties_concrete(xab)
|
257 |
+
if d:
|
258 |
+
reps[xab[0]] = d
|
259 |
+
if reps:
|
260 |
+
undo = {v: k for k, v in reps.items()}
|
261 |
+
did = self.xreplace(reps).doit(**hints)
|
262 |
+
if isinstance(did, tuple): # when separate=True
|
263 |
+
did = tuple([i.xreplace(undo) for i in did])
|
264 |
+
else:
|
265 |
+
did = did.xreplace(undo)
|
266 |
+
return did
|
267 |
+
|
268 |
+
from sympy.simplify.powsimp import powsimp
|
269 |
+
f = self.function
|
270 |
+
for index, limit in enumerate(self.limits):
|
271 |
+
i, a, b = limit
|
272 |
+
dif = b - a
|
273 |
+
if dif.is_integer and dif.is_negative:
|
274 |
+
a, b = b + 1, a - 1
|
275 |
+
f = 1 / f
|
276 |
+
|
277 |
+
g = self._eval_product(f, (i, a, b))
|
278 |
+
if g in (None, S.NaN):
|
279 |
+
return self.func(powsimp(f), *self.limits[index:])
|
280 |
+
else:
|
281 |
+
f = g
|
282 |
+
|
283 |
+
if hints.get('deep', True):
|
284 |
+
return f.doit(**hints)
|
285 |
+
else:
|
286 |
+
return powsimp(f)
|
287 |
+
|
288 |
+
def _eval_adjoint(self):
|
289 |
+
if self.is_commutative:
|
290 |
+
return self.func(self.function.adjoint(), *self.limits)
|
291 |
+
return None
|
292 |
+
|
293 |
+
def _eval_conjugate(self):
|
294 |
+
return self.func(self.function.conjugate(), *self.limits)
|
295 |
+
|
296 |
+
def _eval_product(self, term, limits):
|
297 |
+
|
298 |
+
(k, a, n) = limits
|
299 |
+
|
300 |
+
if k not in term.free_symbols:
|
301 |
+
if (term - 1).is_zero:
|
302 |
+
return S.One
|
303 |
+
return term**(n - a + 1)
|
304 |
+
|
305 |
+
if a == n:
|
306 |
+
return term.subs(k, a)
|
307 |
+
|
308 |
+
from .delta import deltaproduct, _has_simple_delta
|
309 |
+
if term.has(KroneckerDelta) and _has_simple_delta(term, limits[0]):
|
310 |
+
return deltaproduct(term, limits)
|
311 |
+
|
312 |
+
dif = n - a
|
313 |
+
definite = dif.is_Integer
|
314 |
+
if definite and (dif < 100):
|
315 |
+
return self._eval_product_direct(term, limits)
|
316 |
+
|
317 |
+
elif term.is_polynomial(k):
|
318 |
+
poly = term.as_poly(k)
|
319 |
+
|
320 |
+
A = B = Q = S.One
|
321 |
+
|
322 |
+
all_roots = roots(poly)
|
323 |
+
|
324 |
+
M = 0
|
325 |
+
for r, m in all_roots.items():
|
326 |
+
M += m
|
327 |
+
A *= RisingFactorial(a - r, n - a + 1)**m
|
328 |
+
Q *= (n - r)**m
|
329 |
+
|
330 |
+
if M < poly.degree():
|
331 |
+
arg = quo(poly, Q.as_poly(k))
|
332 |
+
B = self.func(arg, (k, a, n)).doit()
|
333 |
+
|
334 |
+
return poly.LC()**(n - a + 1) * A * B
|
335 |
+
|
336 |
+
elif term.is_Add:
|
337 |
+
factored = factor_terms(term, fraction=True)
|
338 |
+
if factored.is_Mul:
|
339 |
+
return self._eval_product(factored, (k, a, n))
|
340 |
+
|
341 |
+
elif term.is_Mul:
|
342 |
+
# Factor in part without the summation variable and part with
|
343 |
+
without_k, with_k = term.as_coeff_mul(k)
|
344 |
+
|
345 |
+
if len(with_k) >= 2:
|
346 |
+
# More than one term including k, so still a multiplication
|
347 |
+
exclude, include = [], []
|
348 |
+
for t in with_k:
|
349 |
+
p = self._eval_product(t, (k, a, n))
|
350 |
+
|
351 |
+
if p is not None:
|
352 |
+
exclude.append(p)
|
353 |
+
else:
|
354 |
+
include.append(t)
|
355 |
+
|
356 |
+
if not exclude:
|
357 |
+
return None
|
358 |
+
else:
|
359 |
+
arg = term._new_rawargs(*include)
|
360 |
+
A = Mul(*exclude)
|
361 |
+
B = self.func(arg, (k, a, n)).doit()
|
362 |
+
return without_k**(n - a + 1)*A * B
|
363 |
+
else:
|
364 |
+
# Just a single term
|
365 |
+
p = self._eval_product(with_k[0], (k, a, n))
|
366 |
+
if p is None:
|
367 |
+
p = self.func(with_k[0], (k, a, n)).doit()
|
368 |
+
return without_k**(n - a + 1)*p
|
369 |
+
|
370 |
+
|
371 |
+
elif term.is_Pow:
|
372 |
+
if not term.base.has(k):
|
373 |
+
s = summation(term.exp, (k, a, n))
|
374 |
+
|
375 |
+
return term.base**s
|
376 |
+
elif not term.exp.has(k):
|
377 |
+
p = self._eval_product(term.base, (k, a, n))
|
378 |
+
|
379 |
+
if p is not None:
|
380 |
+
return p**term.exp
|
381 |
+
|
382 |
+
elif isinstance(term, Product):
|
383 |
+
evaluated = term.doit()
|
384 |
+
f = self._eval_product(evaluated, limits)
|
385 |
+
if f is None:
|
386 |
+
return self.func(evaluated, limits)
|
387 |
+
else:
|
388 |
+
return f
|
389 |
+
|
390 |
+
if definite:
|
391 |
+
return self._eval_product_direct(term, limits)
|
392 |
+
|
393 |
+
def _eval_simplify(self, **kwargs):
|
394 |
+
from sympy.simplify.simplify import product_simplify
|
395 |
+
rv = product_simplify(self, **kwargs)
|
396 |
+
return rv.doit() if kwargs['doit'] else rv
|
397 |
+
|
398 |
+
def _eval_transpose(self):
|
399 |
+
if self.is_commutative:
|
400 |
+
return self.func(self.function.transpose(), *self.limits)
|
401 |
+
return None
|
402 |
+
|
403 |
+
def _eval_product_direct(self, term, limits):
|
404 |
+
(k, a, n) = limits
|
405 |
+
return Mul(*[term.subs(k, a + i) for i in range(n - a + 1)])
|
406 |
+
|
407 |
+
def _eval_derivative(self, x):
|
408 |
+
if isinstance(x, Symbol) and x not in self.free_symbols:
|
409 |
+
return S.Zero
|
410 |
+
f, limits = self.function, list(self.limits)
|
411 |
+
limit = limits.pop(-1)
|
412 |
+
if limits:
|
413 |
+
f = self.func(f, *limits)
|
414 |
+
i, a, b = limit
|
415 |
+
if x in a.free_symbols or x in b.free_symbols:
|
416 |
+
return None
|
417 |
+
h = Dummy()
|
418 |
+
rv = Sum( Product(f, (i, a, h - 1)) * Product(f, (i, h + 1, b)) * Derivative(f, x, evaluate=True).subs(i, h), (h, a, b))
|
419 |
+
return rv
|
420 |
+
|
421 |
+
def is_convergent(self):
|
422 |
+
r"""
|
423 |
+
See docs of :obj:`.Sum.is_convergent()` for explanation of convergence
|
424 |
+
in SymPy.
|
425 |
+
|
426 |
+
Explanation
|
427 |
+
===========
|
428 |
+
|
429 |
+
The infinite product:
|
430 |
+
|
431 |
+
.. math::
|
432 |
+
|
433 |
+
\prod_{1 \leq i < \infty} f(i)
|
434 |
+
|
435 |
+
is defined by the sequence of partial products:
|
436 |
+
|
437 |
+
.. math::
|
438 |
+
|
439 |
+
\prod_{i=1}^{n} f(i) = f(1) f(2) \cdots f(n)
|
440 |
+
|
441 |
+
as n increases without bound. The product converges to a non-zero
|
442 |
+
value if and only if the sum:
|
443 |
+
|
444 |
+
.. math::
|
445 |
+
|
446 |
+
\sum_{1 \leq i < \infty} \log{f(n)}
|
447 |
+
|
448 |
+
converges.
|
449 |
+
|
450 |
+
Examples
|
451 |
+
========
|
452 |
+
|
453 |
+
>>> from sympy import Product, Symbol, cos, pi, exp, oo
|
454 |
+
>>> n = Symbol('n', integer=True)
|
455 |
+
>>> Product(n/(n + 1), (n, 1, oo)).is_convergent()
|
456 |
+
False
|
457 |
+
>>> Product(1/n**2, (n, 1, oo)).is_convergent()
|
458 |
+
False
|
459 |
+
>>> Product(cos(pi/n), (n, 1, oo)).is_convergent()
|
460 |
+
True
|
461 |
+
>>> Product(exp(-n**2), (n, 1, oo)).is_convergent()
|
462 |
+
False
|
463 |
+
|
464 |
+
References
|
465 |
+
==========
|
466 |
+
|
467 |
+
.. [1] https://en.wikipedia.org/wiki/Infinite_product
|
468 |
+
"""
|
469 |
+
sequence_term = self.function
|
470 |
+
log_sum = log(sequence_term)
|
471 |
+
lim = self.limits
|
472 |
+
try:
|
473 |
+
is_conv = Sum(log_sum, *lim).is_convergent()
|
474 |
+
except NotImplementedError:
|
475 |
+
if Sum(sequence_term - 1, *lim).is_absolutely_convergent() is S.true:
|
476 |
+
return S.true
|
477 |
+
raise NotImplementedError("The algorithm to find the product convergence of %s "
|
478 |
+
"is not yet implemented" % (sequence_term))
|
479 |
+
return is_conv
|
480 |
+
|
481 |
+
def reverse_order(expr, *indices):
|
482 |
+
"""
|
483 |
+
Reverse the order of a limit in a Product.
|
484 |
+
|
485 |
+
Explanation
|
486 |
+
===========
|
487 |
+
|
488 |
+
``reverse_order(expr, *indices)`` reverses some limits in the expression
|
489 |
+
``expr`` which can be either a ``Sum`` or a ``Product``. The selectors in
|
490 |
+
the argument ``indices`` specify some indices whose limits get reversed.
|
491 |
+
These selectors are either variable names or numerical indices counted
|
492 |
+
starting from the inner-most limit tuple.
|
493 |
+
|
494 |
+
Examples
|
495 |
+
========
|
496 |
+
|
497 |
+
>>> from sympy import gamma, Product, simplify, Sum
|
498 |
+
>>> from sympy.abc import x, y, a, b, c, d
|
499 |
+
>>> P = Product(x, (x, a, b))
|
500 |
+
>>> Pr = P.reverse_order(x)
|
501 |
+
>>> Pr
|
502 |
+
Product(1/x, (x, b + 1, a - 1))
|
503 |
+
>>> Pr = Pr.doit()
|
504 |
+
>>> Pr
|
505 |
+
1/RisingFactorial(b + 1, a - b - 1)
|
506 |
+
>>> simplify(Pr.rewrite(gamma))
|
507 |
+
Piecewise((gamma(b + 1)/gamma(a), b > -1), ((-1)**(-a + b + 1)*gamma(1 - a)/gamma(-b), True))
|
508 |
+
>>> P = P.doit()
|
509 |
+
>>> P
|
510 |
+
RisingFactorial(a, -a + b + 1)
|
511 |
+
>>> simplify(P.rewrite(gamma))
|
512 |
+
Piecewise((gamma(b + 1)/gamma(a), a > 0), ((-1)**(-a + b + 1)*gamma(1 - a)/gamma(-b), True))
|
513 |
+
|
514 |
+
While one should prefer variable names when specifying which limits
|
515 |
+
to reverse, the index counting notation comes in handy in case there
|
516 |
+
are several symbols with the same name.
|
517 |
+
|
518 |
+
>>> S = Sum(x*y, (x, a, b), (y, c, d))
|
519 |
+
>>> S
|
520 |
+
Sum(x*y, (x, a, b), (y, c, d))
|
521 |
+
>>> S0 = S.reverse_order(0)
|
522 |
+
>>> S0
|
523 |
+
Sum(-x*y, (x, b + 1, a - 1), (y, c, d))
|
524 |
+
>>> S1 = S0.reverse_order(1)
|
525 |
+
>>> S1
|
526 |
+
Sum(x*y, (x, b + 1, a - 1), (y, d + 1, c - 1))
|
527 |
+
|
528 |
+
Of course we can mix both notations:
|
529 |
+
|
530 |
+
>>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1)
|
531 |
+
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
|
532 |
+
>>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x)
|
533 |
+
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
|
534 |
+
|
535 |
+
See Also
|
536 |
+
========
|
537 |
+
|
538 |
+
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index,
|
539 |
+
reorder_limit,
|
540 |
+
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder
|
541 |
+
|
542 |
+
References
|
543 |
+
==========
|
544 |
+
|
545 |
+
.. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
|
546 |
+
Volume 28 Issue 2, April 1981, Pages 305-350
|
547 |
+
https://dl.acm.org/doi/10.1145/322248.322255
|
548 |
+
|
549 |
+
"""
|
550 |
+
l_indices = list(indices)
|
551 |
+
|
552 |
+
for i, indx in enumerate(l_indices):
|
553 |
+
if not isinstance(indx, int):
|
554 |
+
l_indices[i] = expr.index(indx)
|
555 |
+
|
556 |
+
e = 1
|
557 |
+
limits = []
|
558 |
+
for i, limit in enumerate(expr.limits):
|
559 |
+
l = limit
|
560 |
+
if i in l_indices:
|
561 |
+
e = -e
|
562 |
+
l = (limit[0], limit[2] + 1, limit[1] - 1)
|
563 |
+
limits.append(l)
|
564 |
+
|
565 |
+
return Product(expr.function ** e, *limits)
|
566 |
+
|
567 |
+
|
568 |
+
def product(*args, **kwargs):
|
569 |
+
r"""
|
570 |
+
Compute the product.
|
571 |
+
|
572 |
+
Explanation
|
573 |
+
===========
|
574 |
+
|
575 |
+
The notation for symbols is similar to the notation used in Sum or
|
576 |
+
Integral. product(f, (i, a, b)) computes the product of f with
|
577 |
+
respect to i from a to b, i.e.,
|
578 |
+
|
579 |
+
::
|
580 |
+
|
581 |
+
b
|
582 |
+
_____
|
583 |
+
product(f(n), (i, a, b)) = | | f(n)
|
584 |
+
| |
|
585 |
+
i = a
|
586 |
+
|
587 |
+
If it cannot compute the product, it returns an unevaluated Product object.
|
588 |
+
Repeated products can be computed by introducing additional symbols tuples::
|
589 |
+
|
590 |
+
Examples
|
591 |
+
========
|
592 |
+
|
593 |
+
>>> from sympy import product, symbols
|
594 |
+
>>> i, n, m, k = symbols('i n m k', integer=True)
|
595 |
+
|
596 |
+
>>> product(i, (i, 1, k))
|
597 |
+
factorial(k)
|
598 |
+
>>> product(m, (i, 1, k))
|
599 |
+
m**k
|
600 |
+
>>> product(i, (i, 1, k), (k, 1, n))
|
601 |
+
Product(factorial(k), (k, 1, n))
|
602 |
+
|
603 |
+
"""
|
604 |
+
|
605 |
+
prod = Product(*args, **kwargs)
|
606 |
+
|
607 |
+
if isinstance(prod, Product):
|
608 |
+
return prod.doit(deep=False)
|
609 |
+
else:
|
610 |
+
return prod
|
env-llmeval/lib/python3.10/site-packages/sympy/concrete/summations.py
ADDED
@@ -0,0 +1,1646 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Tuple as tTuple
|
2 |
+
|
3 |
+
from sympy.calculus.singularities import is_decreasing
|
4 |
+
from sympy.calculus.accumulationbounds import AccumulationBounds
|
5 |
+
from .expr_with_intlimits import ExprWithIntLimits
|
6 |
+
from .expr_with_limits import AddWithLimits
|
7 |
+
from .gosper import gosper_sum
|
8 |
+
from sympy.core.expr import Expr
|
9 |
+
from sympy.core.add import Add
|
10 |
+
from sympy.core.containers import Tuple
|
11 |
+
from sympy.core.function import Derivative, expand
|
12 |
+
from sympy.core.mul import Mul
|
13 |
+
from sympy.core.numbers import Float, _illegal
|
14 |
+
from sympy.core.relational import Eq
|
15 |
+
from sympy.core.singleton import S
|
16 |
+
from sympy.core.sorting import ordered
|
17 |
+
from sympy.core.symbol import Dummy, Wild, Symbol, symbols
|
18 |
+
from sympy.functions.combinatorial.factorials import factorial
|
19 |
+
from sympy.functions.combinatorial.numbers import bernoulli, harmonic
|
20 |
+
from sympy.functions.elementary.exponential import exp, log
|
21 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
22 |
+
from sympy.functions.elementary.trigonometric import cot, csc
|
23 |
+
from sympy.functions.special.hyper import hyper
|
24 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
25 |
+
from sympy.functions.special.zeta_functions import zeta
|
26 |
+
from sympy.integrals.integrals import Integral
|
27 |
+
from sympy.logic.boolalg import And
|
28 |
+
from sympy.polys.partfrac import apart
|
29 |
+
from sympy.polys.polyerrors import PolynomialError, PolificationFailed
|
30 |
+
from sympy.polys.polytools import parallel_poly_from_expr, Poly, factor
|
31 |
+
from sympy.polys.rationaltools import together
|
32 |
+
from sympy.series.limitseq import limit_seq
|
33 |
+
from sympy.series.order import O
|
34 |
+
from sympy.series.residues import residue
|
35 |
+
from sympy.sets.sets import FiniteSet, Interval
|
36 |
+
from sympy.utilities.iterables import sift
|
37 |
+
import itertools
|
38 |
+
|
39 |
+
|
40 |
+
class Sum(AddWithLimits, ExprWithIntLimits):
|
41 |
+
r"""
|
42 |
+
Represents unevaluated summation.
|
43 |
+
|
44 |
+
Explanation
|
45 |
+
===========
|
46 |
+
|
47 |
+
``Sum`` represents a finite or infinite series, with the first argument
|
48 |
+
being the general form of terms in the series, and the second argument
|
49 |
+
being ``(dummy_variable, start, end)``, with ``dummy_variable`` taking
|
50 |
+
all integer values from ``start`` through ``end``. In accordance with
|
51 |
+
long-standing mathematical convention, the end term is included in the
|
52 |
+
summation.
|
53 |
+
|
54 |
+
Finite sums
|
55 |
+
===========
|
56 |
+
|
57 |
+
For finite sums (and sums with symbolic limits assumed to be finite) we
|
58 |
+
follow the summation convention described by Karr [1], especially
|
59 |
+
definition 3 of section 1.4. The sum:
|
60 |
+
|
61 |
+
.. math::
|
62 |
+
|
63 |
+
\sum_{m \leq i < n} f(i)
|
64 |
+
|
65 |
+
has *the obvious meaning* for `m < n`, namely:
|
66 |
+
|
67 |
+
.. math::
|
68 |
+
|
69 |
+
\sum_{m \leq i < n} f(i) = f(m) + f(m+1) + \ldots + f(n-2) + f(n-1)
|
70 |
+
|
71 |
+
with the upper limit value `f(n)` excluded. The sum over an empty set is
|
72 |
+
zero if and only if `m = n`:
|
73 |
+
|
74 |
+
.. math::
|
75 |
+
|
76 |
+
\sum_{m \leq i < n} f(i) = 0 \quad \mathrm{for} \quad m = n
|
77 |
+
|
78 |
+
Finally, for all other sums over empty sets we assume the following
|
79 |
+
definition:
|
80 |
+
|
81 |
+
.. math::
|
82 |
+
|
83 |
+
\sum_{m \leq i < n} f(i) = - \sum_{n \leq i < m} f(i) \quad \mathrm{for} \quad m > n
|
84 |
+
|
85 |
+
It is important to note that Karr defines all sums with the upper
|
86 |
+
limit being exclusive. This is in contrast to the usual mathematical notation,
|
87 |
+
but does not affect the summation convention. Indeed we have:
|
88 |
+
|
89 |
+
.. math::
|
90 |
+
|
91 |
+
\sum_{m \leq i < n} f(i) = \sum_{i = m}^{n - 1} f(i)
|
92 |
+
|
93 |
+
where the difference in notation is intentional to emphasize the meaning,
|
94 |
+
with limits typeset on the top being inclusive.
|
95 |
+
|
96 |
+
Examples
|
97 |
+
========
|
98 |
+
|
99 |
+
>>> from sympy.abc import i, k, m, n, x
|
100 |
+
>>> from sympy import Sum, factorial, oo, IndexedBase, Function
|
101 |
+
>>> Sum(k, (k, 1, m))
|
102 |
+
Sum(k, (k, 1, m))
|
103 |
+
>>> Sum(k, (k, 1, m)).doit()
|
104 |
+
m**2/2 + m/2
|
105 |
+
>>> Sum(k**2, (k, 1, m))
|
106 |
+
Sum(k**2, (k, 1, m))
|
107 |
+
>>> Sum(k**2, (k, 1, m)).doit()
|
108 |
+
m**3/3 + m**2/2 + m/6
|
109 |
+
>>> Sum(x**k, (k, 0, oo))
|
110 |
+
Sum(x**k, (k, 0, oo))
|
111 |
+
>>> Sum(x**k, (k, 0, oo)).doit()
|
112 |
+
Piecewise((1/(1 - x), Abs(x) < 1), (Sum(x**k, (k, 0, oo)), True))
|
113 |
+
>>> Sum(x**k/factorial(k), (k, 0, oo)).doit()
|
114 |
+
exp(x)
|
115 |
+
|
116 |
+
Here are examples to do summation with symbolic indices. You
|
117 |
+
can use either Function of IndexedBase classes:
|
118 |
+
|
119 |
+
>>> f = Function('f')
|
120 |
+
>>> Sum(f(n), (n, 0, 3)).doit()
|
121 |
+
f(0) + f(1) + f(2) + f(3)
|
122 |
+
>>> Sum(f(n), (n, 0, oo)).doit()
|
123 |
+
Sum(f(n), (n, 0, oo))
|
124 |
+
>>> f = IndexedBase('f')
|
125 |
+
>>> Sum(f[n]**2, (n, 0, 3)).doit()
|
126 |
+
f[0]**2 + f[1]**2 + f[2]**2 + f[3]**2
|
127 |
+
|
128 |
+
An example showing that the symbolic result of a summation is still
|
129 |
+
valid for seemingly nonsensical values of the limits. Then the Karr
|
130 |
+
convention allows us to give a perfectly valid interpretation to
|
131 |
+
those sums by interchanging the limits according to the above rules:
|
132 |
+
|
133 |
+
>>> S = Sum(i, (i, 1, n)).doit()
|
134 |
+
>>> S
|
135 |
+
n**2/2 + n/2
|
136 |
+
>>> S.subs(n, -4)
|
137 |
+
6
|
138 |
+
>>> Sum(i, (i, 1, -4)).doit()
|
139 |
+
6
|
140 |
+
>>> Sum(-i, (i, -3, 0)).doit()
|
141 |
+
6
|
142 |
+
|
143 |
+
An explicit example of the Karr summation convention:
|
144 |
+
|
145 |
+
>>> S1 = Sum(i**2, (i, m, m+n-1)).doit()
|
146 |
+
>>> S1
|
147 |
+
m**2*n + m*n**2 - m*n + n**3/3 - n**2/2 + n/6
|
148 |
+
>>> S2 = Sum(i**2, (i, m+n, m-1)).doit()
|
149 |
+
>>> S2
|
150 |
+
-m**2*n - m*n**2 + m*n - n**3/3 + n**2/2 - n/6
|
151 |
+
>>> S1 + S2
|
152 |
+
0
|
153 |
+
>>> S3 = Sum(i, (i, m, m-1)).doit()
|
154 |
+
>>> S3
|
155 |
+
0
|
156 |
+
|
157 |
+
See Also
|
158 |
+
========
|
159 |
+
|
160 |
+
summation
|
161 |
+
Product, sympy.concrete.products.product
|
162 |
+
|
163 |
+
References
|
164 |
+
==========
|
165 |
+
|
166 |
+
.. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
|
167 |
+
Volume 28 Issue 2, April 1981, Pages 305-350
|
168 |
+
https://dl.acm.org/doi/10.1145/322248.322255
|
169 |
+
.. [2] https://en.wikipedia.org/wiki/Summation#Capital-sigma_notation
|
170 |
+
.. [3] https://en.wikipedia.org/wiki/Empty_sum
|
171 |
+
"""
|
172 |
+
|
173 |
+
__slots__ = ()
|
174 |
+
|
175 |
+
limits: tTuple[tTuple[Symbol, Expr, Expr]]
|
176 |
+
|
177 |
+
def __new__(cls, function, *symbols, **assumptions):
|
178 |
+
obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
|
179 |
+
if not hasattr(obj, 'limits'):
|
180 |
+
return obj
|
181 |
+
if any(len(l) != 3 or None in l for l in obj.limits):
|
182 |
+
raise ValueError('Sum requires values for lower and upper bounds.')
|
183 |
+
|
184 |
+
return obj
|
185 |
+
|
186 |
+
def _eval_is_zero(self):
|
187 |
+
# a Sum is only zero if its function is zero or if all terms
|
188 |
+
# cancel out. This only answers whether the summand is zero; if
|
189 |
+
# not then None is returned since we don't analyze whether all
|
190 |
+
# terms cancel out.
|
191 |
+
if self.function.is_zero or self.has_empty_sequence:
|
192 |
+
return True
|
193 |
+
|
194 |
+
def _eval_is_extended_real(self):
|
195 |
+
if self.has_empty_sequence:
|
196 |
+
return True
|
197 |
+
return self.function.is_extended_real
|
198 |
+
|
199 |
+
def _eval_is_positive(self):
|
200 |
+
if self.has_finite_limits and self.has_reversed_limits is False:
|
201 |
+
return self.function.is_positive
|
202 |
+
|
203 |
+
def _eval_is_negative(self):
|
204 |
+
if self.has_finite_limits and self.has_reversed_limits is False:
|
205 |
+
return self.function.is_negative
|
206 |
+
|
207 |
+
def _eval_is_finite(self):
|
208 |
+
if self.has_finite_limits and self.function.is_finite:
|
209 |
+
return True
|
210 |
+
|
211 |
+
def doit(self, **hints):
|
212 |
+
if hints.get('deep', True):
|
213 |
+
f = self.function.doit(**hints)
|
214 |
+
else:
|
215 |
+
f = self.function
|
216 |
+
|
217 |
+
# first make sure any definite limits have summation
|
218 |
+
# variables with matching assumptions
|
219 |
+
reps = {}
|
220 |
+
for xab in self.limits:
|
221 |
+
d = _dummy_with_inherited_properties_concrete(xab)
|
222 |
+
if d:
|
223 |
+
reps[xab[0]] = d
|
224 |
+
if reps:
|
225 |
+
undo = {v: k for k, v in reps.items()}
|
226 |
+
did = self.xreplace(reps).doit(**hints)
|
227 |
+
if isinstance(did, tuple): # when separate=True
|
228 |
+
did = tuple([i.xreplace(undo) for i in did])
|
229 |
+
elif did is not None:
|
230 |
+
did = did.xreplace(undo)
|
231 |
+
else:
|
232 |
+
did = self
|
233 |
+
return did
|
234 |
+
|
235 |
+
|
236 |
+
if self.function.is_Matrix:
|
237 |
+
expanded = self.expand()
|
238 |
+
if self != expanded:
|
239 |
+
return expanded.doit()
|
240 |
+
return _eval_matrix_sum(self)
|
241 |
+
|
242 |
+
for n, limit in enumerate(self.limits):
|
243 |
+
i, a, b = limit
|
244 |
+
dif = b - a
|
245 |
+
if dif == -1:
|
246 |
+
# Any summation over an empty set is zero
|
247 |
+
return S.Zero
|
248 |
+
if dif.is_integer and dif.is_negative:
|
249 |
+
a, b = b + 1, a - 1
|
250 |
+
f = -f
|
251 |
+
|
252 |
+
newf = eval_sum(f, (i, a, b))
|
253 |
+
if newf is None:
|
254 |
+
if f == self.function:
|
255 |
+
zeta_function = self.eval_zeta_function(f, (i, a, b))
|
256 |
+
if zeta_function is not None:
|
257 |
+
return zeta_function
|
258 |
+
return self
|
259 |
+
else:
|
260 |
+
return self.func(f, *self.limits[n:])
|
261 |
+
f = newf
|
262 |
+
|
263 |
+
if hints.get('deep', True):
|
264 |
+
# eval_sum could return partially unevaluated
|
265 |
+
# result with Piecewise. In this case we won't
|
266 |
+
# doit() recursively.
|
267 |
+
if not isinstance(f, Piecewise):
|
268 |
+
return f.doit(**hints)
|
269 |
+
|
270 |
+
return f
|
271 |
+
|
272 |
+
def eval_zeta_function(self, f, limits):
|
273 |
+
"""
|
274 |
+
Check whether the function matches with the zeta function.
|
275 |
+
|
276 |
+
If it matches, then return a `Piecewise` expression because
|
277 |
+
zeta function does not converge unless `s > 1` and `q > 0`
|
278 |
+
"""
|
279 |
+
i, a, b = limits
|
280 |
+
w, y, z = Wild('w', exclude=[i]), Wild('y', exclude=[i]), Wild('z', exclude=[i])
|
281 |
+
result = f.match((w * i + y) ** (-z))
|
282 |
+
if result is not None and b is S.Infinity:
|
283 |
+
coeff = 1 / result[w] ** result[z]
|
284 |
+
s = result[z]
|
285 |
+
q = result[y] / result[w] + a
|
286 |
+
return Piecewise((coeff * zeta(s, q), And(q > 0, s > 1)), (self, True))
|
287 |
+
|
288 |
+
def _eval_derivative(self, x):
|
289 |
+
"""
|
290 |
+
Differentiate wrt x as long as x is not in the free symbols of any of
|
291 |
+
the upper or lower limits.
|
292 |
+
|
293 |
+
Explanation
|
294 |
+
===========
|
295 |
+
|
296 |
+
Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a`
|
297 |
+
since the value of the sum is discontinuous in `a`. In a case
|
298 |
+
involving a limit variable, the unevaluated derivative is returned.
|
299 |
+
"""
|
300 |
+
|
301 |
+
# diff already confirmed that x is in the free symbols of self, but we
|
302 |
+
# don't want to differentiate wrt any free symbol in the upper or lower
|
303 |
+
# limits
|
304 |
+
# XXX remove this test for free_symbols when the default _eval_derivative is in
|
305 |
+
if isinstance(x, Symbol) and x not in self.free_symbols:
|
306 |
+
return S.Zero
|
307 |
+
|
308 |
+
# get limits and the function
|
309 |
+
f, limits = self.function, list(self.limits)
|
310 |
+
|
311 |
+
limit = limits.pop(-1)
|
312 |
+
|
313 |
+
if limits: # f is the argument to a Sum
|
314 |
+
f = self.func(f, *limits)
|
315 |
+
|
316 |
+
_, a, b = limit
|
317 |
+
if x in a.free_symbols or x in b.free_symbols:
|
318 |
+
return None
|
319 |
+
df = Derivative(f, x, evaluate=True)
|
320 |
+
rv = self.func(df, limit)
|
321 |
+
return rv
|
322 |
+
|
323 |
+
def _eval_difference_delta(self, n, step):
|
324 |
+
k, _, upper = self.args[-1]
|
325 |
+
new_upper = upper.subs(n, n + step)
|
326 |
+
|
327 |
+
if len(self.args) == 2:
|
328 |
+
f = self.args[0]
|
329 |
+
else:
|
330 |
+
f = self.func(*self.args[:-1])
|
331 |
+
|
332 |
+
return Sum(f, (k, upper + 1, new_upper)).doit()
|
333 |
+
|
334 |
+
def _eval_simplify(self, **kwargs):
|
335 |
+
|
336 |
+
function = self.function
|
337 |
+
|
338 |
+
if kwargs.get('deep', True):
|
339 |
+
function = function.simplify(**kwargs)
|
340 |
+
|
341 |
+
# split the function into adds
|
342 |
+
terms = Add.make_args(expand(function))
|
343 |
+
s_t = [] # Sum Terms
|
344 |
+
o_t = [] # Other Terms
|
345 |
+
|
346 |
+
for term in terms:
|
347 |
+
if term.has(Sum):
|
348 |
+
# if there is an embedded sum here
|
349 |
+
# it is of the form x * (Sum(whatever))
|
350 |
+
# hence we make a Mul out of it, and simplify all interior sum terms
|
351 |
+
subterms = Mul.make_args(expand(term))
|
352 |
+
out_terms = []
|
353 |
+
for subterm in subterms:
|
354 |
+
# go through each term
|
355 |
+
if isinstance(subterm, Sum):
|
356 |
+
# if it's a sum, simplify it
|
357 |
+
out_terms.append(subterm._eval_simplify(**kwargs))
|
358 |
+
else:
|
359 |
+
# otherwise, add it as is
|
360 |
+
out_terms.append(subterm)
|
361 |
+
|
362 |
+
# turn it back into a Mul
|
363 |
+
s_t.append(Mul(*out_terms))
|
364 |
+
else:
|
365 |
+
o_t.append(term)
|
366 |
+
|
367 |
+
# next try to combine any interior sums for further simplification
|
368 |
+
from sympy.simplify.simplify import factor_sum, sum_combine
|
369 |
+
result = Add(sum_combine(s_t), *o_t)
|
370 |
+
|
371 |
+
return factor_sum(result, limits=self.limits)
|
372 |
+
|
373 |
+
def is_convergent(self):
|
374 |
+
r"""
|
375 |
+
Checks for the convergence of a Sum.
|
376 |
+
|
377 |
+
Explanation
|
378 |
+
===========
|
379 |
+
|
380 |
+
We divide the study of convergence of infinite sums and products in
|
381 |
+
two parts.
|
382 |
+
|
383 |
+
First Part:
|
384 |
+
One part is the question whether all the terms are well defined, i.e.,
|
385 |
+
they are finite in a sum and also non-zero in a product. Zero
|
386 |
+
is the analogy of (minus) infinity in products as
|
387 |
+
:math:`e^{-\infty} = 0`.
|
388 |
+
|
389 |
+
Second Part:
|
390 |
+
The second part is the question of convergence after infinities,
|
391 |
+
and zeros in products, have been omitted assuming that their number
|
392 |
+
is finite. This means that we only consider the tail of the sum or
|
393 |
+
product, starting from some point after which all terms are well
|
394 |
+
defined.
|
395 |
+
|
396 |
+
For example, in a sum of the form:
|
397 |
+
|
398 |
+
.. math::
|
399 |
+
|
400 |
+
\sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b}
|
401 |
+
|
402 |
+
where a and b are numbers. The routine will return true, even if there
|
403 |
+
are infinities in the term sequence (at most two). An analogous
|
404 |
+
product would be:
|
405 |
+
|
406 |
+
.. math::
|
407 |
+
|
408 |
+
\prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}}
|
409 |
+
|
410 |
+
This is how convergence is interpreted. It is concerned with what
|
411 |
+
happens at the limit. Finding the bad terms is another independent
|
412 |
+
matter.
|
413 |
+
|
414 |
+
Note: It is responsibility of user to see that the sum or product
|
415 |
+
is well defined.
|
416 |
+
|
417 |
+
There are various tests employed to check the convergence like
|
418 |
+
divergence test, root test, integral test, alternating series test,
|
419 |
+
comparison tests, Dirichlet tests. It returns true if Sum is convergent
|
420 |
+
and false if divergent and NotImplementedError if it cannot be checked.
|
421 |
+
|
422 |
+
References
|
423 |
+
==========
|
424 |
+
|
425 |
+
.. [1] https://en.wikipedia.org/wiki/Convergence_tests
|
426 |
+
|
427 |
+
Examples
|
428 |
+
========
|
429 |
+
|
430 |
+
>>> from sympy import factorial, S, Sum, Symbol, oo
|
431 |
+
>>> n = Symbol('n', integer=True)
|
432 |
+
>>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
|
433 |
+
True
|
434 |
+
>>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
|
435 |
+
False
|
436 |
+
>>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
|
437 |
+
False
|
438 |
+
>>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
|
439 |
+
True
|
440 |
+
|
441 |
+
See Also
|
442 |
+
========
|
443 |
+
|
444 |
+
Sum.is_absolutely_convergent
|
445 |
+
sympy.concrete.products.Product.is_convergent
|
446 |
+
"""
|
447 |
+
p, q, r = symbols('p q r', cls=Wild)
|
448 |
+
|
449 |
+
sym = self.limits[0][0]
|
450 |
+
lower_limit = self.limits[0][1]
|
451 |
+
upper_limit = self.limits[0][2]
|
452 |
+
sequence_term = self.function.simplify()
|
453 |
+
|
454 |
+
if len(sequence_term.free_symbols) > 1:
|
455 |
+
raise NotImplementedError("convergence checking for more than one symbol "
|
456 |
+
"containing series is not handled")
|
457 |
+
|
458 |
+
if lower_limit.is_finite and upper_limit.is_finite:
|
459 |
+
return S.true
|
460 |
+
|
461 |
+
# transform sym -> -sym and swap the upper_limit = S.Infinity
|
462 |
+
# and lower_limit = - upper_limit
|
463 |
+
if lower_limit is S.NegativeInfinity:
|
464 |
+
if upper_limit is S.Infinity:
|
465 |
+
return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
|
466 |
+
Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
|
467 |
+
from sympy.simplify.simplify import simplify
|
468 |
+
sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
|
469 |
+
lower_limit = -upper_limit
|
470 |
+
upper_limit = S.Infinity
|
471 |
+
|
472 |
+
sym_ = Dummy(sym.name, integer=True, positive=True)
|
473 |
+
sequence_term = sequence_term.xreplace({sym: sym_})
|
474 |
+
sym = sym_
|
475 |
+
|
476 |
+
interval = Interval(lower_limit, upper_limit)
|
477 |
+
|
478 |
+
# Piecewise function handle
|
479 |
+
if sequence_term.is_Piecewise:
|
480 |
+
for func, cond in sequence_term.args:
|
481 |
+
# see if it represents something going to oo
|
482 |
+
if cond == True or cond.as_set().sup is S.Infinity:
|
483 |
+
s = Sum(func, (sym, lower_limit, upper_limit))
|
484 |
+
return s.is_convergent()
|
485 |
+
return S.true
|
486 |
+
|
487 |
+
### -------- Divergence test ----------- ###
|
488 |
+
try:
|
489 |
+
lim_val = limit_seq(sequence_term, sym)
|
490 |
+
if lim_val is not None and lim_val.is_zero is False:
|
491 |
+
return S.false
|
492 |
+
except NotImplementedError:
|
493 |
+
pass
|
494 |
+
|
495 |
+
try:
|
496 |
+
lim_val_abs = limit_seq(abs(sequence_term), sym)
|
497 |
+
if lim_val_abs is not None and lim_val_abs.is_zero is False:
|
498 |
+
return S.false
|
499 |
+
except NotImplementedError:
|
500 |
+
pass
|
501 |
+
|
502 |
+
order = O(sequence_term, (sym, S.Infinity))
|
503 |
+
|
504 |
+
### --------- p-series test (1/n**p) ---------- ###
|
505 |
+
p_series_test = order.expr.match(sym**p)
|
506 |
+
if p_series_test is not None:
|
507 |
+
if p_series_test[p] < -1:
|
508 |
+
return S.true
|
509 |
+
if p_series_test[p] >= -1:
|
510 |
+
return S.false
|
511 |
+
|
512 |
+
### ------------- comparison test ------------- ###
|
513 |
+
# 1/(n**p*log(n)**q*log(log(n))**r) comparison
|
514 |
+
n_log_test = (order.expr.match(1/(sym**p*log(1/sym)**q*log(-log(1/sym))**r)) or
|
515 |
+
order.expr.match(1/(sym**p*(-log(1/sym))**q*log(-log(1/sym))**r)))
|
516 |
+
if n_log_test is not None:
|
517 |
+
if (n_log_test[p] > 1 or
|
518 |
+
(n_log_test[p] == 1 and n_log_test[q] > 1) or
|
519 |
+
(n_log_test[p] == n_log_test[q] == 1 and n_log_test[r] > 1)):
|
520 |
+
return S.true
|
521 |
+
return S.false
|
522 |
+
|
523 |
+
### ------------- Limit comparison test -----------###
|
524 |
+
# (1/n) comparison
|
525 |
+
try:
|
526 |
+
lim_comp = limit_seq(sym*sequence_term, sym)
|
527 |
+
if lim_comp is not None and lim_comp.is_number and lim_comp > 0:
|
528 |
+
return S.false
|
529 |
+
except NotImplementedError:
|
530 |
+
pass
|
531 |
+
|
532 |
+
### ----------- ratio test ---------------- ###
|
533 |
+
next_sequence_term = sequence_term.xreplace({sym: sym + 1})
|
534 |
+
from sympy.simplify.combsimp import combsimp
|
535 |
+
from sympy.simplify.powsimp import powsimp
|
536 |
+
ratio = combsimp(powsimp(next_sequence_term/sequence_term))
|
537 |
+
try:
|
538 |
+
lim_ratio = limit_seq(ratio, sym)
|
539 |
+
if lim_ratio is not None and lim_ratio.is_number:
|
540 |
+
if abs(lim_ratio) > 1:
|
541 |
+
return S.false
|
542 |
+
if abs(lim_ratio) < 1:
|
543 |
+
return S.true
|
544 |
+
except NotImplementedError:
|
545 |
+
lim_ratio = None
|
546 |
+
|
547 |
+
### ---------- Raabe's test -------------- ###
|
548 |
+
if lim_ratio == 1: # ratio test inconclusive
|
549 |
+
test_val = sym*(sequence_term/
|
550 |
+
sequence_term.subs(sym, sym + 1) - 1)
|
551 |
+
test_val = test_val.gammasimp()
|
552 |
+
try:
|
553 |
+
lim_val = limit_seq(test_val, sym)
|
554 |
+
if lim_val is not None and lim_val.is_number:
|
555 |
+
if lim_val > 1:
|
556 |
+
return S.true
|
557 |
+
if lim_val < 1:
|
558 |
+
return S.false
|
559 |
+
except NotImplementedError:
|
560 |
+
pass
|
561 |
+
|
562 |
+
### ----------- root test ---------------- ###
|
563 |
+
# lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity)
|
564 |
+
try:
|
565 |
+
lim_evaluated = limit_seq(abs(sequence_term)**(1/sym), sym)
|
566 |
+
if lim_evaluated is not None and lim_evaluated.is_number:
|
567 |
+
if lim_evaluated < 1:
|
568 |
+
return S.true
|
569 |
+
if lim_evaluated > 1:
|
570 |
+
return S.false
|
571 |
+
except NotImplementedError:
|
572 |
+
pass
|
573 |
+
|
574 |
+
### ------------- alternating series test ----------- ###
|
575 |
+
dict_val = sequence_term.match(S.NegativeOne**(sym + p)*q)
|
576 |
+
if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
|
577 |
+
return S.true
|
578 |
+
|
579 |
+
### ------------- integral test -------------- ###
|
580 |
+
check_interval = None
|
581 |
+
from sympy.solvers.solveset import solveset
|
582 |
+
maxima = solveset(sequence_term.diff(sym), sym, interval)
|
583 |
+
if not maxima:
|
584 |
+
check_interval = interval
|
585 |
+
elif isinstance(maxima, FiniteSet) and maxima.sup.is_number:
|
586 |
+
check_interval = Interval(maxima.sup, interval.sup)
|
587 |
+
if (check_interval is not None and
|
588 |
+
(is_decreasing(sequence_term, check_interval) or
|
589 |
+
is_decreasing(-sequence_term, check_interval))):
|
590 |
+
integral_val = Integral(
|
591 |
+
sequence_term, (sym, lower_limit, upper_limit))
|
592 |
+
try:
|
593 |
+
integral_val_evaluated = integral_val.doit()
|
594 |
+
if integral_val_evaluated.is_number:
|
595 |
+
return S(integral_val_evaluated.is_finite)
|
596 |
+
except NotImplementedError:
|
597 |
+
pass
|
598 |
+
|
599 |
+
### ----- Dirichlet and bounded times convergent tests ----- ###
|
600 |
+
# TODO
|
601 |
+
#
|
602 |
+
# Dirichlet_test
|
603 |
+
# https://en.wikipedia.org/wiki/Dirichlet%27s_test
|
604 |
+
#
|
605 |
+
# Bounded times convergent test
|
606 |
+
# It is based on comparison theorems for series.
|
607 |
+
# In particular, if the general term of a series can
|
608 |
+
# be written as a product of two terms a_n and b_n
|
609 |
+
# and if a_n is bounded and if Sum(b_n) is absolutely
|
610 |
+
# convergent, then the original series Sum(a_n * b_n)
|
611 |
+
# is absolutely convergent and so convergent.
|
612 |
+
#
|
613 |
+
# The following code can grows like 2**n where n is the
|
614 |
+
# number of args in order.expr
|
615 |
+
# Possibly combined with the potentially slow checks
|
616 |
+
# inside the loop, could make this test extremely slow
|
617 |
+
# for larger summation expressions.
|
618 |
+
|
619 |
+
if order.expr.is_Mul:
|
620 |
+
args = order.expr.args
|
621 |
+
argset = set(args)
|
622 |
+
|
623 |
+
### -------------- Dirichlet tests -------------- ###
|
624 |
+
m = Dummy('m', integer=True)
|
625 |
+
def _dirichlet_test(g_n):
|
626 |
+
try:
|
627 |
+
ing_val = limit_seq(Sum(g_n, (sym, interval.inf, m)).doit(), m)
|
628 |
+
if ing_val is not None and ing_val.is_finite:
|
629 |
+
return S.true
|
630 |
+
except NotImplementedError:
|
631 |
+
pass
|
632 |
+
|
633 |
+
### -------- bounded times convergent test ---------###
|
634 |
+
def _bounded_convergent_test(g1_n, g2_n):
|
635 |
+
try:
|
636 |
+
lim_val = limit_seq(g1_n, sym)
|
637 |
+
if lim_val is not None and (lim_val.is_finite or (
|
638 |
+
isinstance(lim_val, AccumulationBounds)
|
639 |
+
and (lim_val.max - lim_val.min).is_finite)):
|
640 |
+
if Sum(g2_n, (sym, lower_limit, upper_limit)).is_absolutely_convergent():
|
641 |
+
return S.true
|
642 |
+
except NotImplementedError:
|
643 |
+
pass
|
644 |
+
|
645 |
+
for n in range(1, len(argset)):
|
646 |
+
for a_tuple in itertools.combinations(args, n):
|
647 |
+
b_set = argset - set(a_tuple)
|
648 |
+
a_n = Mul(*a_tuple)
|
649 |
+
b_n = Mul(*b_set)
|
650 |
+
|
651 |
+
if is_decreasing(a_n, interval):
|
652 |
+
dirich = _dirichlet_test(b_n)
|
653 |
+
if dirich is not None:
|
654 |
+
return dirich
|
655 |
+
|
656 |
+
bc_test = _bounded_convergent_test(a_n, b_n)
|
657 |
+
if bc_test is not None:
|
658 |
+
return bc_test
|
659 |
+
|
660 |
+
_sym = self.limits[0][0]
|
661 |
+
sequence_term = sequence_term.xreplace({sym: _sym})
|
662 |
+
raise NotImplementedError("The algorithm to find the Sum convergence of %s "
|
663 |
+
"is not yet implemented" % (sequence_term))
|
664 |
+
|
665 |
+
def is_absolutely_convergent(self):
|
666 |
+
"""
|
667 |
+
Checks for the absolute convergence of an infinite series.
|
668 |
+
|
669 |
+
Same as checking convergence of absolute value of sequence_term of
|
670 |
+
an infinite series.
|
671 |
+
|
672 |
+
References
|
673 |
+
==========
|
674 |
+
|
675 |
+
.. [1] https://en.wikipedia.org/wiki/Absolute_convergence
|
676 |
+
|
677 |
+
Examples
|
678 |
+
========
|
679 |
+
|
680 |
+
>>> from sympy import Sum, Symbol, oo
|
681 |
+
>>> n = Symbol('n', integer=True)
|
682 |
+
>>> Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent()
|
683 |
+
False
|
684 |
+
>>> Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent()
|
685 |
+
True
|
686 |
+
|
687 |
+
See Also
|
688 |
+
========
|
689 |
+
|
690 |
+
Sum.is_convergent
|
691 |
+
"""
|
692 |
+
return Sum(abs(self.function), self.limits).is_convergent()
|
693 |
+
|
694 |
+
def euler_maclaurin(self, m=0, n=0, eps=0, eval_integral=True):
|
695 |
+
"""
|
696 |
+
Return an Euler-Maclaurin approximation of self, where m is the
|
697 |
+
number of leading terms to sum directly and n is the number of
|
698 |
+
terms in the tail.
|
699 |
+
|
700 |
+
With m = n = 0, this is simply the corresponding integral
|
701 |
+
plus a first-order endpoint correction.
|
702 |
+
|
703 |
+
Returns (s, e) where s is the Euler-Maclaurin approximation
|
704 |
+
and e is the estimated error (taken to be the magnitude of
|
705 |
+
the first omitted term in the tail):
|
706 |
+
|
707 |
+
>>> from sympy.abc import k, a, b
|
708 |
+
>>> from sympy import Sum
|
709 |
+
>>> Sum(1/k, (k, 2, 5)).doit().evalf()
|
710 |
+
1.28333333333333
|
711 |
+
>>> s, e = Sum(1/k, (k, 2, 5)).euler_maclaurin()
|
712 |
+
>>> s
|
713 |
+
-log(2) + 7/20 + log(5)
|
714 |
+
>>> from sympy import sstr
|
715 |
+
>>> print(sstr((s.evalf(), e.evalf()), full_prec=True))
|
716 |
+
(1.26629073187415, 0.0175000000000000)
|
717 |
+
|
718 |
+
The endpoints may be symbolic:
|
719 |
+
|
720 |
+
>>> s, e = Sum(1/k, (k, a, b)).euler_maclaurin()
|
721 |
+
>>> s
|
722 |
+
-log(a) + log(b) + 1/(2*b) + 1/(2*a)
|
723 |
+
>>> e
|
724 |
+
Abs(1/(12*b**2) - 1/(12*a**2))
|
725 |
+
|
726 |
+
If the function is a polynomial of degree at most 2n+1, the
|
727 |
+
Euler-Maclaurin formula becomes exact (and e = 0 is returned):
|
728 |
+
|
729 |
+
>>> Sum(k, (k, 2, b)).euler_maclaurin()
|
730 |
+
(b**2/2 + b/2 - 1, 0)
|
731 |
+
>>> Sum(k, (k, 2, b)).doit()
|
732 |
+
b**2/2 + b/2 - 1
|
733 |
+
|
734 |
+
With a nonzero eps specified, the summation is ended
|
735 |
+
as soon as the remainder term is less than the epsilon.
|
736 |
+
"""
|
737 |
+
m = int(m)
|
738 |
+
n = int(n)
|
739 |
+
f = self.function
|
740 |
+
if len(self.limits) != 1:
|
741 |
+
raise ValueError("More than 1 limit")
|
742 |
+
i, a, b = self.limits[0]
|
743 |
+
if (a > b) == True:
|
744 |
+
if a - b == 1:
|
745 |
+
return S.Zero, S.Zero
|
746 |
+
a, b = b + 1, a - 1
|
747 |
+
f = -f
|
748 |
+
s = S.Zero
|
749 |
+
if m:
|
750 |
+
if b.is_Integer and a.is_Integer:
|
751 |
+
m = min(m, b - a + 1)
|
752 |
+
if not eps or f.is_polynomial(i):
|
753 |
+
s = Add(*[f.subs(i, a + k) for k in range(m)])
|
754 |
+
else:
|
755 |
+
term = f.subs(i, a)
|
756 |
+
if term:
|
757 |
+
test = abs(term.evalf(3)) < eps
|
758 |
+
if test == True:
|
759 |
+
return s, abs(term)
|
760 |
+
elif not (test == False):
|
761 |
+
# a symbolic Relational class, can't go further
|
762 |
+
return term, S.Zero
|
763 |
+
s = term
|
764 |
+
for k in range(1, m):
|
765 |
+
term = f.subs(i, a + k)
|
766 |
+
if abs(term.evalf(3)) < eps and term != 0:
|
767 |
+
return s, abs(term)
|
768 |
+
s += term
|
769 |
+
if b - a + 1 == m:
|
770 |
+
return s, S.Zero
|
771 |
+
a += m
|
772 |
+
x = Dummy('x')
|
773 |
+
I = Integral(f.subs(i, x), (x, a, b))
|
774 |
+
if eval_integral:
|
775 |
+
I = I.doit()
|
776 |
+
s += I
|
777 |
+
|
778 |
+
def fpoint(expr):
|
779 |
+
if b is S.Infinity:
|
780 |
+
return expr.subs(i, a), 0
|
781 |
+
return expr.subs(i, a), expr.subs(i, b)
|
782 |
+
fa, fb = fpoint(f)
|
783 |
+
iterm = (fa + fb)/2
|
784 |
+
g = f.diff(i)
|
785 |
+
for k in range(1, n + 2):
|
786 |
+
ga, gb = fpoint(g)
|
787 |
+
term = bernoulli(2*k)/factorial(2*k)*(gb - ga)
|
788 |
+
if k > n:
|
789 |
+
break
|
790 |
+
if eps and term:
|
791 |
+
term_evalf = term.evalf(3)
|
792 |
+
if term_evalf is S.NaN:
|
793 |
+
return S.NaN, S.NaN
|
794 |
+
if abs(term_evalf) < eps:
|
795 |
+
break
|
796 |
+
s += term
|
797 |
+
g = g.diff(i, 2, simplify=False)
|
798 |
+
return s + iterm, abs(term)
|
799 |
+
|
800 |
+
|
801 |
+
def reverse_order(self, *indices):
|
802 |
+
"""
|
803 |
+
Reverse the order of a limit in a Sum.
|
804 |
+
|
805 |
+
Explanation
|
806 |
+
===========
|
807 |
+
|
808 |
+
``reverse_order(self, *indices)`` reverses some limits in the expression
|
809 |
+
``self`` which can be either a ``Sum`` or a ``Product``. The selectors in
|
810 |
+
the argument ``indices`` specify some indices whose limits get reversed.
|
811 |
+
These selectors are either variable names or numerical indices counted
|
812 |
+
starting from the inner-most limit tuple.
|
813 |
+
|
814 |
+
Examples
|
815 |
+
========
|
816 |
+
|
817 |
+
>>> from sympy import Sum
|
818 |
+
>>> from sympy.abc import x, y, a, b, c, d
|
819 |
+
|
820 |
+
>>> Sum(x, (x, 0, 3)).reverse_order(x)
|
821 |
+
Sum(-x, (x, 4, -1))
|
822 |
+
>>> Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(x, y)
|
823 |
+
Sum(x*y, (x, 6, 0), (y, 7, -1))
|
824 |
+
>>> Sum(x, (x, a, b)).reverse_order(x)
|
825 |
+
Sum(-x, (x, b + 1, a - 1))
|
826 |
+
>>> Sum(x, (x, a, b)).reverse_order(0)
|
827 |
+
Sum(-x, (x, b + 1, a - 1))
|
828 |
+
|
829 |
+
While one should prefer variable names when specifying which limits
|
830 |
+
to reverse, the index counting notation comes in handy in case there
|
831 |
+
are several symbols with the same name.
|
832 |
+
|
833 |
+
>>> S = Sum(x**2, (x, a, b), (x, c, d))
|
834 |
+
>>> S
|
835 |
+
Sum(x**2, (x, a, b), (x, c, d))
|
836 |
+
>>> S0 = S.reverse_order(0)
|
837 |
+
>>> S0
|
838 |
+
Sum(-x**2, (x, b + 1, a - 1), (x, c, d))
|
839 |
+
>>> S1 = S0.reverse_order(1)
|
840 |
+
>>> S1
|
841 |
+
Sum(x**2, (x, b + 1, a - 1), (x, d + 1, c - 1))
|
842 |
+
|
843 |
+
Of course we can mix both notations:
|
844 |
+
|
845 |
+
>>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1)
|
846 |
+
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
|
847 |
+
>>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x)
|
848 |
+
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
|
849 |
+
|
850 |
+
See Also
|
851 |
+
========
|
852 |
+
|
853 |
+
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index, reorder_limit,
|
854 |
+
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder
|
855 |
+
|
856 |
+
References
|
857 |
+
==========
|
858 |
+
|
859 |
+
.. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
|
860 |
+
Volume 28 Issue 2, April 1981, Pages 305-350
|
861 |
+
https://dl.acm.org/doi/10.1145/322248.322255
|
862 |
+
"""
|
863 |
+
l_indices = list(indices)
|
864 |
+
|
865 |
+
for i, indx in enumerate(l_indices):
|
866 |
+
if not isinstance(indx, int):
|
867 |
+
l_indices[i] = self.index(indx)
|
868 |
+
|
869 |
+
e = 1
|
870 |
+
limits = []
|
871 |
+
for i, limit in enumerate(self.limits):
|
872 |
+
l = limit
|
873 |
+
if i in l_indices:
|
874 |
+
e = -e
|
875 |
+
l = (limit[0], limit[2] + 1, limit[1] - 1)
|
876 |
+
limits.append(l)
|
877 |
+
|
878 |
+
return Sum(e * self.function, *limits)
|
879 |
+
|
880 |
+
def _eval_rewrite_as_Product(self, *args, **kwargs):
|
881 |
+
from sympy.concrete.products import Product
|
882 |
+
if self.function.is_extended_real:
|
883 |
+
return log(Product(exp(self.function), *self.limits))
|
884 |
+
|
885 |
+
|
886 |
+
def summation(f, *symbols, **kwargs):
|
887 |
+
r"""
|
888 |
+
Compute the summation of f with respect to symbols.
|
889 |
+
|
890 |
+
Explanation
|
891 |
+
===========
|
892 |
+
|
893 |
+
The notation for symbols is similar to the notation used in Integral.
|
894 |
+
summation(f, (i, a, b)) computes the sum of f with respect to i from a to b,
|
895 |
+
i.e.,
|
896 |
+
|
897 |
+
::
|
898 |
+
|
899 |
+
b
|
900 |
+
____
|
901 |
+
\ `
|
902 |
+
summation(f, (i, a, b)) = ) f
|
903 |
+
/___,
|
904 |
+
i = a
|
905 |
+
|
906 |
+
If it cannot compute the sum, it returns an unevaluated Sum object.
|
907 |
+
Repeated sums can be computed by introducing additional symbols tuples::
|
908 |
+
|
909 |
+
Examples
|
910 |
+
========
|
911 |
+
|
912 |
+
>>> from sympy import summation, oo, symbols, log
|
913 |
+
>>> i, n, m = symbols('i n m', integer=True)
|
914 |
+
|
915 |
+
>>> summation(2*i - 1, (i, 1, n))
|
916 |
+
n**2
|
917 |
+
>>> summation(1/2**i, (i, 0, oo))
|
918 |
+
2
|
919 |
+
>>> summation(1/log(n)**n, (n, 2, oo))
|
920 |
+
Sum(log(n)**(-n), (n, 2, oo))
|
921 |
+
>>> summation(i, (i, 0, n), (n, 0, m))
|
922 |
+
m**3/6 + m**2/2 + m/3
|
923 |
+
|
924 |
+
>>> from sympy.abc import x
|
925 |
+
>>> from sympy import factorial
|
926 |
+
>>> summation(x**n/factorial(n), (n, 0, oo))
|
927 |
+
exp(x)
|
928 |
+
|
929 |
+
See Also
|
930 |
+
========
|
931 |
+
|
932 |
+
Sum
|
933 |
+
Product, sympy.concrete.products.product
|
934 |
+
|
935 |
+
"""
|
936 |
+
return Sum(f, *symbols, **kwargs).doit(deep=False)
|
937 |
+
|
938 |
+
|
939 |
+
def telescopic_direct(L, R, n, limits):
|
940 |
+
"""
|
941 |
+
Returns the direct summation of the terms of a telescopic sum
|
942 |
+
|
943 |
+
Explanation
|
944 |
+
===========
|
945 |
+
|
946 |
+
L is the term with lower index
|
947 |
+
R is the term with higher index
|
948 |
+
n difference between the indexes of L and R
|
949 |
+
|
950 |
+
Examples
|
951 |
+
========
|
952 |
+
|
953 |
+
>>> from sympy.concrete.summations import telescopic_direct
|
954 |
+
>>> from sympy.abc import k, a, b
|
955 |
+
>>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b))
|
956 |
+
-1/(b + 2) - 1/(b + 1) + 1/(a + 1) + 1/a
|
957 |
+
|
958 |
+
"""
|
959 |
+
(i, a, b) = limits
|
960 |
+
return Add(*[L.subs(i, a + m) + R.subs(i, b - m) for m in range(n)])
|
961 |
+
|
962 |
+
|
963 |
+
def telescopic(L, R, limits):
|
964 |
+
'''
|
965 |
+
Tries to perform the summation using the telescopic property.
|
966 |
+
|
967 |
+
Return None if not possible.
|
968 |
+
'''
|
969 |
+
(i, a, b) = limits
|
970 |
+
if L.is_Add or R.is_Add:
|
971 |
+
return None
|
972 |
+
|
973 |
+
# We want to solve(L.subs(i, i + m) + R, m)
|
974 |
+
# First we try a simple match since this does things that
|
975 |
+
# solve doesn't do, e.g. solve(cos(k+m)-cos(k), m) gives
|
976 |
+
# a more complicated solution than m == 0.
|
977 |
+
|
978 |
+
k = Wild("k")
|
979 |
+
sol = (-R).match(L.subs(i, i + k))
|
980 |
+
s = None
|
981 |
+
if sol and k in sol:
|
982 |
+
s = sol[k]
|
983 |
+
if not (s.is_Integer and L.subs(i, i + s) + R == 0):
|
984 |
+
# invalid match or match didn't work
|
985 |
+
s = None
|
986 |
+
|
987 |
+
# But there are things that match doesn't do that solve
|
988 |
+
# can do, e.g. determine that 1/(x + m) = 1/(1 - x) when m = 1
|
989 |
+
|
990 |
+
if s is None:
|
991 |
+
m = Dummy('m')
|
992 |
+
try:
|
993 |
+
from sympy.solvers.solvers import solve
|
994 |
+
sol = solve(L.subs(i, i + m) + R, m) or []
|
995 |
+
except NotImplementedError:
|
996 |
+
return None
|
997 |
+
sol = [si for si in sol if si.is_Integer and
|
998 |
+
(L.subs(i, i + si) + R).expand().is_zero]
|
999 |
+
if len(sol) != 1:
|
1000 |
+
return None
|
1001 |
+
s = sol[0]
|
1002 |
+
|
1003 |
+
if s < 0:
|
1004 |
+
return telescopic_direct(R, L, abs(s), (i, a, b))
|
1005 |
+
elif s > 0:
|
1006 |
+
return telescopic_direct(L, R, s, (i, a, b))
|
1007 |
+
|
1008 |
+
|
1009 |
+
def eval_sum(f, limits):
|
1010 |
+
(i, a, b) = limits
|
1011 |
+
if f.is_zero:
|
1012 |
+
return S.Zero
|
1013 |
+
if i not in f.free_symbols:
|
1014 |
+
return f*(b - a + 1)
|
1015 |
+
if a == b:
|
1016 |
+
return f.subs(i, a)
|
1017 |
+
if isinstance(f, Piecewise):
|
1018 |
+
if not any(i in arg.args[1].free_symbols for arg in f.args):
|
1019 |
+
# Piecewise conditions do not depend on the dummy summation variable,
|
1020 |
+
# therefore we can fold: Sum(Piecewise((e, c), ...), limits)
|
1021 |
+
# --> Piecewise((Sum(e, limits), c), ...)
|
1022 |
+
newargs = []
|
1023 |
+
for arg in f.args:
|
1024 |
+
newexpr = eval_sum(arg.expr, limits)
|
1025 |
+
if newexpr is None:
|
1026 |
+
return None
|
1027 |
+
newargs.append((newexpr, arg.cond))
|
1028 |
+
return f.func(*newargs)
|
1029 |
+
|
1030 |
+
if f.has(KroneckerDelta):
|
1031 |
+
from .delta import deltasummation, _has_simple_delta
|
1032 |
+
f = f.replace(
|
1033 |
+
lambda x: isinstance(x, Sum),
|
1034 |
+
lambda x: x.factor()
|
1035 |
+
)
|
1036 |
+
if _has_simple_delta(f, limits[0]):
|
1037 |
+
return deltasummation(f, limits)
|
1038 |
+
|
1039 |
+
dif = b - a
|
1040 |
+
definite = dif.is_Integer
|
1041 |
+
# Doing it directly may be faster if there are very few terms.
|
1042 |
+
if definite and (dif < 100):
|
1043 |
+
return eval_sum_direct(f, (i, a, b))
|
1044 |
+
if isinstance(f, Piecewise):
|
1045 |
+
return None
|
1046 |
+
# Try to do it symbolically. Even when the number of terms is
|
1047 |
+
# known, this can save time when b-a is big.
|
1048 |
+
value = eval_sum_symbolic(f.expand(), (i, a, b))
|
1049 |
+
if value is not None:
|
1050 |
+
return value
|
1051 |
+
# Do it directly
|
1052 |
+
if definite:
|
1053 |
+
return eval_sum_direct(f, (i, a, b))
|
1054 |
+
|
1055 |
+
|
1056 |
+
def eval_sum_direct(expr, limits):
|
1057 |
+
"""
|
1058 |
+
Evaluate expression directly, but perform some simple checks first
|
1059 |
+
to possibly result in a smaller expression and faster execution.
|
1060 |
+
"""
|
1061 |
+
(i, a, b) = limits
|
1062 |
+
|
1063 |
+
dif = b - a
|
1064 |
+
# Linearity
|
1065 |
+
if expr.is_Mul:
|
1066 |
+
# Try factor out everything not including i
|
1067 |
+
without_i, with_i = expr.as_independent(i)
|
1068 |
+
if without_i != 1:
|
1069 |
+
s = eval_sum_direct(with_i, (i, a, b))
|
1070 |
+
if s:
|
1071 |
+
r = without_i*s
|
1072 |
+
if r is not S.NaN:
|
1073 |
+
return r
|
1074 |
+
else:
|
1075 |
+
# Try term by term
|
1076 |
+
L, R = expr.as_two_terms()
|
1077 |
+
|
1078 |
+
if not L.has(i):
|
1079 |
+
sR = eval_sum_direct(R, (i, a, b))
|
1080 |
+
if sR:
|
1081 |
+
return L*sR
|
1082 |
+
|
1083 |
+
if not R.has(i):
|
1084 |
+
sL = eval_sum_direct(L, (i, a, b))
|
1085 |
+
if sL:
|
1086 |
+
return sL*R
|
1087 |
+
|
1088 |
+
# do this whether its an Add or Mul
|
1089 |
+
# e.g. apart(1/(25*i**2 + 45*i + 14)) and
|
1090 |
+
# apart(1/((5*i + 2)*(5*i + 7))) ->
|
1091 |
+
# -1/(5*(5*i + 7)) + 1/(5*(5*i + 2))
|
1092 |
+
try:
|
1093 |
+
expr = apart(expr, i) # see if it becomes an Add
|
1094 |
+
except PolynomialError:
|
1095 |
+
pass
|
1096 |
+
|
1097 |
+
if expr.is_Add:
|
1098 |
+
# Try factor out everything not including i
|
1099 |
+
without_i, with_i = expr.as_independent(i)
|
1100 |
+
if without_i != 0:
|
1101 |
+
s = eval_sum_direct(with_i, (i, a, b))
|
1102 |
+
if s:
|
1103 |
+
r = without_i*(dif + 1) + s
|
1104 |
+
if r is not S.NaN:
|
1105 |
+
return r
|
1106 |
+
else:
|
1107 |
+
# Try term by term
|
1108 |
+
L, R = expr.as_two_terms()
|
1109 |
+
lsum = eval_sum_direct(L, (i, a, b))
|
1110 |
+
rsum = eval_sum_direct(R, (i, a, b))
|
1111 |
+
|
1112 |
+
if None not in (lsum, rsum):
|
1113 |
+
r = lsum + rsum
|
1114 |
+
if r is not S.NaN:
|
1115 |
+
return r
|
1116 |
+
|
1117 |
+
return Add(*[expr.subs(i, a + j) for j in range(dif + 1)])
|
1118 |
+
|
1119 |
+
|
1120 |
+
def eval_sum_symbolic(f, limits):
|
1121 |
+
f_orig = f
|
1122 |
+
(i, a, b) = limits
|
1123 |
+
if not f.has(i):
|
1124 |
+
return f*(b - a + 1)
|
1125 |
+
|
1126 |
+
# Linearity
|
1127 |
+
if f.is_Mul:
|
1128 |
+
# Try factor out everything not including i
|
1129 |
+
without_i, with_i = f.as_independent(i)
|
1130 |
+
if without_i != 1:
|
1131 |
+
s = eval_sum_symbolic(with_i, (i, a, b))
|
1132 |
+
if s:
|
1133 |
+
r = without_i*s
|
1134 |
+
if r is not S.NaN:
|
1135 |
+
return r
|
1136 |
+
else:
|
1137 |
+
# Try term by term
|
1138 |
+
L, R = f.as_two_terms()
|
1139 |
+
|
1140 |
+
if not L.has(i):
|
1141 |
+
sR = eval_sum_symbolic(R, (i, a, b))
|
1142 |
+
if sR:
|
1143 |
+
return L*sR
|
1144 |
+
|
1145 |
+
if not R.has(i):
|
1146 |
+
sL = eval_sum_symbolic(L, (i, a, b))
|
1147 |
+
if sL:
|
1148 |
+
return sL*R
|
1149 |
+
|
1150 |
+
# do this whether its an Add or Mul
|
1151 |
+
# e.g. apart(1/(25*i**2 + 45*i + 14)) and
|
1152 |
+
# apart(1/((5*i + 2)*(5*i + 7))) ->
|
1153 |
+
# -1/(5*(5*i + 7)) + 1/(5*(5*i + 2))
|
1154 |
+
try:
|
1155 |
+
f = apart(f, i)
|
1156 |
+
except PolynomialError:
|
1157 |
+
pass
|
1158 |
+
|
1159 |
+
if f.is_Add:
|
1160 |
+
L, R = f.as_two_terms()
|
1161 |
+
lrsum = telescopic(L, R, (i, a, b))
|
1162 |
+
|
1163 |
+
if lrsum:
|
1164 |
+
return lrsum
|
1165 |
+
|
1166 |
+
# Try factor out everything not including i
|
1167 |
+
without_i, with_i = f.as_independent(i)
|
1168 |
+
if without_i != 0:
|
1169 |
+
s = eval_sum_symbolic(with_i, (i, a, b))
|
1170 |
+
if s:
|
1171 |
+
r = without_i*(b - a + 1) + s
|
1172 |
+
if r is not S.NaN:
|
1173 |
+
return r
|
1174 |
+
else:
|
1175 |
+
# Try term by term
|
1176 |
+
lsum = eval_sum_symbolic(L, (i, a, b))
|
1177 |
+
rsum = eval_sum_symbolic(R, (i, a, b))
|
1178 |
+
|
1179 |
+
if None not in (lsum, rsum):
|
1180 |
+
r = lsum + rsum
|
1181 |
+
if r is not S.NaN:
|
1182 |
+
return r
|
1183 |
+
|
1184 |
+
|
1185 |
+
# Polynomial terms with Faulhaber's formula
|
1186 |
+
n = Wild('n')
|
1187 |
+
result = f.match(i**n)
|
1188 |
+
|
1189 |
+
if result is not None:
|
1190 |
+
n = result[n]
|
1191 |
+
|
1192 |
+
if n.is_Integer:
|
1193 |
+
if n >= 0:
|
1194 |
+
if (b is S.Infinity and a is not S.NegativeInfinity) or \
|
1195 |
+
(a is S.NegativeInfinity and b is not S.Infinity):
|
1196 |
+
return S.Infinity
|
1197 |
+
return ((bernoulli(n + 1, b + 1) - bernoulli(n + 1, a))/(n + 1)).expand()
|
1198 |
+
elif a.is_Integer and a >= 1:
|
1199 |
+
if n == -1:
|
1200 |
+
return harmonic(b) - harmonic(a - 1)
|
1201 |
+
else:
|
1202 |
+
return harmonic(b, abs(n)) - harmonic(a - 1, abs(n))
|
1203 |
+
|
1204 |
+
if not (a.has(S.Infinity, S.NegativeInfinity) or
|
1205 |
+
b.has(S.Infinity, S.NegativeInfinity)):
|
1206 |
+
# Geometric terms
|
1207 |
+
c1 = Wild('c1', exclude=[i])
|
1208 |
+
c2 = Wild('c2', exclude=[i])
|
1209 |
+
c3 = Wild('c3', exclude=[i])
|
1210 |
+
wexp = Wild('wexp')
|
1211 |
+
|
1212 |
+
# Here we first attempt powsimp on f for easier matching with the
|
1213 |
+
# exponential pattern, and attempt expansion on the exponent for easier
|
1214 |
+
# matching with the linear pattern.
|
1215 |
+
e = f.powsimp().match(c1 ** wexp)
|
1216 |
+
if e is not None:
|
1217 |
+
e_exp = e.pop(wexp).expand().match(c2*i + c3)
|
1218 |
+
if e_exp is not None:
|
1219 |
+
e.update(e_exp)
|
1220 |
+
|
1221 |
+
p = (c1**c3).subs(e)
|
1222 |
+
q = (c1**c2).subs(e)
|
1223 |
+
r = p*(q**a - q**(b + 1))/(1 - q)
|
1224 |
+
l = p*(b - a + 1)
|
1225 |
+
return Piecewise((l, Eq(q, S.One)), (r, True))
|
1226 |
+
|
1227 |
+
r = gosper_sum(f, (i, a, b))
|
1228 |
+
|
1229 |
+
if isinstance(r, (Mul,Add)):
|
1230 |
+
from sympy.simplify.radsimp import denom
|
1231 |
+
from sympy.solvers.solvers import solve
|
1232 |
+
non_limit = r.free_symbols - Tuple(*limits[1:]).free_symbols
|
1233 |
+
den = denom(together(r))
|
1234 |
+
den_sym = non_limit & den.free_symbols
|
1235 |
+
args = []
|
1236 |
+
for v in ordered(den_sym):
|
1237 |
+
try:
|
1238 |
+
s = solve(den, v)
|
1239 |
+
m = Eq(v, s[0]) if s else S.false
|
1240 |
+
if m != False:
|
1241 |
+
args.append((Sum(f_orig.subs(*m.args), limits).doit(), m))
|
1242 |
+
break
|
1243 |
+
except NotImplementedError:
|
1244 |
+
continue
|
1245 |
+
|
1246 |
+
args.append((r, True))
|
1247 |
+
return Piecewise(*args)
|
1248 |
+
|
1249 |
+
if r not in (None, S.NaN):
|
1250 |
+
return r
|
1251 |
+
|
1252 |
+
h = eval_sum_hyper(f_orig, (i, a, b))
|
1253 |
+
if h is not None:
|
1254 |
+
return h
|
1255 |
+
|
1256 |
+
r = eval_sum_residue(f_orig, (i, a, b))
|
1257 |
+
if r is not None:
|
1258 |
+
return r
|
1259 |
+
|
1260 |
+
factored = f_orig.factor()
|
1261 |
+
if factored != f_orig:
|
1262 |
+
return eval_sum_symbolic(factored, (i, a, b))
|
1263 |
+
|
1264 |
+
|
1265 |
+
def _eval_sum_hyper(f, i, a):
|
1266 |
+
""" Returns (res, cond). Sums from a to oo. """
|
1267 |
+
if a != 0:
|
1268 |
+
return _eval_sum_hyper(f.subs(i, i + a), i, 0)
|
1269 |
+
|
1270 |
+
if f.subs(i, 0) == 0:
|
1271 |
+
from sympy.simplify.simplify import simplify
|
1272 |
+
if simplify(f.subs(i, Dummy('i', integer=True, positive=True))) == 0:
|
1273 |
+
return S.Zero, True
|
1274 |
+
return _eval_sum_hyper(f.subs(i, i + 1), i, 0)
|
1275 |
+
|
1276 |
+
from sympy.simplify.simplify import hypersimp
|
1277 |
+
hs = hypersimp(f, i)
|
1278 |
+
if hs is None:
|
1279 |
+
return None
|
1280 |
+
|
1281 |
+
if isinstance(hs, Float):
|
1282 |
+
from sympy.simplify.simplify import nsimplify
|
1283 |
+
hs = nsimplify(hs)
|
1284 |
+
|
1285 |
+
from sympy.simplify.combsimp import combsimp
|
1286 |
+
from sympy.simplify.hyperexpand import hyperexpand
|
1287 |
+
from sympy.simplify.radsimp import fraction
|
1288 |
+
numer, denom = fraction(factor(hs))
|
1289 |
+
top, topl = numer.as_coeff_mul(i)
|
1290 |
+
bot, botl = denom.as_coeff_mul(i)
|
1291 |
+
ab = [top, bot]
|
1292 |
+
factors = [topl, botl]
|
1293 |
+
params = [[], []]
|
1294 |
+
for k in range(2):
|
1295 |
+
for fac in factors[k]:
|
1296 |
+
mul = 1
|
1297 |
+
if fac.is_Pow:
|
1298 |
+
mul = fac.exp
|
1299 |
+
fac = fac.base
|
1300 |
+
if not mul.is_Integer:
|
1301 |
+
return None
|
1302 |
+
p = Poly(fac, i)
|
1303 |
+
if p.degree() != 1:
|
1304 |
+
return None
|
1305 |
+
m, n = p.all_coeffs()
|
1306 |
+
ab[k] *= m**mul
|
1307 |
+
params[k] += [n/m]*mul
|
1308 |
+
|
1309 |
+
# Add "1" to numerator parameters, to account for implicit n! in
|
1310 |
+
# hypergeometric series.
|
1311 |
+
ap = params[0] + [1]
|
1312 |
+
bq = params[1]
|
1313 |
+
x = ab[0]/ab[1]
|
1314 |
+
h = hyper(ap, bq, x)
|
1315 |
+
f = combsimp(f)
|
1316 |
+
return f.subs(i, 0)*hyperexpand(h), h.convergence_statement
|
1317 |
+
|
1318 |
+
|
1319 |
+
def eval_sum_hyper(f, i_a_b):
|
1320 |
+
i, a, b = i_a_b
|
1321 |
+
|
1322 |
+
if f.is_hypergeometric(i) is False:
|
1323 |
+
return
|
1324 |
+
|
1325 |
+
if (b - a).is_Integer:
|
1326 |
+
# We are never going to do better than doing the sum in the obvious way
|
1327 |
+
return None
|
1328 |
+
|
1329 |
+
old_sum = Sum(f, (i, a, b))
|
1330 |
+
|
1331 |
+
if b != S.Infinity:
|
1332 |
+
if a is S.NegativeInfinity:
|
1333 |
+
res = _eval_sum_hyper(f.subs(i, -i), i, -b)
|
1334 |
+
if res is not None:
|
1335 |
+
return Piecewise(res, (old_sum, True))
|
1336 |
+
else:
|
1337 |
+
n_illegal = lambda x: sum(x.count(_) for _ in _illegal)
|
1338 |
+
had = n_illegal(f)
|
1339 |
+
# check that no extra illegals are introduced
|
1340 |
+
res1 = _eval_sum_hyper(f, i, a)
|
1341 |
+
if res1 is None or n_illegal(res1) > had:
|
1342 |
+
return
|
1343 |
+
res2 = _eval_sum_hyper(f, i, b + 1)
|
1344 |
+
if res2 is None or n_illegal(res2) > had:
|
1345 |
+
return
|
1346 |
+
(res1, cond1), (res2, cond2) = res1, res2
|
1347 |
+
cond = And(cond1, cond2)
|
1348 |
+
if cond == False:
|
1349 |
+
return None
|
1350 |
+
return Piecewise((res1 - res2, cond), (old_sum, True))
|
1351 |
+
|
1352 |
+
if a is S.NegativeInfinity:
|
1353 |
+
res1 = _eval_sum_hyper(f.subs(i, -i), i, 1)
|
1354 |
+
res2 = _eval_sum_hyper(f, i, 0)
|
1355 |
+
if res1 is None or res2 is None:
|
1356 |
+
return None
|
1357 |
+
res1, cond1 = res1
|
1358 |
+
res2, cond2 = res2
|
1359 |
+
cond = And(cond1, cond2)
|
1360 |
+
if cond == False or cond.as_set() == S.EmptySet:
|
1361 |
+
return None
|
1362 |
+
return Piecewise((res1 + res2, cond), (old_sum, True))
|
1363 |
+
|
1364 |
+
# Now b == oo, a != -oo
|
1365 |
+
res = _eval_sum_hyper(f, i, a)
|
1366 |
+
if res is not None:
|
1367 |
+
r, c = res
|
1368 |
+
if c == False:
|
1369 |
+
if r.is_number:
|
1370 |
+
f = f.subs(i, Dummy('i', integer=True, positive=True) + a)
|
1371 |
+
if f.is_positive or f.is_zero:
|
1372 |
+
return S.Infinity
|
1373 |
+
elif f.is_negative:
|
1374 |
+
return S.NegativeInfinity
|
1375 |
+
return None
|
1376 |
+
return Piecewise(res, (old_sum, True))
|
1377 |
+
|
1378 |
+
|
1379 |
+
def eval_sum_residue(f, i_a_b):
|
1380 |
+
r"""Compute the infinite summation with residues
|
1381 |
+
|
1382 |
+
Notes
|
1383 |
+
=====
|
1384 |
+
|
1385 |
+
If $f(n), g(n)$ are polynomials with $\deg(g(n)) - \deg(f(n)) \ge 2$,
|
1386 |
+
some infinite summations can be computed by the following residue
|
1387 |
+
evaluations.
|
1388 |
+
|
1389 |
+
.. math::
|
1390 |
+
\sum_{n=-\infty, g(n) \ne 0}^{\infty} \frac{f(n)}{g(n)} =
|
1391 |
+
-\pi \sum_{\alpha|g(\alpha)=0}
|
1392 |
+
\text{Res}(\cot(\pi x) \frac{f(x)}{g(x)}, \alpha)
|
1393 |
+
|
1394 |
+
.. math::
|
1395 |
+
\sum_{n=-\infty, g(n) \ne 0}^{\infty} (-1)^n \frac{f(n)}{g(n)} =
|
1396 |
+
-\pi \sum_{\alpha|g(\alpha)=0}
|
1397 |
+
\text{Res}(\csc(\pi x) \frac{f(x)}{g(x)}, \alpha)
|
1398 |
+
|
1399 |
+
Examples
|
1400 |
+
========
|
1401 |
+
|
1402 |
+
>>> from sympy import Sum, oo, Symbol
|
1403 |
+
>>> x = Symbol('x')
|
1404 |
+
|
1405 |
+
Doubly infinite series of rational functions.
|
1406 |
+
|
1407 |
+
>>> Sum(1 / (x**2 + 1), (x, -oo, oo)).doit()
|
1408 |
+
pi/tanh(pi)
|
1409 |
+
|
1410 |
+
Doubly infinite alternating series of rational functions.
|
1411 |
+
|
1412 |
+
>>> Sum((-1)**x / (x**2 + 1), (x, -oo, oo)).doit()
|
1413 |
+
pi/sinh(pi)
|
1414 |
+
|
1415 |
+
Infinite series of even rational functions.
|
1416 |
+
|
1417 |
+
>>> Sum(1 / (x**2 + 1), (x, 0, oo)).doit()
|
1418 |
+
1/2 + pi/(2*tanh(pi))
|
1419 |
+
|
1420 |
+
Infinite series of alternating even rational functions.
|
1421 |
+
|
1422 |
+
>>> Sum((-1)**x / (x**2 + 1), (x, 0, oo)).doit()
|
1423 |
+
pi/(2*sinh(pi)) + 1/2
|
1424 |
+
|
1425 |
+
This also have heuristics to transform arbitrarily shifted summand or
|
1426 |
+
arbitrarily shifted summation range to the canonical problem the
|
1427 |
+
formula can handle.
|
1428 |
+
|
1429 |
+
>>> Sum(1 / (x**2 + 2*x + 2), (x, -1, oo)).doit()
|
1430 |
+
1/2 + pi/(2*tanh(pi))
|
1431 |
+
>>> Sum(1 / (x**2 + 4*x + 5), (x, -2, oo)).doit()
|
1432 |
+
1/2 + pi/(2*tanh(pi))
|
1433 |
+
>>> Sum(1 / (x**2 + 1), (x, 1, oo)).doit()
|
1434 |
+
-1/2 + pi/(2*tanh(pi))
|
1435 |
+
>>> Sum(1 / (x**2 + 1), (x, 2, oo)).doit()
|
1436 |
+
-1 + pi/(2*tanh(pi))
|
1437 |
+
|
1438 |
+
References
|
1439 |
+
==========
|
1440 |
+
|
1441 |
+
.. [#] http://www.supermath.info/InfiniteSeriesandtheResidueTheorem.pdf
|
1442 |
+
|
1443 |
+
.. [#] Asmar N.H., Grafakos L. (2018) Residue Theory.
|
1444 |
+
In: Complex Analysis with Applications.
|
1445 |
+
Undergraduate Texts in Mathematics. Springer, Cham.
|
1446 |
+
https://doi.org/10.1007/978-3-319-94063-2_5
|
1447 |
+
"""
|
1448 |
+
i, a, b = i_a_b
|
1449 |
+
|
1450 |
+
def is_even_function(numer, denom):
|
1451 |
+
"""Test if the rational function is an even function"""
|
1452 |
+
numer_even = all(i % 2 == 0 for (i,) in numer.monoms())
|
1453 |
+
denom_even = all(i % 2 == 0 for (i,) in denom.monoms())
|
1454 |
+
numer_odd = all(i % 2 == 1 for (i,) in numer.monoms())
|
1455 |
+
denom_odd = all(i % 2 == 1 for (i,) in denom.monoms())
|
1456 |
+
return (numer_even and denom_even) or (numer_odd and denom_odd)
|
1457 |
+
|
1458 |
+
def match_rational(f, i):
|
1459 |
+
numer, denom = f.as_numer_denom()
|
1460 |
+
try:
|
1461 |
+
(numer, denom), opt = parallel_poly_from_expr((numer, denom), i)
|
1462 |
+
except (PolificationFailed, PolynomialError):
|
1463 |
+
return None
|
1464 |
+
return numer, denom
|
1465 |
+
|
1466 |
+
def get_poles(denom):
|
1467 |
+
roots = denom.sqf_part().all_roots()
|
1468 |
+
roots = sift(roots, lambda x: x.is_integer)
|
1469 |
+
if None in roots:
|
1470 |
+
return None
|
1471 |
+
int_roots, nonint_roots = roots[True], roots[False]
|
1472 |
+
return int_roots, nonint_roots
|
1473 |
+
|
1474 |
+
def get_shift(denom):
|
1475 |
+
n = denom.degree(i)
|
1476 |
+
a = denom.coeff_monomial(i**n)
|
1477 |
+
b = denom.coeff_monomial(i**(n-1))
|
1478 |
+
shift = - b / a / n
|
1479 |
+
return shift
|
1480 |
+
|
1481 |
+
#Need a dummy symbol with no assumptions set for get_residue_factor
|
1482 |
+
z = Dummy('z')
|
1483 |
+
|
1484 |
+
def get_residue_factor(numer, denom, alternating):
|
1485 |
+
residue_factor = (numer.as_expr() / denom.as_expr()).subs(i, z)
|
1486 |
+
if not alternating:
|
1487 |
+
residue_factor *= cot(S.Pi * z)
|
1488 |
+
else:
|
1489 |
+
residue_factor *= csc(S.Pi * z)
|
1490 |
+
return residue_factor
|
1491 |
+
|
1492 |
+
# We don't know how to deal with symbolic constants in summand
|
1493 |
+
if f.free_symbols - {i}:
|
1494 |
+
return None
|
1495 |
+
|
1496 |
+
if not (a.is_Integer or a in (S.Infinity, S.NegativeInfinity)):
|
1497 |
+
return None
|
1498 |
+
if not (b.is_Integer or b in (S.Infinity, S.NegativeInfinity)):
|
1499 |
+
return None
|
1500 |
+
|
1501 |
+
# Quick exit heuristic for the sums which doesn't have infinite range
|
1502 |
+
if a != S.NegativeInfinity and b != S.Infinity:
|
1503 |
+
return None
|
1504 |
+
|
1505 |
+
match = match_rational(f, i)
|
1506 |
+
if match:
|
1507 |
+
alternating = False
|
1508 |
+
numer, denom = match
|
1509 |
+
else:
|
1510 |
+
match = match_rational(f / S.NegativeOne**i, i)
|
1511 |
+
if match:
|
1512 |
+
alternating = True
|
1513 |
+
numer, denom = match
|
1514 |
+
else:
|
1515 |
+
return None
|
1516 |
+
|
1517 |
+
if denom.degree(i) - numer.degree(i) < 2:
|
1518 |
+
return None
|
1519 |
+
|
1520 |
+
if (a, b) == (S.NegativeInfinity, S.Infinity):
|
1521 |
+
poles = get_poles(denom)
|
1522 |
+
if poles is None:
|
1523 |
+
return None
|
1524 |
+
int_roots, nonint_roots = poles
|
1525 |
+
|
1526 |
+
if int_roots:
|
1527 |
+
return None
|
1528 |
+
|
1529 |
+
residue_factor = get_residue_factor(numer, denom, alternating)
|
1530 |
+
residues = [residue(residue_factor, z, root) for root in nonint_roots]
|
1531 |
+
return -S.Pi * sum(residues)
|
1532 |
+
|
1533 |
+
if not (a.is_finite and b is S.Infinity):
|
1534 |
+
return None
|
1535 |
+
|
1536 |
+
if not is_even_function(numer, denom):
|
1537 |
+
# Try shifting summation and check if the summand can be made
|
1538 |
+
# and even function from the origin.
|
1539 |
+
# Sum(f(n), (n, a, b)) => Sum(f(n + s), (n, a - s, b - s))
|
1540 |
+
shift = get_shift(denom)
|
1541 |
+
|
1542 |
+
if not shift.is_Integer:
|
1543 |
+
return None
|
1544 |
+
if shift == 0:
|
1545 |
+
return None
|
1546 |
+
|
1547 |
+
numer = numer.shift(shift)
|
1548 |
+
denom = denom.shift(shift)
|
1549 |
+
|
1550 |
+
if not is_even_function(numer, denom):
|
1551 |
+
return None
|
1552 |
+
|
1553 |
+
if alternating:
|
1554 |
+
f = S.NegativeOne**i * (S.NegativeOne**shift * numer.as_expr() / denom.as_expr())
|
1555 |
+
else:
|
1556 |
+
f = numer.as_expr() / denom.as_expr()
|
1557 |
+
return eval_sum_residue(f, (i, a-shift, b-shift))
|
1558 |
+
|
1559 |
+
poles = get_poles(denom)
|
1560 |
+
if poles is None:
|
1561 |
+
return None
|
1562 |
+
int_roots, nonint_roots = poles
|
1563 |
+
|
1564 |
+
if int_roots:
|
1565 |
+
int_roots = [int(root) for root in int_roots]
|
1566 |
+
int_roots_max = max(int_roots)
|
1567 |
+
int_roots_min = min(int_roots)
|
1568 |
+
# Integer valued poles must be next to each other
|
1569 |
+
# and also symmetric from origin (Because the function is even)
|
1570 |
+
if not len(int_roots) == int_roots_max - int_roots_min + 1:
|
1571 |
+
return None
|
1572 |
+
|
1573 |
+
# Check whether the summation indices contain poles
|
1574 |
+
if a <= max(int_roots):
|
1575 |
+
return None
|
1576 |
+
|
1577 |
+
residue_factor = get_residue_factor(numer, denom, alternating)
|
1578 |
+
residues = [residue(residue_factor, z, root) for root in int_roots + nonint_roots]
|
1579 |
+
full_sum = -S.Pi * sum(residues)
|
1580 |
+
|
1581 |
+
if not int_roots:
|
1582 |
+
# Compute Sum(f, (i, 0, oo)) by adding a extraneous evaluation
|
1583 |
+
# at the origin.
|
1584 |
+
half_sum = (full_sum + f.xreplace({i: 0})) / 2
|
1585 |
+
|
1586 |
+
# Add and subtract extraneous evaluations
|
1587 |
+
extraneous_neg = [f.xreplace({i: i0}) for i0 in range(int(a), 0)]
|
1588 |
+
extraneous_pos = [f.xreplace({i: i0}) for i0 in range(0, int(a))]
|
1589 |
+
result = half_sum + sum(extraneous_neg) - sum(extraneous_pos)
|
1590 |
+
|
1591 |
+
return result
|
1592 |
+
|
1593 |
+
# Compute Sum(f, (i, min(poles) + 1, oo))
|
1594 |
+
half_sum = full_sum / 2
|
1595 |
+
|
1596 |
+
# Subtract extraneous evaluations
|
1597 |
+
extraneous = [f.xreplace({i: i0}) for i0 in range(max(int_roots) + 1, int(a))]
|
1598 |
+
result = half_sum - sum(extraneous)
|
1599 |
+
|
1600 |
+
return result
|
1601 |
+
|
1602 |
+
|
1603 |
+
def _eval_matrix_sum(expression):
|
1604 |
+
f = expression.function
|
1605 |
+
for n, limit in enumerate(expression.limits):
|
1606 |
+
i, a, b = limit
|
1607 |
+
dif = b - a
|
1608 |
+
if dif.is_Integer:
|
1609 |
+
if (dif < 0) == True:
|
1610 |
+
a, b = b + 1, a - 1
|
1611 |
+
f = -f
|
1612 |
+
|
1613 |
+
newf = eval_sum_direct(f, (i, a, b))
|
1614 |
+
if newf is not None:
|
1615 |
+
return newf.doit()
|
1616 |
+
|
1617 |
+
|
1618 |
+
def _dummy_with_inherited_properties_concrete(limits):
|
1619 |
+
"""
|
1620 |
+
Return a Dummy symbol that inherits as many assumptions as possible
|
1621 |
+
from the provided symbol and limits.
|
1622 |
+
|
1623 |
+
If the symbol already has all True assumption shared by the limits
|
1624 |
+
then return None.
|
1625 |
+
"""
|
1626 |
+
x, a, b = limits
|
1627 |
+
l = [a, b]
|
1628 |
+
|
1629 |
+
assumptions_to_consider = ['extended_nonnegative', 'nonnegative',
|
1630 |
+
'extended_nonpositive', 'nonpositive',
|
1631 |
+
'extended_positive', 'positive',
|
1632 |
+
'extended_negative', 'negative',
|
1633 |
+
'integer', 'rational', 'finite',
|
1634 |
+
'zero', 'real', 'extended_real']
|
1635 |
+
|
1636 |
+
assumptions_to_keep = {}
|
1637 |
+
assumptions_to_add = {}
|
1638 |
+
for assum in assumptions_to_consider:
|
1639 |
+
assum_true = x._assumptions.get(assum, None)
|
1640 |
+
if assum_true:
|
1641 |
+
assumptions_to_keep[assum] = True
|
1642 |
+
elif all(getattr(i, 'is_' + assum) for i in l):
|
1643 |
+
assumptions_to_add[assum] = True
|
1644 |
+
if assumptions_to_add:
|
1645 |
+
assumptions_to_keep.update(assumptions_to_add)
|
1646 |
+
return Dummy('d', **assumptions_to_keep)
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/complexfield.cpython-310.pyc
ADDED
Binary file (6.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/expressionrawdomain.cpython-310.pyc
ADDED
Binary file (2.34 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/fractionfield.cpython-310.pyc
ADDED
Binary file (7.16 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyfinitefield.cpython-310.pyc
ADDED
Binary file (895 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyintegerring.cpython-310.pyc
ADDED
Binary file (4.32 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/gmpyrationalfield.cpython-310.pyc
ADDED
Binary file (4.48 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/mpelements.cpython-310.pyc
ADDED
Binary file (5.06 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonintegerring.cpython-310.pyc
ADDED
Binary file (4.14 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/pythonrational.cpython-310.pyc
ADDED
Binary file (799 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/domains/__pycache__/simpledomain.cpython-310.pyc
ADDED
Binary file (774 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/test_basis.cpython-310.pyc
ADDED
Binary file (3.58 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/__pycache__/test_primes.cpython-310.pyc
ADDED
Binary file (9.29 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_basis.py
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.abc import x
|
2 |
+
from sympy.core import S
|
3 |
+
from sympy.core.numbers import AlgebraicNumber
|
4 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
5 |
+
from sympy.polys import Poly, cyclotomic_poly
|
6 |
+
from sympy.polys.domains import QQ
|
7 |
+
from sympy.polys.matrices import DomainMatrix, DM
|
8 |
+
from sympy.polys.numberfields.basis import round_two
|
9 |
+
from sympy.testing.pytest import raises
|
10 |
+
|
11 |
+
|
12 |
+
def test_round_two():
|
13 |
+
# Poly must be irreducible, and over ZZ or QQ:
|
14 |
+
raises(ValueError, lambda: round_two(Poly(x ** 2 - 1)))
|
15 |
+
raises(ValueError, lambda: round_two(Poly(x ** 2 + sqrt(2))))
|
16 |
+
|
17 |
+
# Test on many fields:
|
18 |
+
cases = (
|
19 |
+
# A couple of cyclotomic fields:
|
20 |
+
(cyclotomic_poly(5), DomainMatrix.eye(4, QQ), 125),
|
21 |
+
(cyclotomic_poly(7), DomainMatrix.eye(6, QQ), -16807),
|
22 |
+
# A couple of quadratic fields (one 1 mod 4, one 3 mod 4):
|
23 |
+
(x ** 2 - 5, DM([[1, (1, 2)], [0, (1, 2)]], QQ), 5),
|
24 |
+
(x ** 2 - 7, DM([[1, 0], [0, 1]], QQ), 28),
|
25 |
+
# Dedekind's example of a field with 2 as essential disc divisor:
|
26 |
+
(x ** 3 + x ** 2 - 2 * x + 8, DM([[1, 0, 0], [0, 1, 0], [0, (1, 2), (1, 2)]], QQ).transpose(), -503),
|
27 |
+
# A bunch of cubics with various forms for F -- all of these require
|
28 |
+
# second or third enlargements. (Five of them require a third, while the rest require just a second.)
|
29 |
+
# F = 2^2
|
30 |
+
(x**3 + 3 * x**2 - 4 * x + 4, DM([((1, 2), (1, 4), (1, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), -83),
|
31 |
+
# F = 2^2 * 3
|
32 |
+
(x**3 + 3 * x**2 + 3 * x - 3, DM([((1, 2), 0, (1, 2)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -108),
|
33 |
+
# F = 2^3
|
34 |
+
(x**3 + 5 * x**2 - x + 3, DM([((1, 4), 0, (3, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), -31),
|
35 |
+
# F = 2^2 * 5
|
36 |
+
(x**3 + 5 * x**2 - 5 * x - 5, DM([((1, 2), 0, (1, 2)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), 1300),
|
37 |
+
# F = 3^2
|
38 |
+
(x**3 + 3 * x**2 + 5, DM([((1, 3), (1, 3), (1, 3)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -135),
|
39 |
+
# F = 3^3
|
40 |
+
(x**3 + 6 * x**2 + 3 * x - 1, DM([((1, 3), (1, 3), (1, 3)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), 81),
|
41 |
+
# F = 2^2 * 3^2
|
42 |
+
(x**3 + 6 * x**2 + 4, DM([((1, 3), (2, 3), (1, 3)), (0, 1, 0), (0, 0, (1, 2))], QQ).transpose(), -108),
|
43 |
+
# F = 2^3 * 7
|
44 |
+
(x**3 + 7 * x**2 + 7 * x - 7, DM([((1, 4), 0, (3, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), 49),
|
45 |
+
# F = 2^2 * 13
|
46 |
+
(x**3 + 7 * x**2 - x + 5, DM([((1, 2), 0, (1, 2)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -2028),
|
47 |
+
# F = 2^4
|
48 |
+
(x**3 + 7 * x**2 - 5 * x + 5, DM([((1, 4), 0, (3, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), -140),
|
49 |
+
# F = 5^2
|
50 |
+
(x**3 + 4 * x**2 - 3 * x + 7, DM([((1, 5), (4, 5), (4, 5)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -175),
|
51 |
+
# F = 7^2
|
52 |
+
(x**3 + 8 * x**2 + 5 * x - 1, DM([((1, 7), (6, 7), (2, 7)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), 49),
|
53 |
+
# F = 2 * 5 * 7
|
54 |
+
(x**3 + 8 * x**2 - 2 * x + 6, DM([(1, 0, 0), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -14700),
|
55 |
+
# F = 2^2 * 3 * 5
|
56 |
+
(x**3 + 6 * x**2 - 3 * x + 8, DM([(1, 0, 0), (0, (1, 4), (1, 4)), (0, 0, 1)], QQ).transpose(), -675),
|
57 |
+
# F = 2 * 3^2 * 7
|
58 |
+
(x**3 + 9 * x**2 + 6 * x - 8, DM([(1, 0, 0), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), 3969),
|
59 |
+
# F = 2^2 * 3^2 * 7
|
60 |
+
(x**3 + 15 * x**2 - 9 * x + 13, DM([((1, 6), (1, 3), (1, 6)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -5292),
|
61 |
+
# Polynomial need not be monic
|
62 |
+
(5*x**3 + 5*x**2 - 10 * x + 40, DM([[1, 0, 0], [0, 1, 0], [0, (1, 2), (1, 2)]], QQ).transpose(), -503),
|
63 |
+
# Polynomial can have non-integer rational coeffs
|
64 |
+
(QQ(5, 3)*x**3 + QQ(5, 3)*x**2 - QQ(10, 3)*x + QQ(40, 3), DM([[1, 0, 0], [0, 1, 0], [0, (1, 2), (1, 2)]], QQ).transpose(), -503),
|
65 |
+
)
|
66 |
+
for f, B_exp, d_exp in cases:
|
67 |
+
K = QQ.alg_field_from_poly(f)
|
68 |
+
B = K.maximal_order().QQ_matrix
|
69 |
+
d = K.discriminant()
|
70 |
+
assert d == d_exp
|
71 |
+
# The computed basis need not equal the expected one, but their quotient
|
72 |
+
# must be unimodular:
|
73 |
+
assert (B.inv()*B_exp).det()**2 == 1
|
74 |
+
|
75 |
+
|
76 |
+
def test_AlgebraicField_integral_basis():
|
77 |
+
alpha = AlgebraicNumber(sqrt(5), alias='alpha')
|
78 |
+
k = QQ.algebraic_field(alpha)
|
79 |
+
B0 = k.integral_basis()
|
80 |
+
B1 = k.integral_basis(fmt='sympy')
|
81 |
+
B2 = k.integral_basis(fmt='alg')
|
82 |
+
assert B0 == [k([1]), k([S.Half, S.Half])]
|
83 |
+
assert B1 == [1, S.Half + alpha/2]
|
84 |
+
assert B2 == [k.ext.field_element([1]),
|
85 |
+
k.ext.field_element([S.Half, S.Half])]
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_galoisgroups.py
ADDED
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tests for computing Galois groups. """
|
2 |
+
|
3 |
+
from sympy.abc import x
|
4 |
+
from sympy.combinatorics.galois import (
|
5 |
+
S1TransitiveSubgroups, S2TransitiveSubgroups, S3TransitiveSubgroups,
|
6 |
+
S4TransitiveSubgroups, S5TransitiveSubgroups, S6TransitiveSubgroups,
|
7 |
+
)
|
8 |
+
from sympy.polys.domains.rationalfield import QQ
|
9 |
+
from sympy.polys.numberfields.galoisgroups import (
|
10 |
+
tschirnhausen_transformation,
|
11 |
+
galois_group,
|
12 |
+
_galois_group_degree_4_root_approx,
|
13 |
+
_galois_group_degree_5_hybrid,
|
14 |
+
)
|
15 |
+
from sympy.polys.numberfields.subfield import field_isomorphism
|
16 |
+
from sympy.polys.polytools import Poly
|
17 |
+
from sympy.testing.pytest import raises
|
18 |
+
|
19 |
+
|
20 |
+
def test_tschirnhausen_transformation():
|
21 |
+
for T in [
|
22 |
+
Poly(x**2 - 2),
|
23 |
+
Poly(x**2 + x + 1),
|
24 |
+
Poly(x**4 + 1),
|
25 |
+
Poly(x**4 - x**3 + x**2 - x + 1),
|
26 |
+
]:
|
27 |
+
_, U = tschirnhausen_transformation(T)
|
28 |
+
assert U.degree() == T.degree()
|
29 |
+
assert U.is_monic
|
30 |
+
assert U.is_irreducible
|
31 |
+
K = QQ.alg_field_from_poly(T)
|
32 |
+
L = QQ.alg_field_from_poly(U)
|
33 |
+
assert field_isomorphism(K.ext, L.ext) is not None
|
34 |
+
|
35 |
+
|
36 |
+
# Test polys are from:
|
37 |
+
# Cohen, H. *A Course in Computational Algebraic Number Theory*.
|
38 |
+
test_polys_by_deg = {
|
39 |
+
# Degree 1
|
40 |
+
1: [
|
41 |
+
(x, S1TransitiveSubgroups.S1, True)
|
42 |
+
],
|
43 |
+
# Degree 2
|
44 |
+
2: [
|
45 |
+
(x**2 + x + 1, S2TransitiveSubgroups.S2, False)
|
46 |
+
],
|
47 |
+
# Degree 3
|
48 |
+
3: [
|
49 |
+
(x**3 + x**2 - 2*x - 1, S3TransitiveSubgroups.A3, True),
|
50 |
+
(x**3 + 2, S3TransitiveSubgroups.S3, False),
|
51 |
+
],
|
52 |
+
# Degree 4
|
53 |
+
4: [
|
54 |
+
(x**4 + x**3 + x**2 + x + 1, S4TransitiveSubgroups.C4, False),
|
55 |
+
(x**4 + 1, S4TransitiveSubgroups.V, True),
|
56 |
+
(x**4 - 2, S4TransitiveSubgroups.D4, False),
|
57 |
+
(x**4 + 8*x + 12, S4TransitiveSubgroups.A4, True),
|
58 |
+
(x**4 + x + 1, S4TransitiveSubgroups.S4, False),
|
59 |
+
],
|
60 |
+
# Degree 5
|
61 |
+
5: [
|
62 |
+
(x**5 + x**4 - 4*x**3 - 3*x**2 + 3*x + 1, S5TransitiveSubgroups.C5, True),
|
63 |
+
(x**5 - 5*x + 12, S5TransitiveSubgroups.D5, True),
|
64 |
+
(x**5 + 2, S5TransitiveSubgroups.M20, False),
|
65 |
+
(x**5 + 20*x + 16, S5TransitiveSubgroups.A5, True),
|
66 |
+
(x**5 - x + 1, S5TransitiveSubgroups.S5, False),
|
67 |
+
],
|
68 |
+
# Degree 6
|
69 |
+
6: [
|
70 |
+
(x**6 + x**5 + x**4 + x**3 + x**2 + x + 1, S6TransitiveSubgroups.C6, False),
|
71 |
+
(x**6 + 108, S6TransitiveSubgroups.S3, False),
|
72 |
+
(x**6 + 2, S6TransitiveSubgroups.D6, False),
|
73 |
+
(x**6 - 3*x**2 - 1, S6TransitiveSubgroups.A4, True),
|
74 |
+
(x**6 + 3*x**3 + 3, S6TransitiveSubgroups.G18, False),
|
75 |
+
(x**6 - 3*x**2 + 1, S6TransitiveSubgroups.A4xC2, False),
|
76 |
+
(x**6 - 4*x**2 - 1, S6TransitiveSubgroups.S4p, True),
|
77 |
+
(x**6 - 3*x**5 + 6*x**4 - 7*x**3 + 2*x**2 + x - 4, S6TransitiveSubgroups.S4m, False),
|
78 |
+
(x**6 + 2*x**3 - 2, S6TransitiveSubgroups.G36m, False),
|
79 |
+
(x**6 + 2*x**2 + 2, S6TransitiveSubgroups.S4xC2, False),
|
80 |
+
(x**6 + 10*x**5 + 55*x**4 + 140*x**3 + 175*x**2 + 170*x + 25, S6TransitiveSubgroups.PSL2F5, True),
|
81 |
+
(x**6 + 10*x**5 + 55*x**4 + 140*x**3 + 175*x**2 - 3019*x + 25, S6TransitiveSubgroups.PGL2F5, False),
|
82 |
+
(x**6 + 6*x**4 + 2*x**3 + 9*x**2 + 6*x - 4, S6TransitiveSubgroups.G36p, True),
|
83 |
+
(x**6 + 2*x**4 + 2*x**3 + x**2 + 2*x + 2, S6TransitiveSubgroups.G72, False),
|
84 |
+
(x**6 + 24*x - 20, S6TransitiveSubgroups.A6, True),
|
85 |
+
(x**6 + x + 1, S6TransitiveSubgroups.S6, False),
|
86 |
+
],
|
87 |
+
}
|
88 |
+
|
89 |
+
|
90 |
+
def test_galois_group():
|
91 |
+
"""
|
92 |
+
Try all the test polys.
|
93 |
+
"""
|
94 |
+
for deg in range(1, 7):
|
95 |
+
polys = test_polys_by_deg[deg]
|
96 |
+
for T, G, alt in polys:
|
97 |
+
assert galois_group(T, by_name=True) == (G, alt)
|
98 |
+
|
99 |
+
|
100 |
+
def test_galois_group_degree_out_of_bounds():
|
101 |
+
raises(ValueError, lambda: galois_group(Poly(0, x)))
|
102 |
+
raises(ValueError, lambda: galois_group(Poly(1, x)))
|
103 |
+
raises(ValueError, lambda: galois_group(Poly(x ** 7 + 1)))
|
104 |
+
|
105 |
+
|
106 |
+
def test_galois_group_not_by_name():
|
107 |
+
"""
|
108 |
+
Check at least one polynomial of each supported degree, to see that
|
109 |
+
conversion from name to group works.
|
110 |
+
"""
|
111 |
+
for deg in range(1, 7):
|
112 |
+
T, G_name, _ = test_polys_by_deg[deg][0]
|
113 |
+
G, _ = galois_group(T)
|
114 |
+
assert G == G_name.get_perm_group()
|
115 |
+
|
116 |
+
|
117 |
+
def test_galois_group_not_monic_over_ZZ():
|
118 |
+
"""
|
119 |
+
Check that we can work with polys that are not monic over ZZ.
|
120 |
+
"""
|
121 |
+
for deg in range(1, 7):
|
122 |
+
T, G, alt = test_polys_by_deg[deg][0]
|
123 |
+
assert galois_group(T/2, by_name=True) == (G, alt)
|
124 |
+
|
125 |
+
|
126 |
+
def test__galois_group_degree_4_root_approx():
|
127 |
+
for T, G, alt in test_polys_by_deg[4]:
|
128 |
+
assert _galois_group_degree_4_root_approx(Poly(T)) == (G, alt)
|
129 |
+
|
130 |
+
|
131 |
+
def test__galois_group_degree_5_hybrid():
|
132 |
+
for T, G, alt in test_polys_by_deg[5]:
|
133 |
+
assert _galois_group_degree_5_hybrid(Poly(T)) == (G, alt)
|
134 |
+
|
135 |
+
|
136 |
+
def test_AlgebraicField_galois_group():
|
137 |
+
k = QQ.alg_field_from_poly(Poly(x**4 + 1))
|
138 |
+
G, _ = k.galois_group(by_name=True)
|
139 |
+
assert G == S4TransitiveSubgroups.V
|
140 |
+
|
141 |
+
k = QQ.alg_field_from_poly(Poly(x**4 - 2))
|
142 |
+
G, _ = k.galois_group(by_name=True)
|
143 |
+
assert G == S4TransitiveSubgroups.D4
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_minpoly.py
ADDED
@@ -0,0 +1,474 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tests for minimal polynomials. """
|
2 |
+
|
3 |
+
from sympy.core.function import expand
|
4 |
+
from sympy.core import (GoldenRatio, TribonacciConstant)
|
5 |
+
from sympy.core.numbers import (AlgebraicNumber, I, Rational, oo, pi)
|
6 |
+
from sympy.core.power import Pow
|
7 |
+
from sympy.core.singleton import S
|
8 |
+
from sympy.functions.elementary.exponential import exp
|
9 |
+
from sympy.functions.elementary.miscellaneous import (cbrt, sqrt)
|
10 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
|
11 |
+
from sympy.polys.polytools import Poly
|
12 |
+
from sympy.polys.rootoftools import CRootOf
|
13 |
+
from sympy.solvers.solveset import nonlinsolve
|
14 |
+
from sympy.geometry import Circle, intersection
|
15 |
+
from sympy.testing.pytest import raises, slow
|
16 |
+
from sympy.sets.sets import FiniteSet
|
17 |
+
from sympy.geometry.point import Point2D
|
18 |
+
from sympy.polys.numberfields.minpoly import (
|
19 |
+
minimal_polynomial,
|
20 |
+
_choose_factor,
|
21 |
+
_minpoly_op_algebraic_element,
|
22 |
+
_separate_sq,
|
23 |
+
_minpoly_groebner,
|
24 |
+
)
|
25 |
+
from sympy.polys.partfrac import apart
|
26 |
+
from sympy.polys.polyerrors import (
|
27 |
+
NotAlgebraic,
|
28 |
+
GeneratorsError,
|
29 |
+
)
|
30 |
+
|
31 |
+
from sympy.polys.domains import QQ
|
32 |
+
from sympy.polys.rootoftools import rootof
|
33 |
+
from sympy.polys.polytools import degree
|
34 |
+
|
35 |
+
from sympy.abc import x, y, z
|
36 |
+
|
37 |
+
Q = Rational
|
38 |
+
|
39 |
+
|
40 |
+
def test_minimal_polynomial():
|
41 |
+
assert minimal_polynomial(-7, x) == x + 7
|
42 |
+
assert minimal_polynomial(-1, x) == x + 1
|
43 |
+
assert minimal_polynomial( 0, x) == x
|
44 |
+
assert minimal_polynomial( 1, x) == x - 1
|
45 |
+
assert minimal_polynomial( 7, x) == x - 7
|
46 |
+
|
47 |
+
assert minimal_polynomial(sqrt(2), x) == x**2 - 2
|
48 |
+
assert minimal_polynomial(sqrt(5), x) == x**2 - 5
|
49 |
+
assert minimal_polynomial(sqrt(6), x) == x**2 - 6
|
50 |
+
|
51 |
+
assert minimal_polynomial(2*sqrt(2), x) == x**2 - 8
|
52 |
+
assert minimal_polynomial(3*sqrt(5), x) == x**2 - 45
|
53 |
+
assert minimal_polynomial(4*sqrt(6), x) == x**2 - 96
|
54 |
+
|
55 |
+
assert minimal_polynomial(2*sqrt(2) + 3, x) == x**2 - 6*x + 1
|
56 |
+
assert minimal_polynomial(3*sqrt(5) + 6, x) == x**2 - 12*x - 9
|
57 |
+
assert minimal_polynomial(4*sqrt(6) + 7, x) == x**2 - 14*x - 47
|
58 |
+
|
59 |
+
assert minimal_polynomial(2*sqrt(2) - 3, x) == x**2 + 6*x + 1
|
60 |
+
assert minimal_polynomial(3*sqrt(5) - 6, x) == x**2 + 12*x - 9
|
61 |
+
assert minimal_polynomial(4*sqrt(6) - 7, x) == x**2 + 14*x - 47
|
62 |
+
|
63 |
+
assert minimal_polynomial(sqrt(1 + sqrt(6)), x) == x**4 - 2*x**2 - 5
|
64 |
+
assert minimal_polynomial(sqrt(I + sqrt(6)), x) == x**8 - 10*x**4 + 49
|
65 |
+
|
66 |
+
assert minimal_polynomial(2*I + sqrt(2 + I), x) == x**4 + 4*x**2 + 8*x + 37
|
67 |
+
|
68 |
+
assert minimal_polynomial(sqrt(2) + sqrt(3), x) == x**4 - 10*x**2 + 1
|
69 |
+
assert minimal_polynomial(
|
70 |
+
sqrt(2) + sqrt(3) + sqrt(6), x) == x**4 - 22*x**2 - 48*x - 23
|
71 |
+
|
72 |
+
a = 1 - 9*sqrt(2) + 7*sqrt(3)
|
73 |
+
|
74 |
+
assert minimal_polynomial(
|
75 |
+
1/a, x) == 392*x**4 - 1232*x**3 + 612*x**2 + 4*x - 1
|
76 |
+
assert minimal_polynomial(
|
77 |
+
1/sqrt(a), x) == 392*x**8 - 1232*x**6 + 612*x**4 + 4*x**2 - 1
|
78 |
+
|
79 |
+
raises(NotAlgebraic, lambda: minimal_polynomial(oo, x))
|
80 |
+
raises(NotAlgebraic, lambda: minimal_polynomial(2**y, x))
|
81 |
+
raises(NotAlgebraic, lambda: minimal_polynomial(sin(1), x))
|
82 |
+
|
83 |
+
assert minimal_polynomial(sqrt(2)).dummy_eq(x**2 - 2)
|
84 |
+
assert minimal_polynomial(sqrt(2), x) == x**2 - 2
|
85 |
+
|
86 |
+
assert minimal_polynomial(sqrt(2), polys=True) == Poly(x**2 - 2)
|
87 |
+
assert minimal_polynomial(sqrt(2), x, polys=True) == Poly(x**2 - 2, domain='QQ')
|
88 |
+
assert minimal_polynomial(sqrt(2), x, polys=True, compose=False) == Poly(x**2 - 2, domain='QQ')
|
89 |
+
|
90 |
+
a = AlgebraicNumber(sqrt(2))
|
91 |
+
b = AlgebraicNumber(sqrt(3))
|
92 |
+
|
93 |
+
assert minimal_polynomial(a, x) == x**2 - 2
|
94 |
+
assert minimal_polynomial(b, x) == x**2 - 3
|
95 |
+
|
96 |
+
assert minimal_polynomial(a, x, polys=True) == Poly(x**2 - 2, domain='QQ')
|
97 |
+
assert minimal_polynomial(b, x, polys=True) == Poly(x**2 - 3, domain='QQ')
|
98 |
+
|
99 |
+
assert minimal_polynomial(sqrt(a/2 + 17), x) == 2*x**4 - 68*x**2 + 577
|
100 |
+
assert minimal_polynomial(sqrt(b/2 + 17), x) == 4*x**4 - 136*x**2 + 1153
|
101 |
+
|
102 |
+
a, b = sqrt(2)/3 + 7, AlgebraicNumber(sqrt(2)/3 + 7)
|
103 |
+
|
104 |
+
f = 81*x**8 - 2268*x**6 - 4536*x**5 + 22644*x**4 + 63216*x**3 - \
|
105 |
+
31608*x**2 - 189648*x + 141358
|
106 |
+
|
107 |
+
assert minimal_polynomial(sqrt(a) + sqrt(sqrt(a)), x) == f
|
108 |
+
assert minimal_polynomial(sqrt(b) + sqrt(sqrt(b)), x) == f
|
109 |
+
|
110 |
+
assert minimal_polynomial(
|
111 |
+
a**Q(3, 2), x) == 729*x**4 - 506898*x**2 + 84604519
|
112 |
+
|
113 |
+
# issue 5994
|
114 |
+
eq = S('''
|
115 |
+
-1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 +
|
116 |
+
sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 +
|
117 |
+
sqrt(15)*I/28800000)**(1/3)))''')
|
118 |
+
assert minimal_polynomial(eq, x) == 8000*x**2 - 1
|
119 |
+
|
120 |
+
ex = (sqrt(5)*sqrt(I)/(5*sqrt(1 + 125*I))
|
121 |
+
+ 25*sqrt(5)/(I**Q(5,2)*(1 + 125*I)**Q(3,2))
|
122 |
+
+ 3125*sqrt(5)/(I**Q(11,2)*(1 + 125*I)**Q(3,2))
|
123 |
+
+ 5*I*sqrt(1 - I/125))
|
124 |
+
mp = minimal_polynomial(ex, x)
|
125 |
+
assert mp == 25*x**4 + 5000*x**2 + 250016
|
126 |
+
|
127 |
+
ex = 1 + sqrt(2) + sqrt(3)
|
128 |
+
mp = minimal_polynomial(ex, x)
|
129 |
+
assert mp == x**4 - 4*x**3 - 4*x**2 + 16*x - 8
|
130 |
+
|
131 |
+
ex = 1/(1 + sqrt(2) + sqrt(3))
|
132 |
+
mp = minimal_polynomial(ex, x)
|
133 |
+
assert mp == 8*x**4 - 16*x**3 + 4*x**2 + 4*x - 1
|
134 |
+
|
135 |
+
p = (expand((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3))**Rational(1, 3)
|
136 |
+
mp = minimal_polynomial(p, x)
|
137 |
+
assert mp == x**8 - 8*x**7 - 56*x**6 + 448*x**5 + 480*x**4 - 5056*x**3 + 1984*x**2 + 7424*x - 3008
|
138 |
+
p = expand((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3)
|
139 |
+
mp = minimal_polynomial(p, x)
|
140 |
+
assert mp == x**8 - 512*x**7 - 118208*x**6 + 31131136*x**5 + 647362560*x**4 - 56026611712*x**3 + 116994310144*x**2 + 404854931456*x - 27216576512
|
141 |
+
|
142 |
+
assert minimal_polynomial(S("-sqrt(5)/2 - 1/2 + (-sqrt(5)/2 - 1/2)**2"), x) == x - 1
|
143 |
+
a = 1 + sqrt(2)
|
144 |
+
assert minimal_polynomial((a*sqrt(2) + a)**3, x) == x**2 - 198*x + 1
|
145 |
+
|
146 |
+
p = 1/(1 + sqrt(2) + sqrt(3))
|
147 |
+
assert minimal_polynomial(p, x, compose=False) == 8*x**4 - 16*x**3 + 4*x**2 + 4*x - 1
|
148 |
+
|
149 |
+
p = 2/(1 + sqrt(2) + sqrt(3))
|
150 |
+
assert minimal_polynomial(p, x, compose=False) == x**4 - 4*x**3 + 2*x**2 + 4*x - 2
|
151 |
+
|
152 |
+
assert minimal_polynomial(1 + sqrt(2)*I, x, compose=False) == x**2 - 2*x + 3
|
153 |
+
assert minimal_polynomial(1/(1 + sqrt(2)) + 1, x, compose=False) == x**2 - 2
|
154 |
+
assert minimal_polynomial(sqrt(2)*I + I*(1 + sqrt(2)), x,
|
155 |
+
compose=False) == x**4 + 18*x**2 + 49
|
156 |
+
|
157 |
+
# minimal polynomial of I
|
158 |
+
assert minimal_polynomial(I, x, domain=QQ.algebraic_field(I)) == x - I
|
159 |
+
K = QQ.algebraic_field(I*(sqrt(2) + 1))
|
160 |
+
assert minimal_polynomial(I, x, domain=K) == x - I
|
161 |
+
assert minimal_polynomial(I, x, domain=QQ) == x**2 + 1
|
162 |
+
assert minimal_polynomial(I, x, domain='QQ(y)') == x**2 + 1
|
163 |
+
|
164 |
+
#issue 11553
|
165 |
+
assert minimal_polynomial(GoldenRatio, x) == x**2 - x - 1
|
166 |
+
assert minimal_polynomial(TribonacciConstant + 3, x) == x**3 - 10*x**2 + 32*x - 34
|
167 |
+
assert minimal_polynomial(GoldenRatio, x, domain=QQ.algebraic_field(sqrt(5))) == \
|
168 |
+
2*x - sqrt(5) - 1
|
169 |
+
assert minimal_polynomial(TribonacciConstant, x, domain=QQ.algebraic_field(cbrt(19 - 3*sqrt(33)))) == \
|
170 |
+
48*x - 19*(19 - 3*sqrt(33))**Rational(2, 3) - 3*sqrt(33)*(19 - 3*sqrt(33))**Rational(2, 3) \
|
171 |
+
- 16*(19 - 3*sqrt(33))**Rational(1, 3) - 16
|
172 |
+
|
173 |
+
# AlgebraicNumber with an alias.
|
174 |
+
# Wester H24
|
175 |
+
phi = AlgebraicNumber(S.GoldenRatio.expand(func=True), alias='phi')
|
176 |
+
assert minimal_polynomial(phi, x) == x**2 - x - 1
|
177 |
+
|
178 |
+
|
179 |
+
def test_minimal_polynomial_issue_19732():
|
180 |
+
# https://github.com/sympy/sympy/issues/19732
|
181 |
+
expr = (-280898097948878450887044002323982963174671632174995451265117559518123750720061943079105185551006003416773064305074191140286225850817291393988597615/(-488144716373031204149459129212782509078221364279079444636386844223983756114492222145074506571622290776245390771587888364089507840000000*sqrt(238368341569)*sqrt(S(11918417078450)/63568729
|
182 |
+
- 24411360*sqrt(238368341569)/63568729) +
|
183 |
+
238326799225996604451373809274348704114327860564921529846705817404208077866956345381951726531296652901169111729944612727047670549086208000000*sqrt(S(11918417078450)/63568729
|
184 |
+
- 24411360*sqrt(238368341569)/63568729)) -
|
185 |
+
180561807339168676696180573852937120123827201075968945871075967679148461189459480842956689723484024031016208588658753107/(-59358007109636562851035004992802812513575019937126272896569856090962677491318275291141463850327474176000000*sqrt(238368341569)*sqrt(S(11918417078450)/63568729
|
186 |
+
- 24411360*sqrt(238368341569)/63568729) +
|
187 |
+
28980348180319251787320809875930301310576055074938369007463004788921613896002936637780993064387310446267596800000*sqrt(S(11918417078450)/63568729
|
188 |
+
- 24411360*sqrt(238368341569)/63568729)))
|
189 |
+
poly = (2151288870990266634727173620565483054187142169311153766675688628985237817262915166497766867289157986631135400926544697981091151416655364879773546003475813114962656742744975460025956167152918469472166170500512008351638710934022160294849059721218824490226159355197136265032810944357335461128949781377875451881300105989490353140886315677977149440000000000000000000000*x**4
|
190 |
+
- 5773274155644072033773937864114266313663195672820501581692669271302387257492905909558846459600429795784309388968498783843631580008547382703258503404023153694528041873101120067477617592651525155101107144042679962433039557235772239171616433004024998230222455940044709064078962397144550855715640331680262171410099614469231080995436488414164502751395405398078353242072696360734131090111239998110773292915337556205692674790561090109440000000000000*x**2
|
191 |
+
+ 211295968822207088328287206509522887719741955693091053353263782924470627623790749534705683380138972642560898936171035770539616881000369889020398551821767092685775598633794696371561234818461806577723412581353857653829324364446419444210520602157621008010129702779407422072249192199762604318993590841636967747488049176548615614290254356975376588506729604345612047361483789518445332415765213187893207704958013682516462853001964919444736320672860140355089)
|
192 |
+
assert minimal_polynomial(expr, x) == poly
|
193 |
+
|
194 |
+
|
195 |
+
def test_minimal_polynomial_hi_prec():
|
196 |
+
p = 1/sqrt(1 - 9*sqrt(2) + 7*sqrt(3) + Rational(1, 10)**30)
|
197 |
+
mp = minimal_polynomial(p, x)
|
198 |
+
# checked with Wolfram Alpha
|
199 |
+
assert mp.coeff(x**6) == -1232000000000000000000000000001223999999999999999999999999999987999999999999999999999999999996000000000000000000000000000000
|
200 |
+
|
201 |
+
|
202 |
+
def test_minimal_polynomial_sq():
|
203 |
+
from sympy.core.add import Add
|
204 |
+
from sympy.core.function import expand_multinomial
|
205 |
+
p = expand_multinomial((1 + 5*sqrt(2) + 2*sqrt(3))**3)
|
206 |
+
mp = minimal_polynomial(p**Rational(1, 3), x)
|
207 |
+
assert mp == x**4 - 4*x**3 - 118*x**2 + 244*x + 1321
|
208 |
+
p = expand_multinomial((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3)
|
209 |
+
mp = minimal_polynomial(p**Rational(1, 3), x)
|
210 |
+
assert mp == x**8 - 8*x**7 - 56*x**6 + 448*x**5 + 480*x**4 - 5056*x**3 + 1984*x**2 + 7424*x - 3008
|
211 |
+
p = Add(*[sqrt(i) for i in range(1, 12)])
|
212 |
+
mp = minimal_polynomial(p, x)
|
213 |
+
assert mp.subs({x: 0}) == -71965773323122507776
|
214 |
+
|
215 |
+
|
216 |
+
def test_minpoly_compose():
|
217 |
+
# issue 6868
|
218 |
+
eq = S('''
|
219 |
+
-1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 +
|
220 |
+
sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 +
|
221 |
+
sqrt(15)*I/28800000)**(1/3)))''')
|
222 |
+
mp = minimal_polynomial(eq + 3, x)
|
223 |
+
assert mp == 8000*x**2 - 48000*x + 71999
|
224 |
+
|
225 |
+
# issue 5888
|
226 |
+
assert minimal_polynomial(exp(I*pi/8), x) == x**8 + 1
|
227 |
+
|
228 |
+
mp = minimal_polynomial(sin(pi/7) + sqrt(2), x)
|
229 |
+
assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \
|
230 |
+
770912*x**4 - 268432*x**2 + 28561
|
231 |
+
mp = minimal_polynomial(cos(pi/7) + sqrt(2), x)
|
232 |
+
assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \
|
233 |
+
232*x - 239
|
234 |
+
mp = minimal_polynomial(exp(I*pi/7) + sqrt(2), x)
|
235 |
+
assert mp == x**12 - 2*x**11 - 9*x**10 + 16*x**9 + 43*x**8 - 70*x**7 - 97*x**6 + 126*x**5 + 211*x**4 - 212*x**3 - 37*x**2 + 142*x + 127
|
236 |
+
|
237 |
+
mp = minimal_polynomial(sin(pi/7) + sqrt(2), x)
|
238 |
+
assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \
|
239 |
+
770912*x**4 - 268432*x**2 + 28561
|
240 |
+
mp = minimal_polynomial(cos(pi/7) + sqrt(2), x)
|
241 |
+
assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \
|
242 |
+
232*x - 239
|
243 |
+
mp = minimal_polynomial(exp(I*pi/7) + sqrt(2), x)
|
244 |
+
assert mp == x**12 - 2*x**11 - 9*x**10 + 16*x**9 + 43*x**8 - 70*x**7 - 97*x**6 + 126*x**5 + 211*x**4 - 212*x**3 - 37*x**2 + 142*x + 127
|
245 |
+
|
246 |
+
mp = minimal_polynomial(exp(I*pi*Rational(2, 7)), x)
|
247 |
+
assert mp == x**6 + x**5 + x**4 + x**3 + x**2 + x + 1
|
248 |
+
mp = minimal_polynomial(exp(I*pi*Rational(2, 15)), x)
|
249 |
+
assert mp == x**8 - x**7 + x**5 - x**4 + x**3 - x + 1
|
250 |
+
mp = minimal_polynomial(cos(pi*Rational(2, 7)), x)
|
251 |
+
assert mp == 8*x**3 + 4*x**2 - 4*x - 1
|
252 |
+
mp = minimal_polynomial(sin(pi*Rational(2, 7)), x)
|
253 |
+
ex = (5*cos(pi*Rational(2, 7)) - 7)/(9*cos(pi/7) - 5*cos(pi*Rational(3, 7)))
|
254 |
+
mp = minimal_polynomial(ex, x)
|
255 |
+
assert mp == x**3 + 2*x**2 - x - 1
|
256 |
+
assert minimal_polynomial(-1/(2*cos(pi/7)), x) == x**3 + 2*x**2 - x - 1
|
257 |
+
assert minimal_polynomial(sin(pi*Rational(2, 15)), x) == \
|
258 |
+
256*x**8 - 448*x**6 + 224*x**4 - 32*x**2 + 1
|
259 |
+
assert minimal_polynomial(sin(pi*Rational(5, 14)), x) == 8*x**3 - 4*x**2 - 4*x + 1
|
260 |
+
assert minimal_polynomial(cos(pi/15), x) == 16*x**4 + 8*x**3 - 16*x**2 - 8*x + 1
|
261 |
+
|
262 |
+
ex = rootof(x**3 +x*4 + 1, 0)
|
263 |
+
mp = minimal_polynomial(ex, x)
|
264 |
+
assert mp == x**3 + 4*x + 1
|
265 |
+
mp = minimal_polynomial(ex + 1, x)
|
266 |
+
assert mp == x**3 - 3*x**2 + 7*x - 4
|
267 |
+
assert minimal_polynomial(exp(I*pi/3), x) == x**2 - x + 1
|
268 |
+
assert minimal_polynomial(exp(I*pi/4), x) == x**4 + 1
|
269 |
+
assert minimal_polynomial(exp(I*pi/6), x) == x**4 - x**2 + 1
|
270 |
+
assert minimal_polynomial(exp(I*pi/9), x) == x**6 - x**3 + 1
|
271 |
+
assert minimal_polynomial(exp(I*pi/10), x) == x**8 - x**6 + x**4 - x**2 + 1
|
272 |
+
assert minimal_polynomial(sin(pi/9), x) == 64*x**6 - 96*x**4 + 36*x**2 - 3
|
273 |
+
assert minimal_polynomial(sin(pi/11), x) == 1024*x**10 - 2816*x**8 + \
|
274 |
+
2816*x**6 - 1232*x**4 + 220*x**2 - 11
|
275 |
+
assert minimal_polynomial(sin(pi/21), x) == 4096*x**12 - 11264*x**10 + \
|
276 |
+
11264*x**8 - 4992*x**6 + 960*x**4 - 64*x**2 + 1
|
277 |
+
assert minimal_polynomial(cos(pi/9), x) == 8*x**3 - 6*x - 1
|
278 |
+
|
279 |
+
ex = 2**Rational(1, 3)*exp(2*I*pi/3)
|
280 |
+
assert minimal_polynomial(ex, x) == x**3 - 2
|
281 |
+
|
282 |
+
raises(NotAlgebraic, lambda: minimal_polynomial(cos(pi*sqrt(2)), x))
|
283 |
+
raises(NotAlgebraic, lambda: minimal_polynomial(sin(pi*sqrt(2)), x))
|
284 |
+
raises(NotAlgebraic, lambda: minimal_polynomial(exp(1.618*I*pi), x))
|
285 |
+
raises(NotAlgebraic, lambda: minimal_polynomial(exp(I*pi*sqrt(2)), x))
|
286 |
+
|
287 |
+
# issue 5934
|
288 |
+
ex = 1/(-36000 - 7200*sqrt(5) + (12*sqrt(10)*sqrt(sqrt(5) + 5) +
|
289 |
+
24*sqrt(10)*sqrt(-sqrt(5) + 5))**2) + 1
|
290 |
+
raises(ZeroDivisionError, lambda: minimal_polynomial(ex, x))
|
291 |
+
|
292 |
+
ex = sqrt(1 + 2**Rational(1,3)) + sqrt(1 + 2**Rational(1,4)) + sqrt(2)
|
293 |
+
mp = minimal_polynomial(ex, x)
|
294 |
+
assert degree(mp) == 48 and mp.subs({x:0}) == -16630256576
|
295 |
+
|
296 |
+
ex = tan(pi/5, evaluate=False)
|
297 |
+
mp = minimal_polynomial(ex, x)
|
298 |
+
assert mp == x**4 - 10*x**2 + 5
|
299 |
+
assert mp.subs(x, tan(pi/5)).is_zero
|
300 |
+
|
301 |
+
ex = tan(pi/6, evaluate=False)
|
302 |
+
mp = minimal_polynomial(ex, x)
|
303 |
+
assert mp == 3*x**2 - 1
|
304 |
+
assert mp.subs(x, tan(pi/6)).is_zero
|
305 |
+
|
306 |
+
ex = tan(pi/10, evaluate=False)
|
307 |
+
mp = minimal_polynomial(ex, x)
|
308 |
+
assert mp == 5*x**4 - 10*x**2 + 1
|
309 |
+
assert mp.subs(x, tan(pi/10)).is_zero
|
310 |
+
|
311 |
+
raises(NotAlgebraic, lambda: minimal_polynomial(tan(pi*sqrt(2)), x))
|
312 |
+
|
313 |
+
|
314 |
+
def test_minpoly_issue_7113():
|
315 |
+
# see discussion in https://github.com/sympy/sympy/pull/2234
|
316 |
+
from sympy.simplify.simplify import nsimplify
|
317 |
+
r = nsimplify(pi, tolerance=0.000000001)
|
318 |
+
mp = minimal_polynomial(r, x)
|
319 |
+
assert mp == 1768292677839237920489538677417507171630859375*x**109 - \
|
320 |
+
2734577732179183863586489182929671773182898498218854181690460140337930774573792597743853652058046464
|
321 |
+
|
322 |
+
|
323 |
+
def test_minpoly_issue_23677():
|
324 |
+
r1 = CRootOf(4000000*x**3 - 239960000*x**2 + 4782399900*x - 31663998001, 0)
|
325 |
+
r2 = CRootOf(4000000*x**3 - 239960000*x**2 + 4782399900*x - 31663998001, 1)
|
326 |
+
num = (7680000000000000000*r1**4*r2**4 - 614323200000000000000*r1**4*r2**3
|
327 |
+
+ 18458112576000000000000*r1**4*r2**2 - 246896663036160000000000*r1**4*r2
|
328 |
+
+ 1240473830323209600000000*r1**4 - 614323200000000000000*r1**3*r2**4
|
329 |
+
- 1476464424954240000000000*r1**3*r2**2 - 99225501687553535904000000*r1**3
|
330 |
+
+ 18458112576000000000000*r1**2*r2**4 - 1476464424954240000000000*r1**2*r2**3
|
331 |
+
- 593391458458356671712000000*r1**2*r2 + 2981354896834339226880720000*r1**2
|
332 |
+
- 246896663036160000000000*r1*r2**4 - 593391458458356671712000000*r1*r2**2
|
333 |
+
- 39878756418031796275267195200*r1 + 1240473830323209600000000*r2**4
|
334 |
+
- 99225501687553535904000000*r2**3 + 2981354896834339226880720000*r2**2 -
|
335 |
+
39878756418031796275267195200*r2 + 200361370275616536577343808012)
|
336 |
+
mp = (x**3 + 59426520028417434406408556687919*x**2 +
|
337 |
+
1161475464966574421163316896737773190861975156439163671112508400*x +
|
338 |
+
7467465541178623874454517208254940823818304424383315270991298807299003671748074773558707779600)
|
339 |
+
assert minimal_polynomial(num, x) == mp
|
340 |
+
|
341 |
+
|
342 |
+
def test_minpoly_issue_7574():
|
343 |
+
ex = -(-1)**Rational(1, 3) + (-1)**Rational(2,3)
|
344 |
+
assert minimal_polynomial(ex, x) == x + 1
|
345 |
+
|
346 |
+
|
347 |
+
def test_choose_factor():
|
348 |
+
# Test that this does not enter an infinite loop:
|
349 |
+
bad_factors = [Poly(x-2, x), Poly(x+2, x)]
|
350 |
+
raises(NotImplementedError, lambda: _choose_factor(bad_factors, x, sqrt(3)))
|
351 |
+
|
352 |
+
|
353 |
+
def test_minpoly_fraction_field():
|
354 |
+
assert minimal_polynomial(1/x, y) == -x*y + 1
|
355 |
+
assert minimal_polynomial(1 / (x + 1), y) == (x + 1)*y - 1
|
356 |
+
|
357 |
+
assert minimal_polynomial(sqrt(x), y) == y**2 - x
|
358 |
+
assert minimal_polynomial(sqrt(x + 1), y) == y**2 - x - 1
|
359 |
+
assert minimal_polynomial(sqrt(x) / x, y) == x*y**2 - 1
|
360 |
+
assert minimal_polynomial(sqrt(2) * sqrt(x), y) == y**2 - 2 * x
|
361 |
+
assert minimal_polynomial(sqrt(2) + sqrt(x), y) == \
|
362 |
+
y**4 + (-2*x - 4)*y**2 + x**2 - 4*x + 4
|
363 |
+
|
364 |
+
assert minimal_polynomial(x**Rational(1,3), y) == y**3 - x
|
365 |
+
assert minimal_polynomial(x**Rational(1,3) + sqrt(x), y) == \
|
366 |
+
y**6 - 3*x*y**4 - 2*x*y**3 + 3*x**2*y**2 - 6*x**2*y - x**3 + x**2
|
367 |
+
|
368 |
+
assert minimal_polynomial(sqrt(x) / z, y) == z**2*y**2 - x
|
369 |
+
assert minimal_polynomial(sqrt(x) / (z + 1), y) == (z**2 + 2*z + 1)*y**2 - x
|
370 |
+
|
371 |
+
assert minimal_polynomial(1/x, y, polys=True) == Poly(-x*y + 1, y, domain='ZZ(x)')
|
372 |
+
assert minimal_polynomial(1 / (x + 1), y, polys=True) == \
|
373 |
+
Poly((x + 1)*y - 1, y, domain='ZZ(x)')
|
374 |
+
assert minimal_polynomial(sqrt(x), y, polys=True) == Poly(y**2 - x, y, domain='ZZ(x)')
|
375 |
+
assert minimal_polynomial(sqrt(x) / z, y, polys=True) == \
|
376 |
+
Poly(z**2*y**2 - x, y, domain='ZZ(x, z)')
|
377 |
+
|
378 |
+
# this is (sqrt(1 + x**3)/x).integrate(x).diff(x) - sqrt(1 + x**3)/x
|
379 |
+
a = sqrt(x)/sqrt(1 + x**(-3)) - sqrt(x**3 + 1)/x + 1/(x**Rational(5, 2)* \
|
380 |
+
(1 + x**(-3))**Rational(3, 2)) + 1/(x**Rational(11, 2)*(1 + x**(-3))**Rational(3, 2))
|
381 |
+
|
382 |
+
assert minimal_polynomial(a, y) == y
|
383 |
+
|
384 |
+
raises(NotAlgebraic, lambda: minimal_polynomial(exp(x), y))
|
385 |
+
raises(GeneratorsError, lambda: minimal_polynomial(sqrt(x), x))
|
386 |
+
raises(GeneratorsError, lambda: minimal_polynomial(sqrt(x) - y, x))
|
387 |
+
raises(NotImplementedError, lambda: minimal_polynomial(sqrt(x), y, compose=False))
|
388 |
+
|
389 |
+
@slow
|
390 |
+
def test_minpoly_fraction_field_slow():
|
391 |
+
assert minimal_polynomial(minimal_polynomial(sqrt(x**Rational(1,5) - 1),
|
392 |
+
y).subs(y, sqrt(x**Rational(1,5) - 1)), z) == z
|
393 |
+
|
394 |
+
def test_minpoly_domain():
|
395 |
+
assert minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2))) == \
|
396 |
+
x - sqrt(2)
|
397 |
+
assert minimal_polynomial(sqrt(8), x, domain=QQ.algebraic_field(sqrt(2))) == \
|
398 |
+
x - 2*sqrt(2)
|
399 |
+
assert minimal_polynomial(sqrt(Rational(3,2)), x,
|
400 |
+
domain=QQ.algebraic_field(sqrt(2))) == 2*x**2 - 3
|
401 |
+
|
402 |
+
raises(NotAlgebraic, lambda: minimal_polynomial(y, x, domain=QQ))
|
403 |
+
|
404 |
+
|
405 |
+
def test_issue_14831():
|
406 |
+
a = -2*sqrt(2)*sqrt(12*sqrt(2) + 17)
|
407 |
+
assert minimal_polynomial(a, x) == x**2 + 16*x - 8
|
408 |
+
e = (-3*sqrt(12*sqrt(2) + 17) + 12*sqrt(2) +
|
409 |
+
17 - 2*sqrt(2)*sqrt(12*sqrt(2) + 17))
|
410 |
+
assert minimal_polynomial(e, x) == x
|
411 |
+
|
412 |
+
|
413 |
+
def test_issue_18248():
|
414 |
+
assert nonlinsolve([x*y**3-sqrt(2)/3, x*y**6-4/(9*(sqrt(3)))],x,y) == \
|
415 |
+
FiniteSet((sqrt(3)/2, sqrt(6)/3), (sqrt(3)/2, -sqrt(6)/6 - sqrt(2)*I/2),
|
416 |
+
(sqrt(3)/2, -sqrt(6)/6 + sqrt(2)*I/2))
|
417 |
+
|
418 |
+
|
419 |
+
def test_issue_13230():
|
420 |
+
c1 = Circle(Point2D(3, sqrt(5)), 5)
|
421 |
+
c2 = Circle(Point2D(4, sqrt(7)), 6)
|
422 |
+
assert intersection(c1, c2) == [Point2D(-1 + (-sqrt(7) + sqrt(5))*(-2*sqrt(7)/29
|
423 |
+
+ 9*sqrt(5)/29 + sqrt(196*sqrt(35) + 1941)/29), -2*sqrt(7)/29 + 9*sqrt(5)/29
|
424 |
+
+ sqrt(196*sqrt(35) + 1941)/29), Point2D(-1 + (-sqrt(7) + sqrt(5))*(-sqrt(196*sqrt(35)
|
425 |
+
+ 1941)/29 - 2*sqrt(7)/29 + 9*sqrt(5)/29), -sqrt(196*sqrt(35) + 1941)/29 - 2*sqrt(7)/29 + 9*sqrt(5)/29)]
|
426 |
+
|
427 |
+
def test_issue_19760():
|
428 |
+
e = 1/(sqrt(1 + sqrt(2)) - sqrt(2)*sqrt(1 + sqrt(2))) + 1
|
429 |
+
mp_expected = x**4 - 4*x**3 + 4*x**2 - 2
|
430 |
+
|
431 |
+
for comp in (True, False):
|
432 |
+
mp = Poly(minimal_polynomial(e, compose=comp))
|
433 |
+
assert mp(x) == mp_expected, "minimal_polynomial(e, compose=%s) = %s; %s expected" % (comp, mp(x), mp_expected)
|
434 |
+
|
435 |
+
|
436 |
+
def test_issue_20163():
|
437 |
+
assert apart(1/(x**6+1), extension=[sqrt(3), I]) == \
|
438 |
+
(sqrt(3) + I)/(2*x + sqrt(3) + I)/6 + \
|
439 |
+
(sqrt(3) - I)/(2*x + sqrt(3) - I)/6 - \
|
440 |
+
(sqrt(3) - I)/(2*x - sqrt(3) + I)/6 - \
|
441 |
+
(sqrt(3) + I)/(2*x - sqrt(3) - I)/6 + \
|
442 |
+
I/(x + I)/6 - I/(x - I)/6
|
443 |
+
|
444 |
+
|
445 |
+
def test_issue_22559():
|
446 |
+
alpha = AlgebraicNumber(sqrt(2))
|
447 |
+
assert minimal_polynomial(alpha**3, x) == x**2 - 8
|
448 |
+
|
449 |
+
|
450 |
+
def test_issue_22561():
|
451 |
+
a = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1) / 2, 0, S(-9) / 2, 0], gen=x)
|
452 |
+
assert a.as_expr() == sqrt(2)
|
453 |
+
assert minimal_polynomial(a, x) == x**2 - 2
|
454 |
+
assert minimal_polynomial(a**3, x) == x**2 - 8
|
455 |
+
|
456 |
+
|
457 |
+
def test_separate_sq_not_impl():
|
458 |
+
raises(NotImplementedError, lambda: _separate_sq(x**(S(1)/3) + x))
|
459 |
+
|
460 |
+
|
461 |
+
def test_minpoly_op_algebraic_element_not_impl():
|
462 |
+
raises(NotImplementedError,
|
463 |
+
lambda: _minpoly_op_algebraic_element(Pow, sqrt(2), sqrt(3), x, QQ))
|
464 |
+
|
465 |
+
|
466 |
+
def test_minpoly_groebner():
|
467 |
+
assert _minpoly_groebner(S(2)/3, x, Poly) == 3*x - 2
|
468 |
+
assert _minpoly_groebner(
|
469 |
+
(sqrt(2) + 3)*(sqrt(2) + 1), x, Poly) == x**2 - 10*x - 7
|
470 |
+
assert _minpoly_groebner((sqrt(2) + 3)**(S(1)/3)*(sqrt(2) + 1)**(S(1)/3),
|
471 |
+
x, Poly) == x**6 - 10*x**3 - 7
|
472 |
+
assert _minpoly_groebner((sqrt(2) + 3)**(-S(1)/3)*(sqrt(2) + 1)**(S(1)/3),
|
473 |
+
x, Poly) == 7*x**6 - 2*x**3 - 1
|
474 |
+
raises(NotAlgebraic, lambda: _minpoly_groebner(pi**2, x, Poly))
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_modules.py
ADDED
@@ -0,0 +1,752 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.abc import x, zeta
|
2 |
+
from sympy.polys import Poly, cyclotomic_poly
|
3 |
+
from sympy.polys.domains import FF, QQ, ZZ
|
4 |
+
from sympy.polys.matrices import DomainMatrix, DM
|
5 |
+
from sympy.polys.numberfields.exceptions import (
|
6 |
+
ClosureFailure, MissingUnityError, StructureError
|
7 |
+
)
|
8 |
+
from sympy.polys.numberfields.modules import (
|
9 |
+
Module, ModuleElement, ModuleEndomorphism, PowerBasis, PowerBasisElement,
|
10 |
+
find_min_poly, is_sq_maxrank_HNF, make_mod_elt, to_col,
|
11 |
+
)
|
12 |
+
from sympy.polys.numberfields.utilities import is_int
|
13 |
+
from sympy.polys.polyerrors import UnificationFailed
|
14 |
+
from sympy.testing.pytest import raises
|
15 |
+
|
16 |
+
|
17 |
+
def test_to_col():
|
18 |
+
c = [1, 2, 3, 4]
|
19 |
+
m = to_col(c)
|
20 |
+
assert m.domain.is_ZZ
|
21 |
+
assert m.shape == (4, 1)
|
22 |
+
assert m.flat() == c
|
23 |
+
|
24 |
+
|
25 |
+
def test_Module_NotImplemented():
|
26 |
+
M = Module()
|
27 |
+
raises(NotImplementedError, lambda: M.n)
|
28 |
+
raises(NotImplementedError, lambda: M.mult_tab())
|
29 |
+
raises(NotImplementedError, lambda: M.represent(None))
|
30 |
+
raises(NotImplementedError, lambda: M.starts_with_unity())
|
31 |
+
raises(NotImplementedError, lambda: M.element_from_rational(QQ(2, 3)))
|
32 |
+
|
33 |
+
|
34 |
+
def test_Module_ancestors():
|
35 |
+
T = Poly(cyclotomic_poly(5, x))
|
36 |
+
A = PowerBasis(T)
|
37 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
38 |
+
C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
|
39 |
+
D = B.submodule_from_matrix(5 * DomainMatrix.eye(4, ZZ))
|
40 |
+
assert C.ancestors(include_self=True) == [A, B, C]
|
41 |
+
assert D.ancestors(include_self=True) == [A, B, D]
|
42 |
+
assert C.power_basis_ancestor() == A
|
43 |
+
assert C.nearest_common_ancestor(D) == B
|
44 |
+
M = Module()
|
45 |
+
assert M.power_basis_ancestor() is None
|
46 |
+
|
47 |
+
|
48 |
+
def test_Module_compat_col():
|
49 |
+
T = Poly(cyclotomic_poly(5, x))
|
50 |
+
A = PowerBasis(T)
|
51 |
+
col = to_col([1, 2, 3, 4])
|
52 |
+
row = col.transpose()
|
53 |
+
assert A.is_compat_col(col) is True
|
54 |
+
assert A.is_compat_col(row) is False
|
55 |
+
assert A.is_compat_col(1) is False
|
56 |
+
assert A.is_compat_col(DomainMatrix.eye(3, ZZ)[:, 0]) is False
|
57 |
+
assert A.is_compat_col(DomainMatrix.eye(4, QQ)[:, 0]) is False
|
58 |
+
assert A.is_compat_col(DomainMatrix.eye(4, ZZ)[:, 0]) is True
|
59 |
+
|
60 |
+
|
61 |
+
def test_Module_call():
|
62 |
+
T = Poly(cyclotomic_poly(5, x))
|
63 |
+
B = PowerBasis(T)
|
64 |
+
assert B(0).col.flat() == [1, 0, 0, 0]
|
65 |
+
assert B(1).col.flat() == [0, 1, 0, 0]
|
66 |
+
col = DomainMatrix.eye(4, ZZ)[:, 2]
|
67 |
+
assert B(col).col == col
|
68 |
+
raises(ValueError, lambda: B(-1))
|
69 |
+
|
70 |
+
|
71 |
+
def test_Module_starts_with_unity():
|
72 |
+
T = Poly(cyclotomic_poly(5, x))
|
73 |
+
A = PowerBasis(T)
|
74 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
75 |
+
assert A.starts_with_unity() is True
|
76 |
+
assert B.starts_with_unity() is False
|
77 |
+
|
78 |
+
|
79 |
+
def test_Module_basis_elements():
|
80 |
+
T = Poly(cyclotomic_poly(5, x))
|
81 |
+
A = PowerBasis(T)
|
82 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
83 |
+
basis = B.basis_elements()
|
84 |
+
bp = B.basis_element_pullbacks()
|
85 |
+
for i, (e, p) in enumerate(zip(basis, bp)):
|
86 |
+
c = [0] * 4
|
87 |
+
assert e.module == B
|
88 |
+
assert p.module == A
|
89 |
+
c[i] = 1
|
90 |
+
assert e == B(to_col(c))
|
91 |
+
c[i] = 2
|
92 |
+
assert p == A(to_col(c))
|
93 |
+
|
94 |
+
|
95 |
+
def test_Module_zero():
|
96 |
+
T = Poly(cyclotomic_poly(5, x))
|
97 |
+
A = PowerBasis(T)
|
98 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
99 |
+
assert A.zero().col.flat() == [0, 0, 0, 0]
|
100 |
+
assert A.zero().module == A
|
101 |
+
assert B.zero().col.flat() == [0, 0, 0, 0]
|
102 |
+
assert B.zero().module == B
|
103 |
+
|
104 |
+
|
105 |
+
def test_Module_one():
|
106 |
+
T = Poly(cyclotomic_poly(5, x))
|
107 |
+
A = PowerBasis(T)
|
108 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
109 |
+
assert A.one().col.flat() == [1, 0, 0, 0]
|
110 |
+
assert A.one().module == A
|
111 |
+
assert B.one().col.flat() == [1, 0, 0, 0]
|
112 |
+
assert B.one().module == A
|
113 |
+
|
114 |
+
|
115 |
+
def test_Module_element_from_rational():
|
116 |
+
T = Poly(cyclotomic_poly(5, x))
|
117 |
+
A = PowerBasis(T)
|
118 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
119 |
+
rA = A.element_from_rational(QQ(22, 7))
|
120 |
+
rB = B.element_from_rational(QQ(22, 7))
|
121 |
+
assert rA.coeffs == [22, 0, 0, 0]
|
122 |
+
assert rA.denom == 7
|
123 |
+
assert rA.module == A
|
124 |
+
assert rB.coeffs == [22, 0, 0, 0]
|
125 |
+
assert rB.denom == 7
|
126 |
+
assert rB.module == A
|
127 |
+
|
128 |
+
|
129 |
+
def test_Module_submodule_from_gens():
|
130 |
+
T = Poly(cyclotomic_poly(5, x))
|
131 |
+
A = PowerBasis(T)
|
132 |
+
gens = [2*A(0), 2*A(1), 6*A(0), 6*A(1)]
|
133 |
+
B = A.submodule_from_gens(gens)
|
134 |
+
# Because the 3rd and 4th generators do not add anything new, we expect
|
135 |
+
# the cols of the matrix of B to just reproduce the first two gens:
|
136 |
+
M = gens[0].column().hstack(gens[1].column())
|
137 |
+
assert B.matrix == M
|
138 |
+
# At least one generator must be provided:
|
139 |
+
raises(ValueError, lambda: A.submodule_from_gens([]))
|
140 |
+
# All generators must belong to A:
|
141 |
+
raises(ValueError, lambda: A.submodule_from_gens([3*A(0), B(0)]))
|
142 |
+
|
143 |
+
|
144 |
+
def test_Module_submodule_from_matrix():
|
145 |
+
T = Poly(cyclotomic_poly(5, x))
|
146 |
+
A = PowerBasis(T)
|
147 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
148 |
+
e = B(to_col([1, 2, 3, 4]))
|
149 |
+
f = e.to_parent()
|
150 |
+
assert f.col.flat() == [2, 4, 6, 8]
|
151 |
+
# Matrix must be over ZZ:
|
152 |
+
raises(ValueError, lambda: A.submodule_from_matrix(DomainMatrix.eye(4, QQ)))
|
153 |
+
# Number of rows of matrix must equal number of generators of module A:
|
154 |
+
raises(ValueError, lambda: A.submodule_from_matrix(2 * DomainMatrix.eye(5, ZZ)))
|
155 |
+
|
156 |
+
|
157 |
+
def test_Module_whole_submodule():
|
158 |
+
T = Poly(cyclotomic_poly(5, x))
|
159 |
+
A = PowerBasis(T)
|
160 |
+
B = A.whole_submodule()
|
161 |
+
e = B(to_col([1, 2, 3, 4]))
|
162 |
+
f = e.to_parent()
|
163 |
+
assert f.col.flat() == [1, 2, 3, 4]
|
164 |
+
e0, e1, e2, e3 = B(0), B(1), B(2), B(3)
|
165 |
+
assert e2 * e3 == e0
|
166 |
+
assert e3 ** 2 == e1
|
167 |
+
|
168 |
+
|
169 |
+
def test_PowerBasis_repr():
|
170 |
+
T = Poly(cyclotomic_poly(5, x))
|
171 |
+
A = PowerBasis(T)
|
172 |
+
assert repr(A) == 'PowerBasis(x**4 + x**3 + x**2 + x + 1)'
|
173 |
+
|
174 |
+
|
175 |
+
def test_PowerBasis_eq():
|
176 |
+
T = Poly(cyclotomic_poly(5, x))
|
177 |
+
A = PowerBasis(T)
|
178 |
+
B = PowerBasis(T)
|
179 |
+
assert A == B
|
180 |
+
|
181 |
+
|
182 |
+
def test_PowerBasis_mult_tab():
|
183 |
+
T = Poly(cyclotomic_poly(5, x))
|
184 |
+
A = PowerBasis(T)
|
185 |
+
M = A.mult_tab()
|
186 |
+
exp = {0: {0: [1, 0, 0, 0], 1: [0, 1, 0, 0], 2: [0, 0, 1, 0], 3: [0, 0, 0, 1]},
|
187 |
+
1: {1: [0, 0, 1, 0], 2: [0, 0, 0, 1], 3: [-1, -1, -1, -1]},
|
188 |
+
2: {2: [-1, -1, -1, -1], 3: [1, 0, 0, 0]},
|
189 |
+
3: {3: [0, 1, 0, 0]}}
|
190 |
+
# We get the table we expect:
|
191 |
+
assert M == exp
|
192 |
+
# And all entries are of expected type:
|
193 |
+
assert all(is_int(c) for u in M for v in M[u] for c in M[u][v])
|
194 |
+
|
195 |
+
|
196 |
+
def test_PowerBasis_represent():
|
197 |
+
T = Poly(cyclotomic_poly(5, x))
|
198 |
+
A = PowerBasis(T)
|
199 |
+
col = to_col([1, 2, 3, 4])
|
200 |
+
a = A(col)
|
201 |
+
assert A.represent(a) == col
|
202 |
+
b = A(col, denom=2)
|
203 |
+
raises(ClosureFailure, lambda: A.represent(b))
|
204 |
+
|
205 |
+
|
206 |
+
def test_PowerBasis_element_from_poly():
|
207 |
+
T = Poly(cyclotomic_poly(5, x))
|
208 |
+
A = PowerBasis(T)
|
209 |
+
f = Poly(1 + 2*x)
|
210 |
+
g = Poly(x**4)
|
211 |
+
h = Poly(0, x)
|
212 |
+
assert A.element_from_poly(f).coeffs == [1, 2, 0, 0]
|
213 |
+
assert A.element_from_poly(g).coeffs == [-1, -1, -1, -1]
|
214 |
+
assert A.element_from_poly(h).coeffs == [0, 0, 0, 0]
|
215 |
+
|
216 |
+
|
217 |
+
def test_PowerBasis_element__conversions():
|
218 |
+
k = QQ.cyclotomic_field(5)
|
219 |
+
L = QQ.cyclotomic_field(7)
|
220 |
+
B = PowerBasis(k)
|
221 |
+
|
222 |
+
# ANP --> PowerBasisElement
|
223 |
+
a = k([QQ(1, 2), QQ(1, 3), 5, 7])
|
224 |
+
e = B.element_from_ANP(a)
|
225 |
+
assert e.coeffs == [42, 30, 2, 3]
|
226 |
+
assert e.denom == 6
|
227 |
+
|
228 |
+
# PowerBasisElement --> ANP
|
229 |
+
assert e.to_ANP() == a
|
230 |
+
|
231 |
+
# Cannot convert ANP from different field
|
232 |
+
d = L([QQ(1, 2), QQ(1, 3), 5, 7])
|
233 |
+
raises(UnificationFailed, lambda: B.element_from_ANP(d))
|
234 |
+
|
235 |
+
# AlgebraicNumber --> PowerBasisElement
|
236 |
+
alpha = k.to_alg_num(a)
|
237 |
+
eps = B.element_from_alg_num(alpha)
|
238 |
+
assert eps.coeffs == [42, 30, 2, 3]
|
239 |
+
assert eps.denom == 6
|
240 |
+
|
241 |
+
# PowerBasisElement --> AlgebraicNumber
|
242 |
+
assert eps.to_alg_num() == alpha
|
243 |
+
|
244 |
+
# Cannot convert AlgebraicNumber from different field
|
245 |
+
delta = L.to_alg_num(d)
|
246 |
+
raises(UnificationFailed, lambda: B.element_from_alg_num(delta))
|
247 |
+
|
248 |
+
# When we don't know the field:
|
249 |
+
C = PowerBasis(k.ext.minpoly)
|
250 |
+
# Can convert from AlgebraicNumber:
|
251 |
+
eps = C.element_from_alg_num(alpha)
|
252 |
+
assert eps.coeffs == [42, 30, 2, 3]
|
253 |
+
assert eps.denom == 6
|
254 |
+
# But can't convert back:
|
255 |
+
raises(StructureError, lambda: eps.to_alg_num())
|
256 |
+
|
257 |
+
|
258 |
+
def test_Submodule_repr():
|
259 |
+
T = Poly(cyclotomic_poly(5, x))
|
260 |
+
A = PowerBasis(T)
|
261 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ), denom=3)
|
262 |
+
assert repr(B) == 'Submodule[[2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0], [0, 0, 0, 2]]/3'
|
263 |
+
|
264 |
+
|
265 |
+
def test_Submodule_reduced():
|
266 |
+
T = Poly(cyclotomic_poly(5, x))
|
267 |
+
A = PowerBasis(T)
|
268 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
269 |
+
C = A.submodule_from_matrix(6 * DomainMatrix.eye(4, ZZ), denom=3)
|
270 |
+
D = C.reduced()
|
271 |
+
assert D.denom == 1 and D == C == B
|
272 |
+
|
273 |
+
|
274 |
+
def test_Submodule_discard_before():
|
275 |
+
T = Poly(cyclotomic_poly(5, x))
|
276 |
+
A = PowerBasis(T)
|
277 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
278 |
+
B.compute_mult_tab()
|
279 |
+
C = B.discard_before(2)
|
280 |
+
assert C.parent == B.parent
|
281 |
+
assert B.is_sq_maxrank_HNF() and not C.is_sq_maxrank_HNF()
|
282 |
+
assert C.matrix == B.matrix[:, 2:]
|
283 |
+
assert C.mult_tab() == {0: {0: [-2, -2], 1: [0, 0]}, 1: {1: [0, 0]}}
|
284 |
+
|
285 |
+
|
286 |
+
def test_Submodule_QQ_matrix():
|
287 |
+
T = Poly(cyclotomic_poly(5, x))
|
288 |
+
A = PowerBasis(T)
|
289 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
290 |
+
C = A.submodule_from_matrix(6 * DomainMatrix.eye(4, ZZ), denom=3)
|
291 |
+
assert C.QQ_matrix == B.QQ_matrix
|
292 |
+
|
293 |
+
|
294 |
+
def test_Submodule_represent():
|
295 |
+
T = Poly(cyclotomic_poly(5, x))
|
296 |
+
A = PowerBasis(T)
|
297 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
298 |
+
C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
|
299 |
+
a0 = A(to_col([6, 12, 18, 24]))
|
300 |
+
a1 = A(to_col([2, 4, 6, 8]))
|
301 |
+
a2 = A(to_col([1, 3, 5, 7]))
|
302 |
+
|
303 |
+
b1 = B.represent(a1)
|
304 |
+
assert b1.flat() == [1, 2, 3, 4]
|
305 |
+
|
306 |
+
c0 = C.represent(a0)
|
307 |
+
assert c0.flat() == [1, 2, 3, 4]
|
308 |
+
|
309 |
+
Y = A.submodule_from_matrix(DomainMatrix([
|
310 |
+
[1, 0, 0, 0],
|
311 |
+
[0, 1, 0, 0],
|
312 |
+
[0, 0, 1, 0],
|
313 |
+
], (3, 4), ZZ).transpose())
|
314 |
+
|
315 |
+
U = Poly(cyclotomic_poly(7, x))
|
316 |
+
Z = PowerBasis(U)
|
317 |
+
z0 = Z(to_col([1, 2, 3, 4, 5, 6]))
|
318 |
+
|
319 |
+
raises(ClosureFailure, lambda: Y.represent(A(3)))
|
320 |
+
raises(ClosureFailure, lambda: B.represent(a2))
|
321 |
+
raises(ClosureFailure, lambda: B.represent(z0))
|
322 |
+
|
323 |
+
|
324 |
+
def test_Submodule_is_compat_submodule():
|
325 |
+
T = Poly(cyclotomic_poly(5, x))
|
326 |
+
A = PowerBasis(T)
|
327 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
328 |
+
C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
|
329 |
+
D = C.submodule_from_matrix(5 * DomainMatrix.eye(4, ZZ))
|
330 |
+
assert B.is_compat_submodule(C) is True
|
331 |
+
assert B.is_compat_submodule(A) is False
|
332 |
+
assert B.is_compat_submodule(D) is False
|
333 |
+
|
334 |
+
|
335 |
+
def test_Submodule_eq():
|
336 |
+
T = Poly(cyclotomic_poly(5, x))
|
337 |
+
A = PowerBasis(T)
|
338 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
339 |
+
C = A.submodule_from_matrix(6 * DomainMatrix.eye(4, ZZ), denom=3)
|
340 |
+
assert C == B
|
341 |
+
|
342 |
+
|
343 |
+
def test_Submodule_add():
|
344 |
+
T = Poly(cyclotomic_poly(5, x))
|
345 |
+
A = PowerBasis(T)
|
346 |
+
B = A.submodule_from_matrix(DomainMatrix([
|
347 |
+
[4, 0, 0, 0],
|
348 |
+
[0, 4, 0, 0],
|
349 |
+
], (2, 4), ZZ).transpose(), denom=6)
|
350 |
+
C = A.submodule_from_matrix(DomainMatrix([
|
351 |
+
[0, 10, 0, 0],
|
352 |
+
[0, 0, 7, 0],
|
353 |
+
], (2, 4), ZZ).transpose(), denom=15)
|
354 |
+
D = A.submodule_from_matrix(DomainMatrix([
|
355 |
+
[20, 0, 0, 0],
|
356 |
+
[ 0, 20, 0, 0],
|
357 |
+
[ 0, 0, 14, 0],
|
358 |
+
], (3, 4), ZZ).transpose(), denom=30)
|
359 |
+
assert B + C == D
|
360 |
+
|
361 |
+
U = Poly(cyclotomic_poly(7, x))
|
362 |
+
Z = PowerBasis(U)
|
363 |
+
Y = Z.submodule_from_gens([Z(0), Z(1)])
|
364 |
+
raises(TypeError, lambda: B + Y)
|
365 |
+
|
366 |
+
|
367 |
+
def test_Submodule_mul():
|
368 |
+
T = Poly(cyclotomic_poly(5, x))
|
369 |
+
A = PowerBasis(T)
|
370 |
+
C = A.submodule_from_matrix(DomainMatrix([
|
371 |
+
[0, 10, 0, 0],
|
372 |
+
[0, 0, 7, 0],
|
373 |
+
], (2, 4), ZZ).transpose(), denom=15)
|
374 |
+
C1 = A.submodule_from_matrix(DomainMatrix([
|
375 |
+
[0, 20, 0, 0],
|
376 |
+
[0, 0, 14, 0],
|
377 |
+
], (2, 4), ZZ).transpose(), denom=3)
|
378 |
+
C2 = A.submodule_from_matrix(DomainMatrix([
|
379 |
+
[0, 0, 10, 0],
|
380 |
+
[0, 0, 0, 7],
|
381 |
+
], (2, 4), ZZ).transpose(), denom=15)
|
382 |
+
C3_unred = A.submodule_from_matrix(DomainMatrix([
|
383 |
+
[0, 0, 100, 0],
|
384 |
+
[0, 0, 0, 70],
|
385 |
+
[0, 0, 0, 70],
|
386 |
+
[-49, -49, -49, -49]
|
387 |
+
], (4, 4), ZZ).transpose(), denom=225)
|
388 |
+
C3 = A.submodule_from_matrix(DomainMatrix([
|
389 |
+
[4900, 4900, 0, 0],
|
390 |
+
[4410, 4410, 10, 0],
|
391 |
+
[2107, 2107, 7, 7]
|
392 |
+
], (3, 4), ZZ).transpose(), denom=225)
|
393 |
+
assert C * 1 == C
|
394 |
+
assert C ** 1 == C
|
395 |
+
assert C * 10 == C1
|
396 |
+
assert C * A(1) == C2
|
397 |
+
assert C.mul(C, hnf=False) == C3_unred
|
398 |
+
assert C * C == C3
|
399 |
+
assert C ** 2 == C3
|
400 |
+
|
401 |
+
|
402 |
+
def test_Submodule_reduce_element():
|
403 |
+
T = Poly(cyclotomic_poly(5, x))
|
404 |
+
A = PowerBasis(T)
|
405 |
+
B = A.whole_submodule()
|
406 |
+
b = B(to_col([90, 84, 80, 75]), denom=120)
|
407 |
+
|
408 |
+
C = B.submodule_from_matrix(DomainMatrix.eye(4, ZZ), denom=2)
|
409 |
+
b_bar_expected = B(to_col([30, 24, 20, 15]), denom=120)
|
410 |
+
b_bar = C.reduce_element(b)
|
411 |
+
assert b_bar == b_bar_expected
|
412 |
+
|
413 |
+
C = B.submodule_from_matrix(DomainMatrix.eye(4, ZZ), denom=4)
|
414 |
+
b_bar_expected = B(to_col([0, 24, 20, 15]), denom=120)
|
415 |
+
b_bar = C.reduce_element(b)
|
416 |
+
assert b_bar == b_bar_expected
|
417 |
+
|
418 |
+
C = B.submodule_from_matrix(DomainMatrix.eye(4, ZZ), denom=8)
|
419 |
+
b_bar_expected = B(to_col([0, 9, 5, 0]), denom=120)
|
420 |
+
b_bar = C.reduce_element(b)
|
421 |
+
assert b_bar == b_bar_expected
|
422 |
+
|
423 |
+
a = A(to_col([1, 2, 3, 4]))
|
424 |
+
raises(NotImplementedError, lambda: C.reduce_element(a))
|
425 |
+
|
426 |
+
C = B.submodule_from_matrix(DomainMatrix([
|
427 |
+
[5, 4, 3, 2],
|
428 |
+
[0, 8, 7, 6],
|
429 |
+
[0, 0,11,12],
|
430 |
+
[0, 0, 0, 1]
|
431 |
+
], (4, 4), ZZ).transpose())
|
432 |
+
raises(StructureError, lambda: C.reduce_element(b))
|
433 |
+
|
434 |
+
|
435 |
+
def test_is_HNF():
|
436 |
+
M = DM([
|
437 |
+
[3, 2, 1],
|
438 |
+
[0, 2, 1],
|
439 |
+
[0, 0, 1]
|
440 |
+
], ZZ)
|
441 |
+
M1 = DM([
|
442 |
+
[3, 2, 1],
|
443 |
+
[0, -2, 1],
|
444 |
+
[0, 0, 1]
|
445 |
+
], ZZ)
|
446 |
+
M2 = DM([
|
447 |
+
[3, 2, 3],
|
448 |
+
[0, 2, 1],
|
449 |
+
[0, 0, 1]
|
450 |
+
], ZZ)
|
451 |
+
assert is_sq_maxrank_HNF(M) is True
|
452 |
+
assert is_sq_maxrank_HNF(M1) is False
|
453 |
+
assert is_sq_maxrank_HNF(M2) is False
|
454 |
+
|
455 |
+
|
456 |
+
def test_make_mod_elt():
|
457 |
+
T = Poly(cyclotomic_poly(5, x))
|
458 |
+
A = PowerBasis(T)
|
459 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
460 |
+
col = to_col([1, 2, 3, 4])
|
461 |
+
eA = make_mod_elt(A, col)
|
462 |
+
eB = make_mod_elt(B, col)
|
463 |
+
assert isinstance(eA, PowerBasisElement)
|
464 |
+
assert not isinstance(eB, PowerBasisElement)
|
465 |
+
|
466 |
+
|
467 |
+
def test_ModuleElement_repr():
|
468 |
+
T = Poly(cyclotomic_poly(5, x))
|
469 |
+
A = PowerBasis(T)
|
470 |
+
e = A(to_col([1, 2, 3, 4]), denom=2)
|
471 |
+
assert repr(e) == '[1, 2, 3, 4]/2'
|
472 |
+
|
473 |
+
|
474 |
+
def test_ModuleElement_reduced():
|
475 |
+
T = Poly(cyclotomic_poly(5, x))
|
476 |
+
A = PowerBasis(T)
|
477 |
+
e = A(to_col([2, 4, 6, 8]), denom=2)
|
478 |
+
f = e.reduced()
|
479 |
+
assert f.denom == 1 and f == e
|
480 |
+
|
481 |
+
|
482 |
+
def test_ModuleElement_reduced_mod_p():
|
483 |
+
T = Poly(cyclotomic_poly(5, x))
|
484 |
+
A = PowerBasis(T)
|
485 |
+
e = A(to_col([20, 40, 60, 80]))
|
486 |
+
f = e.reduced_mod_p(7)
|
487 |
+
assert f.coeffs == [-1, -2, -3, 3]
|
488 |
+
|
489 |
+
|
490 |
+
def test_ModuleElement_from_int_list():
|
491 |
+
T = Poly(cyclotomic_poly(5, x))
|
492 |
+
A = PowerBasis(T)
|
493 |
+
c = [1, 2, 3, 4]
|
494 |
+
assert ModuleElement.from_int_list(A, c).coeffs == c
|
495 |
+
|
496 |
+
|
497 |
+
def test_ModuleElement_len():
|
498 |
+
T = Poly(cyclotomic_poly(5, x))
|
499 |
+
A = PowerBasis(T)
|
500 |
+
e = A(0)
|
501 |
+
assert len(e) == 4
|
502 |
+
|
503 |
+
|
504 |
+
def test_ModuleElement_column():
|
505 |
+
T = Poly(cyclotomic_poly(5, x))
|
506 |
+
A = PowerBasis(T)
|
507 |
+
e = A(0)
|
508 |
+
col1 = e.column()
|
509 |
+
assert col1 == e.col and col1 is not e.col
|
510 |
+
col2 = e.column(domain=FF(5))
|
511 |
+
assert col2.domain.is_FF
|
512 |
+
|
513 |
+
|
514 |
+
def test_ModuleElement_QQ_col():
|
515 |
+
T = Poly(cyclotomic_poly(5, x))
|
516 |
+
A = PowerBasis(T)
|
517 |
+
e = A(to_col([1, 2, 3, 4]), denom=1)
|
518 |
+
f = A(to_col([3, 6, 9, 12]), denom=3)
|
519 |
+
assert e.QQ_col == f.QQ_col
|
520 |
+
|
521 |
+
|
522 |
+
def test_ModuleElement_to_ancestors():
|
523 |
+
T = Poly(cyclotomic_poly(5, x))
|
524 |
+
A = PowerBasis(T)
|
525 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
526 |
+
C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
|
527 |
+
D = C.submodule_from_matrix(5 * DomainMatrix.eye(4, ZZ))
|
528 |
+
eD = D(0)
|
529 |
+
eC = eD.to_parent()
|
530 |
+
eB = eD.to_ancestor(B)
|
531 |
+
eA = eD.over_power_basis()
|
532 |
+
assert eC.module is C and eC.coeffs == [5, 0, 0, 0]
|
533 |
+
assert eB.module is B and eB.coeffs == [15, 0, 0, 0]
|
534 |
+
assert eA.module is A and eA.coeffs == [30, 0, 0, 0]
|
535 |
+
|
536 |
+
a = A(0)
|
537 |
+
raises(ValueError, lambda: a.to_parent())
|
538 |
+
|
539 |
+
|
540 |
+
def test_ModuleElement_compatibility():
|
541 |
+
T = Poly(cyclotomic_poly(5, x))
|
542 |
+
A = PowerBasis(T)
|
543 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
544 |
+
C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
|
545 |
+
D = B.submodule_from_matrix(5 * DomainMatrix.eye(4, ZZ))
|
546 |
+
assert C(0).is_compat(C(1)) is True
|
547 |
+
assert C(0).is_compat(D(0)) is False
|
548 |
+
u, v = C(0).unify(D(0))
|
549 |
+
assert u.module is B and v.module is B
|
550 |
+
assert C(C.represent(u)) == C(0) and D(D.represent(v)) == D(0)
|
551 |
+
|
552 |
+
u, v = C(0).unify(C(1))
|
553 |
+
assert u == C(0) and v == C(1)
|
554 |
+
|
555 |
+
U = Poly(cyclotomic_poly(7, x))
|
556 |
+
Z = PowerBasis(U)
|
557 |
+
raises(UnificationFailed, lambda: C(0).unify(Z(1)))
|
558 |
+
|
559 |
+
|
560 |
+
def test_ModuleElement_eq():
|
561 |
+
T = Poly(cyclotomic_poly(5, x))
|
562 |
+
A = PowerBasis(T)
|
563 |
+
e = A(to_col([1, 2, 3, 4]), denom=1)
|
564 |
+
f = A(to_col([3, 6, 9, 12]), denom=3)
|
565 |
+
assert e == f
|
566 |
+
|
567 |
+
U = Poly(cyclotomic_poly(7, x))
|
568 |
+
Z = PowerBasis(U)
|
569 |
+
assert e != Z(0)
|
570 |
+
assert e != 3.14
|
571 |
+
|
572 |
+
|
573 |
+
def test_ModuleElement_equiv():
|
574 |
+
T = Poly(cyclotomic_poly(5, x))
|
575 |
+
A = PowerBasis(T)
|
576 |
+
e = A(to_col([1, 2, 3, 4]), denom=1)
|
577 |
+
f = A(to_col([3, 6, 9, 12]), denom=3)
|
578 |
+
assert e.equiv(f)
|
579 |
+
|
580 |
+
C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
|
581 |
+
g = C(to_col([1, 2, 3, 4]), denom=1)
|
582 |
+
h = A(to_col([3, 6, 9, 12]), denom=1)
|
583 |
+
assert g.equiv(h)
|
584 |
+
assert C(to_col([5, 0, 0, 0]), denom=7).equiv(QQ(15, 7))
|
585 |
+
|
586 |
+
U = Poly(cyclotomic_poly(7, x))
|
587 |
+
Z = PowerBasis(U)
|
588 |
+
raises(UnificationFailed, lambda: e.equiv(Z(0)))
|
589 |
+
|
590 |
+
assert e.equiv(3.14) is False
|
591 |
+
|
592 |
+
|
593 |
+
def test_ModuleElement_add():
|
594 |
+
T = Poly(cyclotomic_poly(5, x))
|
595 |
+
A = PowerBasis(T)
|
596 |
+
C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
|
597 |
+
e = A(to_col([1, 2, 3, 4]), denom=6)
|
598 |
+
f = A(to_col([5, 6, 7, 8]), denom=10)
|
599 |
+
g = C(to_col([1, 1, 1, 1]), denom=2)
|
600 |
+
assert e + f == A(to_col([10, 14, 18, 22]), denom=15)
|
601 |
+
assert e - f == A(to_col([-5, -4, -3, -2]), denom=15)
|
602 |
+
assert e + g == A(to_col([10, 11, 12, 13]), denom=6)
|
603 |
+
assert e + QQ(7, 10) == A(to_col([26, 10, 15, 20]), denom=30)
|
604 |
+
assert g + QQ(7, 10) == A(to_col([22, 15, 15, 15]), denom=10)
|
605 |
+
|
606 |
+
U = Poly(cyclotomic_poly(7, x))
|
607 |
+
Z = PowerBasis(U)
|
608 |
+
raises(TypeError, lambda: e + Z(0))
|
609 |
+
raises(TypeError, lambda: e + 3.14)
|
610 |
+
|
611 |
+
|
612 |
+
def test_ModuleElement_mul():
|
613 |
+
T = Poly(cyclotomic_poly(5, x))
|
614 |
+
A = PowerBasis(T)
|
615 |
+
C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
|
616 |
+
e = A(to_col([0, 2, 0, 0]), denom=3)
|
617 |
+
f = A(to_col([0, 0, 0, 7]), denom=5)
|
618 |
+
g = C(to_col([0, 0, 0, 1]), denom=2)
|
619 |
+
h = A(to_col([0, 0, 3, 1]), denom=7)
|
620 |
+
assert e * f == A(to_col([-14, -14, -14, -14]), denom=15)
|
621 |
+
assert e * g == A(to_col([-1, -1, -1, -1]))
|
622 |
+
assert e * h == A(to_col([-2, -2, -2, 4]), denom=21)
|
623 |
+
assert e * QQ(6, 5) == A(to_col([0, 4, 0, 0]), denom=5)
|
624 |
+
assert (g * QQ(10, 21)).equiv(A(to_col([0, 0, 0, 5]), denom=7))
|
625 |
+
assert e // QQ(6, 5) == A(to_col([0, 5, 0, 0]), denom=9)
|
626 |
+
|
627 |
+
U = Poly(cyclotomic_poly(7, x))
|
628 |
+
Z = PowerBasis(U)
|
629 |
+
raises(TypeError, lambda: e * Z(0))
|
630 |
+
raises(TypeError, lambda: e * 3.14)
|
631 |
+
raises(TypeError, lambda: e // 3.14)
|
632 |
+
raises(ZeroDivisionError, lambda: e // 0)
|
633 |
+
|
634 |
+
|
635 |
+
def test_ModuleElement_div():
|
636 |
+
T = Poly(cyclotomic_poly(5, x))
|
637 |
+
A = PowerBasis(T)
|
638 |
+
C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
|
639 |
+
e = A(to_col([0, 2, 0, 0]), denom=3)
|
640 |
+
f = A(to_col([0, 0, 0, 7]), denom=5)
|
641 |
+
g = C(to_col([1, 1, 1, 1]))
|
642 |
+
assert e // f == 10*A(3)//21
|
643 |
+
assert e // g == -2*A(2)//9
|
644 |
+
assert 3 // g == -A(1)
|
645 |
+
|
646 |
+
|
647 |
+
def test_ModuleElement_pow():
|
648 |
+
T = Poly(cyclotomic_poly(5, x))
|
649 |
+
A = PowerBasis(T)
|
650 |
+
C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
|
651 |
+
e = A(to_col([0, 2, 0, 0]), denom=3)
|
652 |
+
g = C(to_col([0, 0, 0, 1]), denom=2)
|
653 |
+
assert e ** 3 == A(to_col([0, 0, 0, 8]), denom=27)
|
654 |
+
assert g ** 2 == C(to_col([0, 3, 0, 0]), denom=4)
|
655 |
+
assert e ** 0 == A(to_col([1, 0, 0, 0]))
|
656 |
+
assert g ** 0 == A(to_col([1, 0, 0, 0]))
|
657 |
+
assert e ** 1 == e
|
658 |
+
assert g ** 1 == g
|
659 |
+
|
660 |
+
|
661 |
+
def test_ModuleElement_mod():
|
662 |
+
T = Poly(cyclotomic_poly(5, x))
|
663 |
+
A = PowerBasis(T)
|
664 |
+
e = A(to_col([1, 15, 8, 0]), denom=2)
|
665 |
+
assert e % 7 == A(to_col([1, 1, 8, 0]), denom=2)
|
666 |
+
assert e % QQ(1, 2) == A.zero()
|
667 |
+
assert e % QQ(1, 3) == A(to_col([1, 1, 0, 0]), denom=6)
|
668 |
+
|
669 |
+
B = A.submodule_from_gens([A(0), 5*A(1), 3*A(2), A(3)])
|
670 |
+
assert e % B == A(to_col([1, 5, 2, 0]), denom=2)
|
671 |
+
|
672 |
+
C = B.whole_submodule()
|
673 |
+
raises(TypeError, lambda: e % C)
|
674 |
+
|
675 |
+
|
676 |
+
def test_PowerBasisElement_polys():
|
677 |
+
T = Poly(cyclotomic_poly(5, x))
|
678 |
+
A = PowerBasis(T)
|
679 |
+
e = A(to_col([1, 15, 8, 0]), denom=2)
|
680 |
+
assert e.numerator(x=zeta) == Poly(8 * zeta ** 2 + 15 * zeta + 1, domain=ZZ)
|
681 |
+
assert e.poly(x=zeta) == Poly(4 * zeta ** 2 + QQ(15, 2) * zeta + QQ(1, 2), domain=QQ)
|
682 |
+
|
683 |
+
|
684 |
+
def test_PowerBasisElement_norm():
|
685 |
+
T = Poly(cyclotomic_poly(5, x))
|
686 |
+
A = PowerBasis(T)
|
687 |
+
lam = A(to_col([1, -1, 0, 0]))
|
688 |
+
assert lam.norm() == 5
|
689 |
+
|
690 |
+
|
691 |
+
def test_PowerBasisElement_inverse():
|
692 |
+
T = Poly(cyclotomic_poly(5, x))
|
693 |
+
A = PowerBasis(T)
|
694 |
+
e = A(to_col([1, 1, 1, 1]))
|
695 |
+
assert 2 // e == -2*A(1)
|
696 |
+
assert e ** -3 == -A(3)
|
697 |
+
|
698 |
+
|
699 |
+
def test_ModuleHomomorphism_matrix():
|
700 |
+
T = Poly(cyclotomic_poly(5, x))
|
701 |
+
A = PowerBasis(T)
|
702 |
+
phi = ModuleEndomorphism(A, lambda a: a ** 2)
|
703 |
+
M = phi.matrix()
|
704 |
+
assert M == DomainMatrix([
|
705 |
+
[1, 0, -1, 0],
|
706 |
+
[0, 0, -1, 1],
|
707 |
+
[0, 1, -1, 0],
|
708 |
+
[0, 0, -1, 0]
|
709 |
+
], (4, 4), ZZ)
|
710 |
+
|
711 |
+
|
712 |
+
def test_ModuleHomomorphism_kernel():
|
713 |
+
T = Poly(cyclotomic_poly(5, x))
|
714 |
+
A = PowerBasis(T)
|
715 |
+
phi = ModuleEndomorphism(A, lambda a: a ** 5)
|
716 |
+
N = phi.kernel()
|
717 |
+
assert N.n == 3
|
718 |
+
|
719 |
+
|
720 |
+
def test_EndomorphismRing_represent():
|
721 |
+
T = Poly(cyclotomic_poly(5, x))
|
722 |
+
A = PowerBasis(T)
|
723 |
+
R = A.endomorphism_ring()
|
724 |
+
phi = R.inner_endomorphism(A(1))
|
725 |
+
col = R.represent(phi)
|
726 |
+
assert col.transpose() == DomainMatrix([
|
727 |
+
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1]
|
728 |
+
], (1, 16), ZZ)
|
729 |
+
|
730 |
+
B = A.submodule_from_matrix(DomainMatrix.zeros((4, 0), ZZ))
|
731 |
+
S = B.endomorphism_ring()
|
732 |
+
psi = S.inner_endomorphism(A(1))
|
733 |
+
col = S.represent(psi)
|
734 |
+
assert col == DomainMatrix([], (0, 0), ZZ)
|
735 |
+
|
736 |
+
raises(NotImplementedError, lambda: R.represent(3.14))
|
737 |
+
|
738 |
+
|
739 |
+
def test_find_min_poly():
|
740 |
+
T = Poly(cyclotomic_poly(5, x))
|
741 |
+
A = PowerBasis(T)
|
742 |
+
powers = []
|
743 |
+
m = find_min_poly(A(1), QQ, x=x, powers=powers)
|
744 |
+
assert m == Poly(T, domain=QQ)
|
745 |
+
assert len(powers) == 5
|
746 |
+
|
747 |
+
# powers list need not be passed
|
748 |
+
m = find_min_poly(A(1), QQ, x=x)
|
749 |
+
assert m == Poly(T, domain=QQ)
|
750 |
+
|
751 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
752 |
+
raises(MissingUnityError, lambda: find_min_poly(B(1), QQ))
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_primes.py
ADDED
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from math import prod
|
2 |
+
|
3 |
+
from sympy import QQ, ZZ
|
4 |
+
from sympy.abc import x, theta
|
5 |
+
from sympy.ntheory import factorint
|
6 |
+
from sympy.ntheory.residue_ntheory import n_order
|
7 |
+
from sympy.polys import Poly, cyclotomic_poly
|
8 |
+
from sympy.polys.matrices import DomainMatrix
|
9 |
+
from sympy.polys.numberfields.basis import round_two
|
10 |
+
from sympy.polys.numberfields.exceptions import StructureError
|
11 |
+
from sympy.polys.numberfields.modules import PowerBasis, to_col
|
12 |
+
from sympy.polys.numberfields.primes import (
|
13 |
+
prime_decomp, _two_elt_rep,
|
14 |
+
_check_formal_conditions_for_maximal_order,
|
15 |
+
)
|
16 |
+
from sympy.testing.pytest import raises
|
17 |
+
|
18 |
+
|
19 |
+
def test_check_formal_conditions_for_maximal_order():
|
20 |
+
T = Poly(cyclotomic_poly(5, x))
|
21 |
+
A = PowerBasis(T)
|
22 |
+
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
|
23 |
+
C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
|
24 |
+
D = A.submodule_from_matrix(DomainMatrix.eye(4, ZZ)[:, :-1])
|
25 |
+
# Is a direct submodule of a power basis, but lacks 1 as first generator:
|
26 |
+
raises(StructureError, lambda: _check_formal_conditions_for_maximal_order(B))
|
27 |
+
# Is not a direct submodule of a power basis:
|
28 |
+
raises(StructureError, lambda: _check_formal_conditions_for_maximal_order(C))
|
29 |
+
# Is direct submod of pow basis, and starts with 1, but not sq/max rank/HNF:
|
30 |
+
raises(StructureError, lambda: _check_formal_conditions_for_maximal_order(D))
|
31 |
+
|
32 |
+
|
33 |
+
def test_two_elt_rep():
|
34 |
+
ell = 7
|
35 |
+
T = Poly(cyclotomic_poly(ell))
|
36 |
+
ZK, dK = round_two(T)
|
37 |
+
for p in [29, 13, 11, 5]:
|
38 |
+
P = prime_decomp(p, T)
|
39 |
+
for Pi in P:
|
40 |
+
# We have Pi in two-element representation, and, because we are
|
41 |
+
# looking at a cyclotomic field, this was computed by the "easy"
|
42 |
+
# method that just factors T mod p. We will now convert this to
|
43 |
+
# a set of Z-generators, then convert that back into a two-element
|
44 |
+
# rep. The latter need not be identical to the two-elt rep we
|
45 |
+
# already have, but it must have the same HNF.
|
46 |
+
H = p*ZK + Pi.alpha*ZK
|
47 |
+
gens = H.basis_element_pullbacks()
|
48 |
+
# Note: we could supply f = Pi.f, but prefer to test behavior without it.
|
49 |
+
b = _two_elt_rep(gens, ZK, p)
|
50 |
+
if b != Pi.alpha:
|
51 |
+
H2 = p*ZK + b*ZK
|
52 |
+
assert H2 == H
|
53 |
+
|
54 |
+
|
55 |
+
def test_valuation_at_prime_ideal():
|
56 |
+
p = 7
|
57 |
+
T = Poly(cyclotomic_poly(p))
|
58 |
+
ZK, dK = round_two(T)
|
59 |
+
P = prime_decomp(p, T, dK=dK, ZK=ZK)
|
60 |
+
assert len(P) == 1
|
61 |
+
P0 = P[0]
|
62 |
+
v = P0.valuation(p*ZK)
|
63 |
+
assert v == P0.e
|
64 |
+
# Test easy 0 case:
|
65 |
+
assert P0.valuation(5*ZK) == 0
|
66 |
+
|
67 |
+
|
68 |
+
def test_decomp_1():
|
69 |
+
# All prime decompositions in cyclotomic fields are in the "easy case,"
|
70 |
+
# since the index is unity.
|
71 |
+
# Here we check the ramified prime.
|
72 |
+
T = Poly(cyclotomic_poly(7))
|
73 |
+
raises(ValueError, lambda: prime_decomp(7))
|
74 |
+
P = prime_decomp(7, T)
|
75 |
+
assert len(P) == 1
|
76 |
+
P0 = P[0]
|
77 |
+
assert P0.e == 6
|
78 |
+
assert P0.f == 1
|
79 |
+
# Test powers:
|
80 |
+
assert P0**0 == P0.ZK
|
81 |
+
assert P0**1 == P0
|
82 |
+
assert P0**6 == 7 * P0.ZK
|
83 |
+
|
84 |
+
|
85 |
+
def test_decomp_2():
|
86 |
+
# More easy cyclotomic cases, but here we check unramified primes.
|
87 |
+
ell = 7
|
88 |
+
T = Poly(cyclotomic_poly(ell))
|
89 |
+
for p in [29, 13, 11, 5]:
|
90 |
+
f_exp = n_order(p, ell)
|
91 |
+
g_exp = (ell - 1) // f_exp
|
92 |
+
P = prime_decomp(p, T)
|
93 |
+
assert len(P) == g_exp
|
94 |
+
for Pi in P:
|
95 |
+
assert Pi.e == 1
|
96 |
+
assert Pi.f == f_exp
|
97 |
+
|
98 |
+
|
99 |
+
def test_decomp_3():
|
100 |
+
T = Poly(x ** 2 - 35)
|
101 |
+
rad = {}
|
102 |
+
ZK, dK = round_two(T, radicals=rad)
|
103 |
+
# 35 is 3 mod 4, so field disc is 4*5*7, and theory says each of the
|
104 |
+
# rational primes 2, 5, 7 should be the square of a prime ideal.
|
105 |
+
for p in [2, 5, 7]:
|
106 |
+
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p))
|
107 |
+
assert len(P) == 1
|
108 |
+
assert P[0].e == 2
|
109 |
+
assert P[0]**2 == p*ZK
|
110 |
+
|
111 |
+
|
112 |
+
def test_decomp_4():
|
113 |
+
T = Poly(x ** 2 - 21)
|
114 |
+
rad = {}
|
115 |
+
ZK, dK = round_two(T, radicals=rad)
|
116 |
+
# 21 is 1 mod 4, so field disc is 3*7, and theory says the
|
117 |
+
# rational primes 3, 7 should be the square of a prime ideal.
|
118 |
+
for p in [3, 7]:
|
119 |
+
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p))
|
120 |
+
assert len(P) == 1
|
121 |
+
assert P[0].e == 2
|
122 |
+
assert P[0]**2 == p*ZK
|
123 |
+
|
124 |
+
|
125 |
+
def test_decomp_5():
|
126 |
+
# Here is our first test of the "hard case" of prime decomposition.
|
127 |
+
# We work in a quadratic extension Q(sqrt(d)) where d is 1 mod 4, and
|
128 |
+
# we consider the factorization of the rational prime 2, which divides
|
129 |
+
# the index.
|
130 |
+
# Theory says the form of p's factorization depends on the residue of
|
131 |
+
# d mod 8, so we consider both cases, d = 1 mod 8 and d = 5 mod 8.
|
132 |
+
for d in [-7, -3]:
|
133 |
+
T = Poly(x ** 2 - d)
|
134 |
+
rad = {}
|
135 |
+
ZK, dK = round_two(T, radicals=rad)
|
136 |
+
p = 2
|
137 |
+
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p))
|
138 |
+
if d % 8 == 1:
|
139 |
+
assert len(P) == 2
|
140 |
+
assert all(P[i].e == 1 and P[i].f == 1 for i in range(2))
|
141 |
+
assert prod(Pi**Pi.e for Pi in P) == p * ZK
|
142 |
+
else:
|
143 |
+
assert d % 8 == 5
|
144 |
+
assert len(P) == 1
|
145 |
+
assert P[0].e == 1
|
146 |
+
assert P[0].f == 2
|
147 |
+
assert P[0].as_submodule() == p * ZK
|
148 |
+
|
149 |
+
|
150 |
+
def test_decomp_6():
|
151 |
+
# Another case where 2 divides the index. This is Dedekind's example of
|
152 |
+
# an essential discriminant divisor. (See Cohen, Exercise 6.10.)
|
153 |
+
T = Poly(x ** 3 + x ** 2 - 2 * x + 8)
|
154 |
+
rad = {}
|
155 |
+
ZK, dK = round_two(T, radicals=rad)
|
156 |
+
p = 2
|
157 |
+
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p))
|
158 |
+
assert len(P) == 3
|
159 |
+
assert all(Pi.e == Pi.f == 1 for Pi in P)
|
160 |
+
assert prod(Pi**Pi.e for Pi in P) == p*ZK
|
161 |
+
|
162 |
+
|
163 |
+
def test_decomp_7():
|
164 |
+
# Try working through an AlgebraicField
|
165 |
+
T = Poly(x ** 3 + x ** 2 - 2 * x + 8)
|
166 |
+
K = QQ.alg_field_from_poly(T)
|
167 |
+
p = 2
|
168 |
+
P = K.primes_above(p)
|
169 |
+
ZK = K.maximal_order()
|
170 |
+
assert len(P) == 3
|
171 |
+
assert all(Pi.e == Pi.f == 1 for Pi in P)
|
172 |
+
assert prod(Pi**Pi.e for Pi in P) == p*ZK
|
173 |
+
|
174 |
+
|
175 |
+
def test_decomp_8():
|
176 |
+
# This time we consider various cubics, and try factoring all primes
|
177 |
+
# dividing the index.
|
178 |
+
cases = (
|
179 |
+
x ** 3 + 3 * x ** 2 - 4 * x + 4,
|
180 |
+
x ** 3 + 3 * x ** 2 + 3 * x - 3,
|
181 |
+
x ** 3 + 5 * x ** 2 - x + 3,
|
182 |
+
x ** 3 + 5 * x ** 2 - 5 * x - 5,
|
183 |
+
x ** 3 + 3 * x ** 2 + 5,
|
184 |
+
x ** 3 + 6 * x ** 2 + 3 * x - 1,
|
185 |
+
x ** 3 + 6 * x ** 2 + 4,
|
186 |
+
x ** 3 + 7 * x ** 2 + 7 * x - 7,
|
187 |
+
x ** 3 + 7 * x ** 2 - x + 5,
|
188 |
+
x ** 3 + 7 * x ** 2 - 5 * x + 5,
|
189 |
+
x ** 3 + 4 * x ** 2 - 3 * x + 7,
|
190 |
+
x ** 3 + 8 * x ** 2 + 5 * x - 1,
|
191 |
+
x ** 3 + 8 * x ** 2 - 2 * x + 6,
|
192 |
+
x ** 3 + 6 * x ** 2 - 3 * x + 8,
|
193 |
+
x ** 3 + 9 * x ** 2 + 6 * x - 8,
|
194 |
+
x ** 3 + 15 * x ** 2 - 9 * x + 13,
|
195 |
+
)
|
196 |
+
def display(T, p, radical, P, I, J):
|
197 |
+
"""Useful for inspection, when running test manually."""
|
198 |
+
print('=' * 20)
|
199 |
+
print(T, p, radical)
|
200 |
+
for Pi in P:
|
201 |
+
print(f' ({Pi!r})')
|
202 |
+
print("I: ", I)
|
203 |
+
print("J: ", J)
|
204 |
+
print(f'Equal: {I == J}')
|
205 |
+
inspect = False
|
206 |
+
for g in cases:
|
207 |
+
T = Poly(g)
|
208 |
+
rad = {}
|
209 |
+
ZK, dK = round_two(T, radicals=rad)
|
210 |
+
dT = T.discriminant()
|
211 |
+
f_squared = dT // dK
|
212 |
+
F = factorint(f_squared)
|
213 |
+
for p in F:
|
214 |
+
radical = rad.get(p)
|
215 |
+
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=radical)
|
216 |
+
I = prod(Pi**Pi.e for Pi in P)
|
217 |
+
J = p * ZK
|
218 |
+
if inspect:
|
219 |
+
display(T, p, radical, P, I, J)
|
220 |
+
assert I == J
|
221 |
+
|
222 |
+
|
223 |
+
def test_PrimeIdeal_eq():
|
224 |
+
# `==` should fail on objects of different types, so even a completely
|
225 |
+
# inert PrimeIdeal should test unequal to the rational prime it divides.
|
226 |
+
T = Poly(cyclotomic_poly(7))
|
227 |
+
P0 = prime_decomp(5, T)[0]
|
228 |
+
assert P0.f == 6
|
229 |
+
assert P0.as_submodule() == 5 * P0.ZK
|
230 |
+
assert P0 != 5
|
231 |
+
|
232 |
+
|
233 |
+
def test_PrimeIdeal_add():
|
234 |
+
T = Poly(cyclotomic_poly(7))
|
235 |
+
P0 = prime_decomp(7, T)[0]
|
236 |
+
# Adding ideals computes their GCD, so adding the ramified prime dividing
|
237 |
+
# 7 to 7 itself should reproduce this prime (as a submodule).
|
238 |
+
assert P0 + 7 * P0.ZK == P0.as_submodule()
|
239 |
+
|
240 |
+
|
241 |
+
def test_str():
|
242 |
+
# Without alias:
|
243 |
+
k = QQ.alg_field_from_poly(Poly(x**2 + 7))
|
244 |
+
frp = k.primes_above(2)[0]
|
245 |
+
assert str(frp) == '(2, 3*_x/2 + 1/2)'
|
246 |
+
|
247 |
+
frp = k.primes_above(3)[0]
|
248 |
+
assert str(frp) == '(3)'
|
249 |
+
|
250 |
+
# With alias:
|
251 |
+
k = QQ.alg_field_from_poly(Poly(x ** 2 + 7), alias='alpha')
|
252 |
+
frp = k.primes_above(2)[0]
|
253 |
+
assert str(frp) == '(2, 3*alpha/2 + 1/2)'
|
254 |
+
|
255 |
+
frp = k.primes_above(3)[0]
|
256 |
+
assert str(frp) == '(3)'
|
257 |
+
|
258 |
+
|
259 |
+
def test_repr():
|
260 |
+
T = Poly(x**2 + 7)
|
261 |
+
ZK, dK = round_two(T)
|
262 |
+
P = prime_decomp(2, T, dK=dK, ZK=ZK)
|
263 |
+
assert repr(P[0]) == '[ (2, (3*x + 1)/2) e=1, f=1 ]'
|
264 |
+
assert P[0].repr(field_gen=theta) == '[ (2, (3*theta + 1)/2) e=1, f=1 ]'
|
265 |
+
assert P[0].repr(field_gen=theta, just_gens=True) == '(2, (3*theta + 1)/2)'
|
266 |
+
|
267 |
+
|
268 |
+
def test_PrimeIdeal_reduce():
|
269 |
+
k = QQ.alg_field_from_poly(Poly(x ** 3 + x ** 2 - 2 * x + 8))
|
270 |
+
Zk = k.maximal_order()
|
271 |
+
P = k.primes_above(2)
|
272 |
+
frp = P[2]
|
273 |
+
|
274 |
+
# reduce_element
|
275 |
+
a = Zk.parent(to_col([23, 20, 11]), denom=6)
|
276 |
+
a_bar_expected = Zk.parent(to_col([11, 5, 2]), denom=6)
|
277 |
+
a_bar = frp.reduce_element(a)
|
278 |
+
assert a_bar == a_bar_expected
|
279 |
+
|
280 |
+
# reduce_ANP
|
281 |
+
a = k([QQ(11, 6), QQ(20, 6), QQ(23, 6)])
|
282 |
+
a_bar_expected = k([QQ(2, 6), QQ(5, 6), QQ(11, 6)])
|
283 |
+
a_bar = frp.reduce_ANP(a)
|
284 |
+
assert a_bar == a_bar_expected
|
285 |
+
|
286 |
+
# reduce_alg_num
|
287 |
+
a = k.to_alg_num(a)
|
288 |
+
a_bar_expected = k.to_alg_num(a_bar_expected)
|
289 |
+
a_bar = frp.reduce_alg_num(a)
|
290 |
+
assert a_bar == a_bar_expected
|
291 |
+
|
292 |
+
|
293 |
+
def test_issue_23402():
|
294 |
+
k = QQ.alg_field_from_poly(Poly(x ** 3 + x ** 2 - 2 * x + 8))
|
295 |
+
P = k.primes_above(3)
|
296 |
+
assert P[0].alpha.equiv(0)
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_subfield.py
ADDED
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tests for the subfield problem and allied problems. """
|
2 |
+
|
3 |
+
from sympy.core.numbers import (AlgebraicNumber, I, pi, Rational)
|
4 |
+
from sympy.core.singleton import S
|
5 |
+
from sympy.functions.elementary.exponential import exp
|
6 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
7 |
+
from sympy.external.gmpy import MPQ
|
8 |
+
from sympy.polys.numberfields.subfield import (
|
9 |
+
is_isomorphism_possible,
|
10 |
+
field_isomorphism_pslq,
|
11 |
+
field_isomorphism,
|
12 |
+
primitive_element,
|
13 |
+
to_number_field,
|
14 |
+
)
|
15 |
+
from sympy.polys.polyerrors import IsomorphismFailed
|
16 |
+
from sympy.polys.polytools import Poly
|
17 |
+
from sympy.polys.rootoftools import CRootOf
|
18 |
+
from sympy.testing.pytest import raises
|
19 |
+
|
20 |
+
from sympy.abc import x
|
21 |
+
|
22 |
+
Q = Rational
|
23 |
+
|
24 |
+
|
25 |
+
def test_field_isomorphism_pslq():
|
26 |
+
a = AlgebraicNumber(I)
|
27 |
+
b = AlgebraicNumber(I*sqrt(3))
|
28 |
+
|
29 |
+
raises(NotImplementedError, lambda: field_isomorphism_pslq(a, b))
|
30 |
+
|
31 |
+
a = AlgebraicNumber(sqrt(2))
|
32 |
+
b = AlgebraicNumber(sqrt(3))
|
33 |
+
c = AlgebraicNumber(sqrt(7))
|
34 |
+
d = AlgebraicNumber(sqrt(2) + sqrt(3))
|
35 |
+
e = AlgebraicNumber(sqrt(2) + sqrt(3) + sqrt(7))
|
36 |
+
|
37 |
+
assert field_isomorphism_pslq(a, a) == [1, 0]
|
38 |
+
assert field_isomorphism_pslq(a, b) is None
|
39 |
+
assert field_isomorphism_pslq(a, c) is None
|
40 |
+
assert field_isomorphism_pslq(a, d) == [Q(1, 2), 0, -Q(9, 2), 0]
|
41 |
+
assert field_isomorphism_pslq(
|
42 |
+
a, e) == [Q(1, 80), 0, -Q(1, 2), 0, Q(59, 20), 0]
|
43 |
+
|
44 |
+
assert field_isomorphism_pslq(b, a) is None
|
45 |
+
assert field_isomorphism_pslq(b, b) == [1, 0]
|
46 |
+
assert field_isomorphism_pslq(b, c) is None
|
47 |
+
assert field_isomorphism_pslq(b, d) == [-Q(1, 2), 0, Q(11, 2), 0]
|
48 |
+
assert field_isomorphism_pslq(b, e) == [-Q(
|
49 |
+
3, 640), 0, Q(67, 320), 0, -Q(297, 160), 0, Q(313, 80), 0]
|
50 |
+
|
51 |
+
assert field_isomorphism_pslq(c, a) is None
|
52 |
+
assert field_isomorphism_pslq(c, b) is None
|
53 |
+
assert field_isomorphism_pslq(c, c) == [1, 0]
|
54 |
+
assert field_isomorphism_pslq(c, d) is None
|
55 |
+
assert field_isomorphism_pslq(c, e) == [Q(
|
56 |
+
3, 640), 0, -Q(71, 320), 0, Q(377, 160), 0, -Q(469, 80), 0]
|
57 |
+
|
58 |
+
assert field_isomorphism_pslq(d, a) is None
|
59 |
+
assert field_isomorphism_pslq(d, b) is None
|
60 |
+
assert field_isomorphism_pslq(d, c) is None
|
61 |
+
assert field_isomorphism_pslq(d, d) == [1, 0]
|
62 |
+
assert field_isomorphism_pslq(d, e) == [-Q(
|
63 |
+
3, 640), 0, Q(71, 320), 0, -Q(377, 160), 0, Q(549, 80), 0]
|
64 |
+
|
65 |
+
assert field_isomorphism_pslq(e, a) is None
|
66 |
+
assert field_isomorphism_pslq(e, b) is None
|
67 |
+
assert field_isomorphism_pslq(e, c) is None
|
68 |
+
assert field_isomorphism_pslq(e, d) is None
|
69 |
+
assert field_isomorphism_pslq(e, e) == [1, 0]
|
70 |
+
|
71 |
+
f = AlgebraicNumber(3*sqrt(2) + 8*sqrt(7) - 5)
|
72 |
+
|
73 |
+
assert field_isomorphism_pslq(
|
74 |
+
f, e) == [Q(3, 80), 0, -Q(139, 80), 0, Q(347, 20), 0, -Q(761, 20), -5]
|
75 |
+
|
76 |
+
|
77 |
+
def test_field_isomorphism():
|
78 |
+
assert field_isomorphism(3, sqrt(2)) == [3]
|
79 |
+
|
80 |
+
assert field_isomorphism( I*sqrt(3), I*sqrt(3)/2) == [ 2, 0]
|
81 |
+
assert field_isomorphism(-I*sqrt(3), I*sqrt(3)/2) == [-2, 0]
|
82 |
+
|
83 |
+
assert field_isomorphism( I*sqrt(3), -I*sqrt(3)/2) == [-2, 0]
|
84 |
+
assert field_isomorphism(-I*sqrt(3), -I*sqrt(3)/2) == [ 2, 0]
|
85 |
+
|
86 |
+
assert field_isomorphism( 2*I*sqrt(3)/7, 5*I*sqrt(3)/3) == [ Rational(6, 35), 0]
|
87 |
+
assert field_isomorphism(-2*I*sqrt(3)/7, 5*I*sqrt(3)/3) == [Rational(-6, 35), 0]
|
88 |
+
|
89 |
+
assert field_isomorphism( 2*I*sqrt(3)/7, -5*I*sqrt(3)/3) == [Rational(-6, 35), 0]
|
90 |
+
assert field_isomorphism(-2*I*sqrt(3)/7, -5*I*sqrt(3)/3) == [ Rational(6, 35), 0]
|
91 |
+
|
92 |
+
assert field_isomorphism(
|
93 |
+
2*I*sqrt(3)/7 + 27, 5*I*sqrt(3)/3) == [ Rational(6, 35), 27]
|
94 |
+
assert field_isomorphism(
|
95 |
+
-2*I*sqrt(3)/7 + 27, 5*I*sqrt(3)/3) == [Rational(-6, 35), 27]
|
96 |
+
|
97 |
+
assert field_isomorphism(
|
98 |
+
2*I*sqrt(3)/7 + 27, -5*I*sqrt(3)/3) == [Rational(-6, 35), 27]
|
99 |
+
assert field_isomorphism(
|
100 |
+
-2*I*sqrt(3)/7 + 27, -5*I*sqrt(3)/3) == [ Rational(6, 35), 27]
|
101 |
+
|
102 |
+
p = AlgebraicNumber( sqrt(2) + sqrt(3))
|
103 |
+
q = AlgebraicNumber(-sqrt(2) + sqrt(3))
|
104 |
+
r = AlgebraicNumber( sqrt(2) - sqrt(3))
|
105 |
+
s = AlgebraicNumber(-sqrt(2) - sqrt(3))
|
106 |
+
|
107 |
+
pos_coeffs = [ S.Half, S.Zero, Rational(-9, 2), S.Zero]
|
108 |
+
neg_coeffs = [Rational(-1, 2), S.Zero, Rational(9, 2), S.Zero]
|
109 |
+
|
110 |
+
a = AlgebraicNumber(sqrt(2))
|
111 |
+
|
112 |
+
assert is_isomorphism_possible(a, p) is True
|
113 |
+
assert is_isomorphism_possible(a, q) is True
|
114 |
+
assert is_isomorphism_possible(a, r) is True
|
115 |
+
assert is_isomorphism_possible(a, s) is True
|
116 |
+
|
117 |
+
assert field_isomorphism(a, p, fast=True) == pos_coeffs
|
118 |
+
assert field_isomorphism(a, q, fast=True) == neg_coeffs
|
119 |
+
assert field_isomorphism(a, r, fast=True) == pos_coeffs
|
120 |
+
assert field_isomorphism(a, s, fast=True) == neg_coeffs
|
121 |
+
|
122 |
+
assert field_isomorphism(a, p, fast=False) == pos_coeffs
|
123 |
+
assert field_isomorphism(a, q, fast=False) == neg_coeffs
|
124 |
+
assert field_isomorphism(a, r, fast=False) == pos_coeffs
|
125 |
+
assert field_isomorphism(a, s, fast=False) == neg_coeffs
|
126 |
+
|
127 |
+
a = AlgebraicNumber(-sqrt(2))
|
128 |
+
|
129 |
+
assert is_isomorphism_possible(a, p) is True
|
130 |
+
assert is_isomorphism_possible(a, q) is True
|
131 |
+
assert is_isomorphism_possible(a, r) is True
|
132 |
+
assert is_isomorphism_possible(a, s) is True
|
133 |
+
|
134 |
+
assert field_isomorphism(a, p, fast=True) == neg_coeffs
|
135 |
+
assert field_isomorphism(a, q, fast=True) == pos_coeffs
|
136 |
+
assert field_isomorphism(a, r, fast=True) == neg_coeffs
|
137 |
+
assert field_isomorphism(a, s, fast=True) == pos_coeffs
|
138 |
+
|
139 |
+
assert field_isomorphism(a, p, fast=False) == neg_coeffs
|
140 |
+
assert field_isomorphism(a, q, fast=False) == pos_coeffs
|
141 |
+
assert field_isomorphism(a, r, fast=False) == neg_coeffs
|
142 |
+
assert field_isomorphism(a, s, fast=False) == pos_coeffs
|
143 |
+
|
144 |
+
pos_coeffs = [ S.Half, S.Zero, Rational(-11, 2), S.Zero]
|
145 |
+
neg_coeffs = [Rational(-1, 2), S.Zero, Rational(11, 2), S.Zero]
|
146 |
+
|
147 |
+
a = AlgebraicNumber(sqrt(3))
|
148 |
+
|
149 |
+
assert is_isomorphism_possible(a, p) is True
|
150 |
+
assert is_isomorphism_possible(a, q) is True
|
151 |
+
assert is_isomorphism_possible(a, r) is True
|
152 |
+
assert is_isomorphism_possible(a, s) is True
|
153 |
+
|
154 |
+
assert field_isomorphism(a, p, fast=True) == neg_coeffs
|
155 |
+
assert field_isomorphism(a, q, fast=True) == neg_coeffs
|
156 |
+
assert field_isomorphism(a, r, fast=True) == pos_coeffs
|
157 |
+
assert field_isomorphism(a, s, fast=True) == pos_coeffs
|
158 |
+
|
159 |
+
assert field_isomorphism(a, p, fast=False) == neg_coeffs
|
160 |
+
assert field_isomorphism(a, q, fast=False) == neg_coeffs
|
161 |
+
assert field_isomorphism(a, r, fast=False) == pos_coeffs
|
162 |
+
assert field_isomorphism(a, s, fast=False) == pos_coeffs
|
163 |
+
|
164 |
+
a = AlgebraicNumber(-sqrt(3))
|
165 |
+
|
166 |
+
assert is_isomorphism_possible(a, p) is True
|
167 |
+
assert is_isomorphism_possible(a, q) is True
|
168 |
+
assert is_isomorphism_possible(a, r) is True
|
169 |
+
assert is_isomorphism_possible(a, s) is True
|
170 |
+
|
171 |
+
assert field_isomorphism(a, p, fast=True) == pos_coeffs
|
172 |
+
assert field_isomorphism(a, q, fast=True) == pos_coeffs
|
173 |
+
assert field_isomorphism(a, r, fast=True) == neg_coeffs
|
174 |
+
assert field_isomorphism(a, s, fast=True) == neg_coeffs
|
175 |
+
|
176 |
+
assert field_isomorphism(a, p, fast=False) == pos_coeffs
|
177 |
+
assert field_isomorphism(a, q, fast=False) == pos_coeffs
|
178 |
+
assert field_isomorphism(a, r, fast=False) == neg_coeffs
|
179 |
+
assert field_isomorphism(a, s, fast=False) == neg_coeffs
|
180 |
+
|
181 |
+
pos_coeffs = [ Rational(3, 2), S.Zero, Rational(-33, 2), -S(8)]
|
182 |
+
neg_coeffs = [Rational(-3, 2), S.Zero, Rational(33, 2), -S(8)]
|
183 |
+
|
184 |
+
a = AlgebraicNumber(3*sqrt(3) - 8)
|
185 |
+
|
186 |
+
assert is_isomorphism_possible(a, p) is True
|
187 |
+
assert is_isomorphism_possible(a, q) is True
|
188 |
+
assert is_isomorphism_possible(a, r) is True
|
189 |
+
assert is_isomorphism_possible(a, s) is True
|
190 |
+
|
191 |
+
assert field_isomorphism(a, p, fast=True) == neg_coeffs
|
192 |
+
assert field_isomorphism(a, q, fast=True) == neg_coeffs
|
193 |
+
assert field_isomorphism(a, r, fast=True) == pos_coeffs
|
194 |
+
assert field_isomorphism(a, s, fast=True) == pos_coeffs
|
195 |
+
|
196 |
+
assert field_isomorphism(a, p, fast=False) == neg_coeffs
|
197 |
+
assert field_isomorphism(a, q, fast=False) == neg_coeffs
|
198 |
+
assert field_isomorphism(a, r, fast=False) == pos_coeffs
|
199 |
+
assert field_isomorphism(a, s, fast=False) == pos_coeffs
|
200 |
+
|
201 |
+
a = AlgebraicNumber(3*sqrt(2) + 2*sqrt(3) + 1)
|
202 |
+
|
203 |
+
pos_1_coeffs = [ S.Half, S.Zero, Rational(-5, 2), S.One]
|
204 |
+
neg_5_coeffs = [Rational(-5, 2), S.Zero, Rational(49, 2), S.One]
|
205 |
+
pos_5_coeffs = [ Rational(5, 2), S.Zero, Rational(-49, 2), S.One]
|
206 |
+
neg_1_coeffs = [Rational(-1, 2), S.Zero, Rational(5, 2), S.One]
|
207 |
+
|
208 |
+
assert is_isomorphism_possible(a, p) is True
|
209 |
+
assert is_isomorphism_possible(a, q) is True
|
210 |
+
assert is_isomorphism_possible(a, r) is True
|
211 |
+
assert is_isomorphism_possible(a, s) is True
|
212 |
+
|
213 |
+
assert field_isomorphism(a, p, fast=True) == pos_1_coeffs
|
214 |
+
assert field_isomorphism(a, q, fast=True) == neg_5_coeffs
|
215 |
+
assert field_isomorphism(a, r, fast=True) == pos_5_coeffs
|
216 |
+
assert field_isomorphism(a, s, fast=True) == neg_1_coeffs
|
217 |
+
|
218 |
+
assert field_isomorphism(a, p, fast=False) == pos_1_coeffs
|
219 |
+
assert field_isomorphism(a, q, fast=False) == neg_5_coeffs
|
220 |
+
assert field_isomorphism(a, r, fast=False) == pos_5_coeffs
|
221 |
+
assert field_isomorphism(a, s, fast=False) == neg_1_coeffs
|
222 |
+
|
223 |
+
a = AlgebraicNumber(sqrt(2))
|
224 |
+
b = AlgebraicNumber(sqrt(3))
|
225 |
+
c = AlgebraicNumber(sqrt(7))
|
226 |
+
|
227 |
+
assert is_isomorphism_possible(a, b) is True
|
228 |
+
assert is_isomorphism_possible(b, a) is True
|
229 |
+
|
230 |
+
assert is_isomorphism_possible(c, p) is False
|
231 |
+
|
232 |
+
assert field_isomorphism(sqrt(2), sqrt(3), fast=True) is None
|
233 |
+
assert field_isomorphism(sqrt(3), sqrt(2), fast=True) is None
|
234 |
+
|
235 |
+
assert field_isomorphism(sqrt(2), sqrt(3), fast=False) is None
|
236 |
+
assert field_isomorphism(sqrt(3), sqrt(2), fast=False) is None
|
237 |
+
|
238 |
+
a = AlgebraicNumber(sqrt(2))
|
239 |
+
b = AlgebraicNumber(2 ** (S(1) / 3))
|
240 |
+
|
241 |
+
assert is_isomorphism_possible(a, b) is False
|
242 |
+
assert field_isomorphism(a, b) is None
|
243 |
+
|
244 |
+
|
245 |
+
def test_primitive_element():
|
246 |
+
assert primitive_element([sqrt(2)], x) == (x**2 - 2, [1])
|
247 |
+
assert primitive_element(
|
248 |
+
[sqrt(2), sqrt(3)], x) == (x**4 - 10*x**2 + 1, [1, 1])
|
249 |
+
|
250 |
+
assert primitive_element([sqrt(2)], x, polys=True) == (Poly(x**2 - 2, domain='QQ'), [1])
|
251 |
+
assert primitive_element([sqrt(
|
252 |
+
2), sqrt(3)], x, polys=True) == (Poly(x**4 - 10*x**2 + 1, domain='QQ'), [1, 1])
|
253 |
+
|
254 |
+
assert primitive_element(
|
255 |
+
[sqrt(2)], x, ex=True) == (x**2 - 2, [1], [[1, 0]])
|
256 |
+
assert primitive_element([sqrt(2), sqrt(3)], x, ex=True) == \
|
257 |
+
(x**4 - 10*x**2 + 1, [1, 1], [[Q(1, 2), 0, -Q(9, 2), 0], [-
|
258 |
+
Q(1, 2), 0, Q(11, 2), 0]])
|
259 |
+
|
260 |
+
assert primitive_element(
|
261 |
+
[sqrt(2)], x, ex=True, polys=True) == (Poly(x**2 - 2, domain='QQ'), [1], [[1, 0]])
|
262 |
+
assert primitive_element([sqrt(2), sqrt(3)], x, ex=True, polys=True) == \
|
263 |
+
(Poly(x**4 - 10*x**2 + 1, domain='QQ'), [1, 1], [[Q(1, 2), 0, -Q(9, 2),
|
264 |
+
0], [-Q(1, 2), 0, Q(11, 2), 0]])
|
265 |
+
|
266 |
+
assert primitive_element([sqrt(2)], polys=True) == (Poly(x**2 - 2), [1])
|
267 |
+
|
268 |
+
raises(ValueError, lambda: primitive_element([], x, ex=False))
|
269 |
+
raises(ValueError, lambda: primitive_element([], x, ex=True))
|
270 |
+
|
271 |
+
# Issue 14117
|
272 |
+
a, b = I*sqrt(2*sqrt(2) + 3), I*sqrt(-2*sqrt(2) + 3)
|
273 |
+
assert primitive_element([a, b, I], x) == (x**4 + 6*x**2 + 1, [1, 0, 0])
|
274 |
+
|
275 |
+
assert primitive_element([sqrt(2), 0], x) == (x**2 - 2, [1, 0])
|
276 |
+
assert primitive_element([0, sqrt(2)], x) == (x**2 - 2, [1, 1])
|
277 |
+
assert primitive_element([sqrt(2), 0], x, ex=True) == (x**2 - 2, [1, 0], [[MPQ(1,1), MPQ(0,1)], []])
|
278 |
+
assert primitive_element([0, sqrt(2)], x, ex=True) == (x**2 - 2, [1, 1], [[], [MPQ(1,1), MPQ(0,1)]])
|
279 |
+
|
280 |
+
|
281 |
+
def test_to_number_field():
|
282 |
+
assert to_number_field(sqrt(2)) == AlgebraicNumber(sqrt(2))
|
283 |
+
assert to_number_field(
|
284 |
+
[sqrt(2), sqrt(3)]) == AlgebraicNumber(sqrt(2) + sqrt(3))
|
285 |
+
|
286 |
+
a = AlgebraicNumber(sqrt(2) + sqrt(3), [S.Half, S.Zero, Rational(-9, 2), S.Zero])
|
287 |
+
|
288 |
+
assert to_number_field(sqrt(2), sqrt(2) + sqrt(3)) == a
|
289 |
+
assert to_number_field(sqrt(2), AlgebraicNumber(sqrt(2) + sqrt(3))) == a
|
290 |
+
|
291 |
+
raises(IsomorphismFailed, lambda: to_number_field(sqrt(2), sqrt(3)))
|
292 |
+
|
293 |
+
|
294 |
+
def test_issue_22561():
|
295 |
+
a = to_number_field(sqrt(2), sqrt(2) + sqrt(3))
|
296 |
+
b = to_number_field(sqrt(2), sqrt(2) + sqrt(5))
|
297 |
+
assert field_isomorphism(a, b) == [1, 0]
|
298 |
+
|
299 |
+
|
300 |
+
def test_issue_22736():
|
301 |
+
a = CRootOf(x**4 + x**3 + x**2 + x + 1, -1)
|
302 |
+
a._reset()
|
303 |
+
b = exp(2*I*pi/5)
|
304 |
+
assert field_isomorphism(a, b) == [1, 0]
|
env-llmeval/lib/python3.10/site-packages/sympy/polys/numberfields/tests/test_utilities.py
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.abc import x
|
2 |
+
from sympy.core.numbers import (I, Rational)
|
3 |
+
from sympy.core.singleton import S
|
4 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
5 |
+
from sympy.polys import Poly, cyclotomic_poly
|
6 |
+
from sympy.polys.domains import FF, QQ
|
7 |
+
from sympy.polys.matrices import DomainMatrix, DM
|
8 |
+
from sympy.polys.matrices.exceptions import DMRankError
|
9 |
+
from sympy.polys.numberfields.utilities import (
|
10 |
+
AlgIntPowers, coeff_search, extract_fundamental_discriminant,
|
11 |
+
isolate, supplement_a_subspace,
|
12 |
+
)
|
13 |
+
from sympy.printing.lambdarepr import IntervalPrinter
|
14 |
+
from sympy.testing.pytest import raises
|
15 |
+
|
16 |
+
|
17 |
+
def test_AlgIntPowers_01():
|
18 |
+
T = Poly(cyclotomic_poly(5))
|
19 |
+
zeta_pow = AlgIntPowers(T)
|
20 |
+
raises(ValueError, lambda: zeta_pow[-1])
|
21 |
+
for e in range(10):
|
22 |
+
a = e % 5
|
23 |
+
if a < 4:
|
24 |
+
c = zeta_pow[e]
|
25 |
+
assert c[a] == 1 and all(c[i] == 0 for i in range(4) if i != a)
|
26 |
+
else:
|
27 |
+
assert zeta_pow[e] == [-1] * 4
|
28 |
+
|
29 |
+
|
30 |
+
def test_AlgIntPowers_02():
|
31 |
+
T = Poly(x**3 + 2*x**2 + 3*x + 4)
|
32 |
+
m = 7
|
33 |
+
theta_pow = AlgIntPowers(T, m)
|
34 |
+
for e in range(10):
|
35 |
+
computed = theta_pow[e]
|
36 |
+
coeffs = (Poly(x)**e % T + Poly(x**3)).rep.rep[1:]
|
37 |
+
expected = [c % m for c in reversed(coeffs)]
|
38 |
+
assert computed == expected
|
39 |
+
|
40 |
+
|
41 |
+
def test_coeff_search():
|
42 |
+
C = []
|
43 |
+
search = coeff_search(2, 1)
|
44 |
+
for i, c in enumerate(search):
|
45 |
+
C.append(c)
|
46 |
+
if i == 12:
|
47 |
+
break
|
48 |
+
assert C == [[1, 1], [1, 0], [1, -1], [0, 1], [2, 2], [2, 1], [2, 0], [2, -1], [2, -2], [1, 2], [1, -2], [0, 2], [3, 3]]
|
49 |
+
|
50 |
+
|
51 |
+
def test_extract_fundamental_discriminant():
|
52 |
+
# To extract, integer must be 0 or 1 mod 4.
|
53 |
+
raises(ValueError, lambda: extract_fundamental_discriminant(2))
|
54 |
+
raises(ValueError, lambda: extract_fundamental_discriminant(3))
|
55 |
+
# Try many cases, of different forms:
|
56 |
+
cases = (
|
57 |
+
(0, {}, {0: 1}),
|
58 |
+
(1, {}, {}),
|
59 |
+
(8, {2: 3}, {}),
|
60 |
+
(-8, {2: 3, -1: 1}, {}),
|
61 |
+
(12, {2: 2, 3: 1}, {}),
|
62 |
+
(36, {}, {2: 1, 3: 1}),
|
63 |
+
(45, {5: 1}, {3: 1}),
|
64 |
+
(48, {2: 2, 3: 1}, {2: 1}),
|
65 |
+
(1125, {5: 1}, {3: 1, 5: 1}),
|
66 |
+
)
|
67 |
+
for a, D_expected, F_expected in cases:
|
68 |
+
D, F = extract_fundamental_discriminant(a)
|
69 |
+
assert D == D_expected
|
70 |
+
assert F == F_expected
|
71 |
+
|
72 |
+
|
73 |
+
def test_supplement_a_subspace_1():
|
74 |
+
M = DM([[1, 7, 0], [2, 3, 4]], QQ).transpose()
|
75 |
+
|
76 |
+
# First supplement over QQ:
|
77 |
+
B = supplement_a_subspace(M)
|
78 |
+
assert B[:, :2] == M
|
79 |
+
assert B[:, 2] == DomainMatrix.eye(3, QQ).to_dense()[:, 0]
|
80 |
+
|
81 |
+
# Now supplement over FF(7):
|
82 |
+
M = M.convert_to(FF(7))
|
83 |
+
B = supplement_a_subspace(M)
|
84 |
+
assert B[:, :2] == M
|
85 |
+
# When we work mod 7, first col of M goes to [1, 0, 0],
|
86 |
+
# so the supplementary vector cannot equal this, as it did
|
87 |
+
# when we worked over QQ. Instead, we get the second std basis vector:
|
88 |
+
assert B[:, 2] == DomainMatrix.eye(3, FF(7)).to_dense()[:, 1]
|
89 |
+
|
90 |
+
|
91 |
+
def test_supplement_a_subspace_2():
|
92 |
+
M = DM([[1, 0, 0], [2, 0, 0]], QQ).transpose()
|
93 |
+
with raises(DMRankError):
|
94 |
+
supplement_a_subspace(M)
|
95 |
+
|
96 |
+
|
97 |
+
def test_IntervalPrinter():
|
98 |
+
ip = IntervalPrinter()
|
99 |
+
assert ip.doprint(x**Rational(1, 3)) == "x**(mpi('1/3'))"
|
100 |
+
assert ip.doprint(sqrt(x)) == "x**(mpi('1/2'))"
|
101 |
+
|
102 |
+
|
103 |
+
def test_isolate():
|
104 |
+
assert isolate(1) == (1, 1)
|
105 |
+
assert isolate(S.Half) == (S.Half, S.Half)
|
106 |
+
|
107 |
+
assert isolate(sqrt(2)) == (1, 2)
|
108 |
+
assert isolate(-sqrt(2)) == (-2, -1)
|
109 |
+
|
110 |
+
assert isolate(sqrt(2), eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12))
|
111 |
+
assert isolate(-sqrt(2), eps=Rational(1, 100)) == (Rational(-17, 12), Rational(-24, 17))
|
112 |
+
|
113 |
+
raises(NotImplementedError, lambda: isolate(I))
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_c.cpython-310.pyc
ADDED
Binary file (30.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_conventions.cpython-310.pyc
ADDED
Binary file (3.83 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_cupy.cpython-310.pyc
ADDED
Binary file (2.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_cxx.cpython-310.pyc
ADDED
Binary file (3.38 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_fortran.cpython-310.pyc
ADDED
Binary file (32.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_glsl.cpython-310.pyc
ADDED
Binary file (26.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_jscode.cpython-310.pyc
ADDED
Binary file (12.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_julia.cpython-310.pyc
ADDED
Binary file (14.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_latex.cpython-310.pyc
ADDED
Binary file (127 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_llvmjit.cpython-310.pyc
ADDED
Binary file (6.71 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_maple.cpython-310.pyc
ADDED
Binary file (14.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_mathematica.cpython-310.pyc
ADDED
Binary file (10.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_mathml.cpython-310.pyc
ADDED
Binary file (81.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_octave.cpython-310.pyc
ADDED
Binary file (20.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_python.cpython-310.pyc
ADDED
Binary file (8.37 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_rust.cpython-310.pyc
ADDED
Binary file (12.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_str.cpython-310.pyc
ADDED
Binary file (48.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_tableform.cpython-310.pyc
ADDED
Binary file (4.35 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_tensorflow.cpython-310.pyc
ADDED
Binary file (16 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_tree.cpython-310.pyc
ADDED
Binary file (4.48 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/utilities/__init__.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""This module contains some general purpose utilities that are used across
|
2 |
+
SymPy.
|
3 |
+
"""
|
4 |
+
from .iterables import (flatten, group, take, subsets,
|
5 |
+
variations, numbered_symbols, cartes, capture, dict_merge,
|
6 |
+
prefixes, postfixes, sift, topological_sort, unflatten,
|
7 |
+
has_dups, has_variety, reshape, rotations)
|
8 |
+
|
9 |
+
from .misc import filldedent
|
10 |
+
|
11 |
+
from .lambdify import lambdify
|
12 |
+
|
13 |
+
from .decorator import threaded, xthreaded, public, memoize_property
|
14 |
+
|
15 |
+
from .timeutils import timed
|
16 |
+
|
17 |
+
__all__ = [
|
18 |
+
'flatten', 'group', 'take', 'subsets', 'variations', 'numbered_symbols',
|
19 |
+
'cartes', 'capture', 'dict_merge', 'prefixes', 'postfixes', 'sift',
|
20 |
+
'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape',
|
21 |
+
'rotations',
|
22 |
+
|
23 |
+
'filldedent',
|
24 |
+
|
25 |
+
'lambdify',
|
26 |
+
|
27 |
+
'threaded', 'xthreaded', 'public', 'memoize_property',
|
28 |
+
|
29 |
+
'timed',
|
30 |
+
]
|
env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.01 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/codegen.cpython-310.pyc
ADDED
Binary file (63.6 kB). View file
|
|