applied-ai-018 commited on
Commit
313f213
·
verified ·
1 Parent(s): 3dd82bf

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step120/zero/11.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
  2. ckpts/universal/global_step120/zero/11.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
  3. ckpts/universal/global_step120/zero/14.input_layernorm.weight/exp_avg.pt +3 -0
  4. ckpts/universal/global_step120/zero/14.input_layernorm.weight/exp_avg_sq.pt +3 -0
  5. ckpts/universal/global_step120/zero/14.input_layernorm.weight/fp32.pt +3 -0
  6. ckpts/universal/global_step120/zero/20.post_attention_layernorm.weight/exp_avg.pt +3 -0
  7. ckpts/universal/global_step120/zero/20.post_attention_layernorm.weight/exp_avg_sq.pt +3 -0
  8. ckpts/universal/global_step120/zero/20.post_attention_layernorm.weight/fp32.pt +3 -0
  9. ckpts/universal/global_step120/zero/24.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
  10. ckpts/universal/global_step120/zero/24.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
  11. ckpts/universal/global_step120/zero/5.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
  12. venv/lib/python3.10/site-packages/sympy/core/add.py +1287 -0
  13. venv/lib/python3.10/site-packages/sympy/core/alphabets.py +4 -0
  14. venv/lib/python3.10/site-packages/sympy/core/backend.py +84 -0
  15. venv/lib/python3.10/site-packages/sympy/core/core.py +63 -0
  16. venv/lib/python3.10/site-packages/sympy/core/decorators.py +238 -0
  17. venv/lib/python3.10/site-packages/sympy/core/evalf.py +1801 -0
  18. venv/lib/python3.10/site-packages/sympy/core/mod.py +238 -0
  19. venv/lib/python3.10/site-packages/sympy/core/parameters.py +161 -0
  20. venv/lib/python3.10/site-packages/sympy/core/power.py +2004 -0
  21. venv/lib/python3.10/site-packages/sympy/core/relational.py +1587 -0
  22. venv/lib/python3.10/site-packages/sympy/core/sorting.py +309 -0
  23. venv/lib/python3.10/site-packages/sympy/core/trace.py +12 -0
  24. venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/__init__.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/bivariate.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/decompogen.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/deutils.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/inequalities.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/pde.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/polysys.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/recurr.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/solvers.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/solveset.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/sympy/solvers/benchmarks/__init__.py +0 -0
  35. venv/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/bench_solvers.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/sympy/solvers/benchmarks/bench_solvers.py +12 -0
  38. venv/lib/python3.10/site-packages/sympy/solvers/diophantine/__init__.py +5 -0
  39. venv/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/__init__.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/diophantine.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/sympy/solvers/diophantine/diophantine.py +0 -0
  42. venv/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__init__.py +0 -0
  43. venv/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/test_diophantine.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/test_diophantine.py +1037 -0
  46. venv/lib/python3.10/site-packages/sympy/solvers/ode/__init__.py +16 -0
  47. venv/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/__init__.cpython-310.pyc +0 -0
  48. venv/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/hypergeometric.cpython-310.pyc +0 -0
  49. venv/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/lie_group.cpython-310.pyc +0 -0
  50. venv/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/nonhomogeneous.cpython-310.pyc +0 -0
ckpts/universal/global_step120/zero/11.mlp.dense_4h_to_h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b52e0c49f8ba36772094d243ff57ea468caffec36365d7965894ef18c69c09e1
3
+ size 33555627
ckpts/universal/global_step120/zero/11.mlp.dense_4h_to_h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a2066afedd5ba39e417fe0ca4bb0dd4eec14af5b673c6093a15f42bb12b85bae
3
+ size 33555533
ckpts/universal/global_step120/zero/14.input_layernorm.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ffde4b05fd5f228b10401cc470fe1826e8c65dd62bb5db16c42cf5b1d8c6615
3
+ size 9372
ckpts/universal/global_step120/zero/14.input_layernorm.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db31c7c8a727f102713d18886e43d4a6e9cb28ee5e6235788ad4025d077145fb
3
+ size 9387
ckpts/universal/global_step120/zero/14.input_layernorm.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:469ca80dcb5385265a7cdde3b0ff4f4eed282fd515c929dae464e5d7f0409334
3
+ size 9293
ckpts/universal/global_step120/zero/20.post_attention_layernorm.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce67db68e1f415307ac462bf595a1c592cbfbba65c157a7155c25691e1e0e4c0
3
+ size 9372
ckpts/universal/global_step120/zero/20.post_attention_layernorm.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:346bbe948843055fa9b2a5bcd21c2eec7f116ca48836e98badf19ab8687b3b39
3
+ size 9387
ckpts/universal/global_step120/zero/20.post_attention_layernorm.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e60f3e5e5b455ced5a141a0d56ab43bd10b814894897cb46b737830878dc5b35
3
+ size 9293
ckpts/universal/global_step120/zero/24.mlp.dense_4h_to_h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:116b57da1f77bc8a2490e1177fbaef43913dead5bdefa000fe87537aece53523
3
+ size 33555627
ckpts/universal/global_step120/zero/24.mlp.dense_4h_to_h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd98c8354e01844182b9e134cb8f61c2ff74ab55ddcee3c04fd8ebf4c7d22a5d
3
+ size 33555533
ckpts/universal/global_step120/zero/5.mlp.dense_4h_to_h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ca85bb2dc05ab5bdd9e72a9f3f6f4514fcd4d7f461185d659d09ae0e80e56f2
3
+ size 33555627
venv/lib/python3.10/site-packages/sympy/core/add.py ADDED
@@ -0,0 +1,1287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple as tTuple
2
+ from collections import defaultdict
3
+ from functools import cmp_to_key, reduce
4
+ from operator import attrgetter
5
+ from .basic import Basic
6
+ from .parameters import global_parameters
7
+ from .logic import _fuzzy_group, fuzzy_or, fuzzy_not
8
+ from .singleton import S
9
+ from .operations import AssocOp, AssocOpDispatcher
10
+ from .cache import cacheit
11
+ from .numbers import ilcm, igcd, equal_valued
12
+ from .expr import Expr
13
+ from .kind import UndefinedKind
14
+ from sympy.utilities.iterables import is_sequence, sift
15
+
16
+ # Key for sorting commutative args in canonical order
17
+ _args_sortkey = cmp_to_key(Basic.compare)
18
+
19
+
20
+ def _could_extract_minus_sign(expr):
21
+ # assume expr is Add-like
22
+ # We choose the one with less arguments with minus signs
23
+ negative_args = sum(1 for i in expr.args
24
+ if i.could_extract_minus_sign())
25
+ positive_args = len(expr.args) - negative_args
26
+ if positive_args > negative_args:
27
+ return False
28
+ elif positive_args < negative_args:
29
+ return True
30
+ # choose based on .sort_key() to prefer
31
+ # x - 1 instead of 1 - x and
32
+ # 3 - sqrt(2) instead of -3 + sqrt(2)
33
+ return bool(expr.sort_key() < (-expr).sort_key())
34
+
35
+
36
+ def _addsort(args):
37
+ # in-place sorting of args
38
+ args.sort(key=_args_sortkey)
39
+
40
+
41
+ def _unevaluated_Add(*args):
42
+ """Return a well-formed unevaluated Add: Numbers are collected and
43
+ put in slot 0 and args are sorted. Use this when args have changed
44
+ but you still want to return an unevaluated Add.
45
+
46
+ Examples
47
+ ========
48
+
49
+ >>> from sympy.core.add import _unevaluated_Add as uAdd
50
+ >>> from sympy import S, Add
51
+ >>> from sympy.abc import x, y
52
+ >>> a = uAdd(*[S(1.0), x, S(2)])
53
+ >>> a.args[0]
54
+ 3.00000000000000
55
+ >>> a.args[1]
56
+ x
57
+
58
+ Beyond the Number being in slot 0, there is no other assurance of
59
+ order for the arguments since they are hash sorted. So, for testing
60
+ purposes, output produced by this in some other function can only
61
+ be tested against the output of this function or as one of several
62
+ options:
63
+
64
+ >>> opts = (Add(x, y, evaluate=False), Add(y, x, evaluate=False))
65
+ >>> a = uAdd(x, y)
66
+ >>> assert a in opts and a == uAdd(x, y)
67
+ >>> uAdd(x + 1, x + 2)
68
+ x + x + 3
69
+ """
70
+ args = list(args)
71
+ newargs = []
72
+ co = S.Zero
73
+ while args:
74
+ a = args.pop()
75
+ if a.is_Add:
76
+ # this will keep nesting from building up
77
+ # so that x + (x + 1) -> x + x + 1 (3 args)
78
+ args.extend(a.args)
79
+ elif a.is_Number:
80
+ co += a
81
+ else:
82
+ newargs.append(a)
83
+ _addsort(newargs)
84
+ if co:
85
+ newargs.insert(0, co)
86
+ return Add._from_args(newargs)
87
+
88
+
89
+ class Add(Expr, AssocOp):
90
+ """
91
+ Expression representing addition operation for algebraic group.
92
+
93
+ .. deprecated:: 1.7
94
+
95
+ Using arguments that aren't subclasses of :class:`~.Expr` in core
96
+ operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
97
+ deprecated. See :ref:`non-expr-args-deprecated` for details.
98
+
99
+ Every argument of ``Add()`` must be ``Expr``. Infix operator ``+``
100
+ on most scalar objects in SymPy calls this class.
101
+
102
+ Another use of ``Add()`` is to represent the structure of abstract
103
+ addition so that its arguments can be substituted to return different
104
+ class. Refer to examples section for this.
105
+
106
+ ``Add()`` evaluates the argument unless ``evaluate=False`` is passed.
107
+ The evaluation logic includes:
108
+
109
+ 1. Flattening
110
+ ``Add(x, Add(y, z))`` -> ``Add(x, y, z)``
111
+
112
+ 2. Identity removing
113
+ ``Add(x, 0, y)`` -> ``Add(x, y)``
114
+
115
+ 3. Coefficient collecting by ``.as_coeff_Mul()``
116
+ ``Add(x, 2*x)`` -> ``Mul(3, x)``
117
+
118
+ 4. Term sorting
119
+ ``Add(y, x, 2)`` -> ``Add(2, x, y)``
120
+
121
+ If no argument is passed, identity element 0 is returned. If single
122
+ element is passed, that element is returned.
123
+
124
+ Note that ``Add(*args)`` is more efficient than ``sum(args)`` because
125
+ it flattens the arguments. ``sum(a, b, c, ...)`` recursively adds the
126
+ arguments as ``a + (b + (c + ...))``, which has quadratic complexity.
127
+ On the other hand, ``Add(a, b, c, d)`` does not assume nested
128
+ structure, making the complexity linear.
129
+
130
+ Since addition is group operation, every argument should have the
131
+ same :obj:`sympy.core.kind.Kind()`.
132
+
133
+ Examples
134
+ ========
135
+
136
+ >>> from sympy import Add, I
137
+ >>> from sympy.abc import x, y
138
+ >>> Add(x, 1)
139
+ x + 1
140
+ >>> Add(x, x)
141
+ 2*x
142
+ >>> 2*x**2 + 3*x + I*y + 2*y + 2*x/5 + 1.0*y + 1
143
+ 2*x**2 + 17*x/5 + 3.0*y + I*y + 1
144
+
145
+ If ``evaluate=False`` is passed, result is not evaluated.
146
+
147
+ >>> Add(1, 2, evaluate=False)
148
+ 1 + 2
149
+ >>> Add(x, x, evaluate=False)
150
+ x + x
151
+
152
+ ``Add()`` also represents the general structure of addition operation.
153
+
154
+ >>> from sympy import MatrixSymbol
155
+ >>> A,B = MatrixSymbol('A', 2,2), MatrixSymbol('B', 2,2)
156
+ >>> expr = Add(x,y).subs({x:A, y:B})
157
+ >>> expr
158
+ A + B
159
+ >>> type(expr)
160
+ <class 'sympy.matrices.expressions.matadd.MatAdd'>
161
+
162
+ Note that the printers do not display in args order.
163
+
164
+ >>> Add(x, 1)
165
+ x + 1
166
+ >>> Add(x, 1).args
167
+ (1, x)
168
+
169
+ See Also
170
+ ========
171
+
172
+ MatAdd
173
+
174
+ """
175
+
176
+ __slots__ = ()
177
+
178
+ args: tTuple[Expr, ...]
179
+
180
+ is_Add = True
181
+
182
+ _args_type = Expr
183
+
184
+ @classmethod
185
+ def flatten(cls, seq):
186
+ """
187
+ Takes the sequence "seq" of nested Adds and returns a flatten list.
188
+
189
+ Returns: (commutative_part, noncommutative_part, order_symbols)
190
+
191
+ Applies associativity, all terms are commutable with respect to
192
+ addition.
193
+
194
+ NB: the removal of 0 is already handled by AssocOp.__new__
195
+
196
+ See Also
197
+ ========
198
+
199
+ sympy.core.mul.Mul.flatten
200
+
201
+ """
202
+ from sympy.calculus.accumulationbounds import AccumBounds
203
+ from sympy.matrices.expressions import MatrixExpr
204
+ from sympy.tensor.tensor import TensExpr
205
+ rv = None
206
+ if len(seq) == 2:
207
+ a, b = seq
208
+ if b.is_Rational:
209
+ a, b = b, a
210
+ if a.is_Rational:
211
+ if b.is_Mul:
212
+ rv = [a, b], [], None
213
+ if rv:
214
+ if all(s.is_commutative for s in rv[0]):
215
+ return rv
216
+ return [], rv[0], None
217
+
218
+ terms = {} # term -> coeff
219
+ # e.g. x**2 -> 5 for ... + 5*x**2 + ...
220
+
221
+ coeff = S.Zero # coefficient (Number or zoo) to always be in slot 0
222
+ # e.g. 3 + ...
223
+ order_factors = []
224
+
225
+ extra = []
226
+
227
+ for o in seq:
228
+
229
+ # O(x)
230
+ if o.is_Order:
231
+ if o.expr.is_zero:
232
+ continue
233
+ for o1 in order_factors:
234
+ if o1.contains(o):
235
+ o = None
236
+ break
237
+ if o is None:
238
+ continue
239
+ order_factors = [o] + [
240
+ o1 for o1 in order_factors if not o.contains(o1)]
241
+ continue
242
+
243
+ # 3 or NaN
244
+ elif o.is_Number:
245
+ if (o is S.NaN or coeff is S.ComplexInfinity and
246
+ o.is_finite is False) and not extra:
247
+ # we know for sure the result will be nan
248
+ return [S.NaN], [], None
249
+ if coeff.is_Number or isinstance(coeff, AccumBounds):
250
+ coeff += o
251
+ if coeff is S.NaN and not extra:
252
+ # we know for sure the result will be nan
253
+ return [S.NaN], [], None
254
+ continue
255
+
256
+ elif isinstance(o, AccumBounds):
257
+ coeff = o.__add__(coeff)
258
+ continue
259
+
260
+ elif isinstance(o, MatrixExpr):
261
+ # can't add 0 to Matrix so make sure coeff is not 0
262
+ extra.append(o)
263
+ continue
264
+
265
+ elif isinstance(o, TensExpr):
266
+ coeff = o.__add__(coeff) if coeff else o
267
+ continue
268
+
269
+ elif o is S.ComplexInfinity:
270
+ if coeff.is_finite is False and not extra:
271
+ # we know for sure the result will be nan
272
+ return [S.NaN], [], None
273
+ coeff = S.ComplexInfinity
274
+ continue
275
+
276
+ # Add([...])
277
+ elif o.is_Add:
278
+ # NB: here we assume Add is always commutative
279
+ seq.extend(o.args) # TODO zerocopy?
280
+ continue
281
+
282
+ # Mul([...])
283
+ elif o.is_Mul:
284
+ c, s = o.as_coeff_Mul()
285
+
286
+ # check for unevaluated Pow, e.g. 2**3 or 2**(-1/2)
287
+ elif o.is_Pow:
288
+ b, e = o.as_base_exp()
289
+ if b.is_Number and (e.is_Integer or
290
+ (e.is_Rational and e.is_negative)):
291
+ seq.append(b**e)
292
+ continue
293
+ c, s = S.One, o
294
+
295
+ else:
296
+ # everything else
297
+ c = S.One
298
+ s = o
299
+
300
+ # now we have:
301
+ # o = c*s, where
302
+ #
303
+ # c is a Number
304
+ # s is an expression with number factor extracted
305
+ # let's collect terms with the same s, so e.g.
306
+ # 2*x**2 + 3*x**2 -> 5*x**2
307
+ if s in terms:
308
+ terms[s] += c
309
+ if terms[s] is S.NaN and not extra:
310
+ # we know for sure the result will be nan
311
+ return [S.NaN], [], None
312
+ else:
313
+ terms[s] = c
314
+
315
+ # now let's construct new args:
316
+ # [2*x**2, x**3, 7*x**4, pi, ...]
317
+ newseq = []
318
+ noncommutative = False
319
+ for s, c in terms.items():
320
+ # 0*s
321
+ if c.is_zero:
322
+ continue
323
+ # 1*s
324
+ elif c is S.One:
325
+ newseq.append(s)
326
+ # c*s
327
+ else:
328
+ if s.is_Mul:
329
+ # Mul, already keeps its arguments in perfect order.
330
+ # so we can simply put c in slot0 and go the fast way.
331
+ cs = s._new_rawargs(*((c,) + s.args))
332
+ newseq.append(cs)
333
+ elif s.is_Add:
334
+ # we just re-create the unevaluated Mul
335
+ newseq.append(Mul(c, s, evaluate=False))
336
+ else:
337
+ # alternatively we have to call all Mul's machinery (slow)
338
+ newseq.append(Mul(c, s))
339
+
340
+ noncommutative = noncommutative or not s.is_commutative
341
+
342
+ # oo, -oo
343
+ if coeff is S.Infinity:
344
+ newseq = [f for f in newseq if not (f.is_extended_nonnegative or f.is_real)]
345
+
346
+ elif coeff is S.NegativeInfinity:
347
+ newseq = [f for f in newseq if not (f.is_extended_nonpositive or f.is_real)]
348
+
349
+ if coeff is S.ComplexInfinity:
350
+ # zoo might be
351
+ # infinite_real + finite_im
352
+ # finite_real + infinite_im
353
+ # infinite_real + infinite_im
354
+ # addition of a finite real or imaginary number won't be able to
355
+ # change the zoo nature; adding an infinite qualtity would result
356
+ # in a NaN condition if it had sign opposite of the infinite
357
+ # portion of zoo, e.g., infinite_real - infinite_real.
358
+ newseq = [c for c in newseq if not (c.is_finite and
359
+ c.is_extended_real is not None)]
360
+
361
+ # process O(x)
362
+ if order_factors:
363
+ newseq2 = []
364
+ for t in newseq:
365
+ for o in order_factors:
366
+ # x + O(x) -> O(x)
367
+ if o.contains(t):
368
+ t = None
369
+ break
370
+ # x + O(x**2) -> x + O(x**2)
371
+ if t is not None:
372
+ newseq2.append(t)
373
+ newseq = newseq2 + order_factors
374
+ # 1 + O(1) -> O(1)
375
+ for o in order_factors:
376
+ if o.contains(coeff):
377
+ coeff = S.Zero
378
+ break
379
+
380
+ # order args canonically
381
+ _addsort(newseq)
382
+
383
+ # current code expects coeff to be first
384
+ if coeff is not S.Zero:
385
+ newseq.insert(0, coeff)
386
+
387
+ if extra:
388
+ newseq += extra
389
+ noncommutative = True
390
+
391
+ # we are done
392
+ if noncommutative:
393
+ return [], newseq, None
394
+ else:
395
+ return newseq, [], None
396
+
397
+ @classmethod
398
+ def class_key(cls):
399
+ return 3, 1, cls.__name__
400
+
401
+ @property
402
+ def kind(self):
403
+ k = attrgetter('kind')
404
+ kinds = map(k, self.args)
405
+ kinds = frozenset(kinds)
406
+ if len(kinds) != 1:
407
+ # Since addition is group operator, kind must be same.
408
+ # We know that this is unexpected signature, so return this.
409
+ result = UndefinedKind
410
+ else:
411
+ result, = kinds
412
+ return result
413
+
414
+ def could_extract_minus_sign(self):
415
+ return _could_extract_minus_sign(self)
416
+
417
+ @cacheit
418
+ def as_coeff_add(self, *deps):
419
+ """
420
+ Returns a tuple (coeff, args) where self is treated as an Add and coeff
421
+ is the Number term and args is a tuple of all other terms.
422
+
423
+ Examples
424
+ ========
425
+
426
+ >>> from sympy.abc import x
427
+ >>> (7 + 3*x).as_coeff_add()
428
+ (7, (3*x,))
429
+ >>> (7*x).as_coeff_add()
430
+ (0, (7*x,))
431
+ """
432
+ if deps:
433
+ l1, l2 = sift(self.args, lambda x: x.has_free(*deps), binary=True)
434
+ return self._new_rawargs(*l2), tuple(l1)
435
+ coeff, notrat = self.args[0].as_coeff_add()
436
+ if coeff is not S.Zero:
437
+ return coeff, notrat + self.args[1:]
438
+ return S.Zero, self.args
439
+
440
+ def as_coeff_Add(self, rational=False, deps=None):
441
+ """
442
+ Efficiently extract the coefficient of a summation.
443
+ """
444
+ coeff, args = self.args[0], self.args[1:]
445
+
446
+ if coeff.is_Number and not rational or coeff.is_Rational:
447
+ return coeff, self._new_rawargs(*args)
448
+ return S.Zero, self
449
+
450
+ # Note, we intentionally do not implement Add.as_coeff_mul(). Rather, we
451
+ # let Expr.as_coeff_mul() just always return (S.One, self) for an Add. See
452
+ # issue 5524.
453
+
454
+ def _eval_power(self, e):
455
+ from .evalf import pure_complex
456
+ from .relational import is_eq
457
+ if len(self.args) == 2 and any(_.is_infinite for _ in self.args):
458
+ if e.is_zero is False and is_eq(e, S.One) is False:
459
+ # looking for literal a + I*b
460
+ a, b = self.args
461
+ if a.coeff(S.ImaginaryUnit):
462
+ a, b = b, a
463
+ ico = b.coeff(S.ImaginaryUnit)
464
+ if ico and ico.is_extended_real and a.is_extended_real:
465
+ if e.is_extended_negative:
466
+ return S.Zero
467
+ if e.is_extended_positive:
468
+ return S.ComplexInfinity
469
+ return
470
+ if e.is_Rational and self.is_number:
471
+ ri = pure_complex(self)
472
+ if ri:
473
+ r, i = ri
474
+ if e.q == 2:
475
+ from sympy.functions.elementary.miscellaneous import sqrt
476
+ D = sqrt(r**2 + i**2)
477
+ if D.is_Rational:
478
+ from .exprtools import factor_terms
479
+ from sympy.functions.elementary.complexes import sign
480
+ from .function import expand_multinomial
481
+ # (r, i, D) is a Pythagorean triple
482
+ root = sqrt(factor_terms((D - r)/2))**e.p
483
+ return root*expand_multinomial((
484
+ # principle value
485
+ (D + r)/abs(i) + sign(i)*S.ImaginaryUnit)**e.p)
486
+ elif e == -1:
487
+ return _unevaluated_Mul(
488
+ r - i*S.ImaginaryUnit,
489
+ 1/(r**2 + i**2))
490
+ elif e.is_Number and abs(e) != 1:
491
+ # handle the Float case: (2.0 + 4*x)**e -> 4**e*(0.5 + x)**e
492
+ c, m = zip(*[i.as_coeff_Mul() for i in self.args])
493
+ if any(i.is_Float for i in c): # XXX should this always be done?
494
+ big = -1
495
+ for i in c:
496
+ if abs(i) >= big:
497
+ big = abs(i)
498
+ if big > 0 and not equal_valued(big, 1):
499
+ from sympy.functions.elementary.complexes import sign
500
+ bigs = (big, -big)
501
+ c = [sign(i) if i in bigs else i/big for i in c]
502
+ addpow = Add(*[c*m for c, m in zip(c, m)])**e
503
+ return big**e*addpow
504
+
505
+ @cacheit
506
+ def _eval_derivative(self, s):
507
+ return self.func(*[a.diff(s) for a in self.args])
508
+
509
+ def _eval_nseries(self, x, n, logx, cdir=0):
510
+ terms = [t.nseries(x, n=n, logx=logx, cdir=cdir) for t in self.args]
511
+ return self.func(*terms)
512
+
513
+ def _matches_simple(self, expr, repl_dict):
514
+ # handle (w+3).matches('x+5') -> {w: x+2}
515
+ coeff, terms = self.as_coeff_add()
516
+ if len(terms) == 1:
517
+ return terms[0].matches(expr - coeff, repl_dict)
518
+ return
519
+
520
+ def matches(self, expr, repl_dict=None, old=False):
521
+ return self._matches_commutative(expr, repl_dict, old)
522
+
523
+ @staticmethod
524
+ def _combine_inverse(lhs, rhs):
525
+ """
526
+ Returns lhs - rhs, but treats oo like a symbol so oo - oo
527
+ returns 0, instead of a nan.
528
+ """
529
+ from sympy.simplify.simplify import signsimp
530
+ inf = (S.Infinity, S.NegativeInfinity)
531
+ if lhs.has(*inf) or rhs.has(*inf):
532
+ from .symbol import Dummy
533
+ oo = Dummy('oo')
534
+ reps = {
535
+ S.Infinity: oo,
536
+ S.NegativeInfinity: -oo}
537
+ ireps = {v: k for k, v in reps.items()}
538
+ eq = lhs.xreplace(reps) - rhs.xreplace(reps)
539
+ if eq.has(oo):
540
+ eq = eq.replace(
541
+ lambda x: x.is_Pow and x.base is oo,
542
+ lambda x: x.base)
543
+ rv = eq.xreplace(ireps)
544
+ else:
545
+ rv = lhs - rhs
546
+ srv = signsimp(rv)
547
+ return srv if srv.is_Number else rv
548
+
549
+ @cacheit
550
+ def as_two_terms(self):
551
+ """Return head and tail of self.
552
+
553
+ This is the most efficient way to get the head and tail of an
554
+ expression.
555
+
556
+ - if you want only the head, use self.args[0];
557
+ - if you want to process the arguments of the tail then use
558
+ self.as_coef_add() which gives the head and a tuple containing
559
+ the arguments of the tail when treated as an Add.
560
+ - if you want the coefficient when self is treated as a Mul
561
+ then use self.as_coeff_mul()[0]
562
+
563
+ >>> from sympy.abc import x, y
564
+ >>> (3*x - 2*y + 5).as_two_terms()
565
+ (5, 3*x - 2*y)
566
+ """
567
+ return self.args[0], self._new_rawargs(*self.args[1:])
568
+
569
+ def as_numer_denom(self):
570
+ """
571
+ Decomposes an expression to its numerator part and its
572
+ denominator part.
573
+
574
+ Examples
575
+ ========
576
+
577
+ >>> from sympy.abc import x, y, z
578
+ >>> (x*y/z).as_numer_denom()
579
+ (x*y, z)
580
+ >>> (x*(y + 1)/y**7).as_numer_denom()
581
+ (x*(y + 1), y**7)
582
+
583
+ See Also
584
+ ========
585
+
586
+ sympy.core.expr.Expr.as_numer_denom
587
+ """
588
+ # clear rational denominator
589
+ content, expr = self.primitive()
590
+ if not isinstance(expr, Add):
591
+ return Mul(content, expr, evaluate=False).as_numer_denom()
592
+ ncon, dcon = content.as_numer_denom()
593
+
594
+ # collect numerators and denominators of the terms
595
+ nd = defaultdict(list)
596
+ for f in expr.args:
597
+ ni, di = f.as_numer_denom()
598
+ nd[di].append(ni)
599
+
600
+ # check for quick exit
601
+ if len(nd) == 1:
602
+ d, n = nd.popitem()
603
+ return self.func(
604
+ *[_keep_coeff(ncon, ni) for ni in n]), _keep_coeff(dcon, d)
605
+
606
+ # sum up the terms having a common denominator
607
+ for d, n in nd.items():
608
+ if len(n) == 1:
609
+ nd[d] = n[0]
610
+ else:
611
+ nd[d] = self.func(*n)
612
+
613
+ # assemble single numerator and denominator
614
+ denoms, numers = [list(i) for i in zip(*iter(nd.items()))]
615
+ n, d = self.func(*[Mul(*(denoms[:i] + [numers[i]] + denoms[i + 1:]))
616
+ for i in range(len(numers))]), Mul(*denoms)
617
+
618
+ return _keep_coeff(ncon, n), _keep_coeff(dcon, d)
619
+
620
+ def _eval_is_polynomial(self, syms):
621
+ return all(term._eval_is_polynomial(syms) for term in self.args)
622
+
623
+ def _eval_is_rational_function(self, syms):
624
+ return all(term._eval_is_rational_function(syms) for term in self.args)
625
+
626
+ def _eval_is_meromorphic(self, x, a):
627
+ return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args),
628
+ quick_exit=True)
629
+
630
+ def _eval_is_algebraic_expr(self, syms):
631
+ return all(term._eval_is_algebraic_expr(syms) for term in self.args)
632
+
633
+ # assumption methods
634
+ _eval_is_real = lambda self: _fuzzy_group(
635
+ (a.is_real for a in self.args), quick_exit=True)
636
+ _eval_is_extended_real = lambda self: _fuzzy_group(
637
+ (a.is_extended_real for a in self.args), quick_exit=True)
638
+ _eval_is_complex = lambda self: _fuzzy_group(
639
+ (a.is_complex for a in self.args), quick_exit=True)
640
+ _eval_is_antihermitian = lambda self: _fuzzy_group(
641
+ (a.is_antihermitian for a in self.args), quick_exit=True)
642
+ _eval_is_finite = lambda self: _fuzzy_group(
643
+ (a.is_finite for a in self.args), quick_exit=True)
644
+ _eval_is_hermitian = lambda self: _fuzzy_group(
645
+ (a.is_hermitian for a in self.args), quick_exit=True)
646
+ _eval_is_integer = lambda self: _fuzzy_group(
647
+ (a.is_integer for a in self.args), quick_exit=True)
648
+ _eval_is_rational = lambda self: _fuzzy_group(
649
+ (a.is_rational for a in self.args), quick_exit=True)
650
+ _eval_is_algebraic = lambda self: _fuzzy_group(
651
+ (a.is_algebraic for a in self.args), quick_exit=True)
652
+ _eval_is_commutative = lambda self: _fuzzy_group(
653
+ a.is_commutative for a in self.args)
654
+
655
+ def _eval_is_infinite(self):
656
+ sawinf = False
657
+ for a in self.args:
658
+ ainf = a.is_infinite
659
+ if ainf is None:
660
+ return None
661
+ elif ainf is True:
662
+ # infinite+infinite might not be infinite
663
+ if sawinf is True:
664
+ return None
665
+ sawinf = True
666
+ return sawinf
667
+
668
+ def _eval_is_imaginary(self):
669
+ nz = []
670
+ im_I = []
671
+ for a in self.args:
672
+ if a.is_extended_real:
673
+ if a.is_zero:
674
+ pass
675
+ elif a.is_zero is False:
676
+ nz.append(a)
677
+ else:
678
+ return
679
+ elif a.is_imaginary:
680
+ im_I.append(a*S.ImaginaryUnit)
681
+ elif a.is_Mul and S.ImaginaryUnit in a.args:
682
+ coeff, ai = a.as_coeff_mul(S.ImaginaryUnit)
683
+ if ai == (S.ImaginaryUnit,) and coeff.is_extended_real:
684
+ im_I.append(-coeff)
685
+ else:
686
+ return
687
+ else:
688
+ return
689
+ b = self.func(*nz)
690
+ if b != self:
691
+ if b.is_zero:
692
+ return fuzzy_not(self.func(*im_I).is_zero)
693
+ elif b.is_zero is False:
694
+ return False
695
+
696
+ def _eval_is_zero(self):
697
+ if self.is_commutative is False:
698
+ # issue 10528: there is no way to know if a nc symbol
699
+ # is zero or not
700
+ return
701
+ nz = []
702
+ z = 0
703
+ im_or_z = False
704
+ im = 0
705
+ for a in self.args:
706
+ if a.is_extended_real:
707
+ if a.is_zero:
708
+ z += 1
709
+ elif a.is_zero is False:
710
+ nz.append(a)
711
+ else:
712
+ return
713
+ elif a.is_imaginary:
714
+ im += 1
715
+ elif a.is_Mul and S.ImaginaryUnit in a.args:
716
+ coeff, ai = a.as_coeff_mul(S.ImaginaryUnit)
717
+ if ai == (S.ImaginaryUnit,) and coeff.is_extended_real:
718
+ im_or_z = True
719
+ else:
720
+ return
721
+ else:
722
+ return
723
+ if z == len(self.args):
724
+ return True
725
+ if len(nz) in [0, len(self.args)]:
726
+ return None
727
+ b = self.func(*nz)
728
+ if b.is_zero:
729
+ if not im_or_z:
730
+ if im == 0:
731
+ return True
732
+ elif im == 1:
733
+ return False
734
+ if b.is_zero is False:
735
+ return False
736
+
737
+ def _eval_is_odd(self):
738
+ l = [f for f in self.args if not (f.is_even is True)]
739
+ if not l:
740
+ return False
741
+ if l[0].is_odd:
742
+ return self._new_rawargs(*l[1:]).is_even
743
+
744
+ def _eval_is_irrational(self):
745
+ for t in self.args:
746
+ a = t.is_irrational
747
+ if a:
748
+ others = list(self.args)
749
+ others.remove(t)
750
+ if all(x.is_rational is True for x in others):
751
+ return True
752
+ return None
753
+ if a is None:
754
+ return
755
+ return False
756
+
757
+ def _all_nonneg_or_nonppos(self):
758
+ nn = np = 0
759
+ for a in self.args:
760
+ if a.is_nonnegative:
761
+ if np:
762
+ return False
763
+ nn = 1
764
+ elif a.is_nonpositive:
765
+ if nn:
766
+ return False
767
+ np = 1
768
+ else:
769
+ break
770
+ else:
771
+ return True
772
+
773
+ def _eval_is_extended_positive(self):
774
+ if self.is_number:
775
+ return super()._eval_is_extended_positive()
776
+ c, a = self.as_coeff_Add()
777
+ if not c.is_zero:
778
+ from .exprtools import _monotonic_sign
779
+ v = _monotonic_sign(a)
780
+ if v is not None:
781
+ s = v + c
782
+ if s != self and s.is_extended_positive and a.is_extended_nonnegative:
783
+ return True
784
+ if len(self.free_symbols) == 1:
785
+ v = _monotonic_sign(self)
786
+ if v is not None and v != self and v.is_extended_positive:
787
+ return True
788
+ pos = nonneg = nonpos = unknown_sign = False
789
+ saw_INF = set()
790
+ args = [a for a in self.args if not a.is_zero]
791
+ if not args:
792
+ return False
793
+ for a in args:
794
+ ispos = a.is_extended_positive
795
+ infinite = a.is_infinite
796
+ if infinite:
797
+ saw_INF.add(fuzzy_or((ispos, a.is_extended_nonnegative)))
798
+ if True in saw_INF and False in saw_INF:
799
+ return
800
+ if ispos:
801
+ pos = True
802
+ continue
803
+ elif a.is_extended_nonnegative:
804
+ nonneg = True
805
+ continue
806
+ elif a.is_extended_nonpositive:
807
+ nonpos = True
808
+ continue
809
+
810
+ if infinite is None:
811
+ return
812
+ unknown_sign = True
813
+
814
+ if saw_INF:
815
+ if len(saw_INF) > 1:
816
+ return
817
+ return saw_INF.pop()
818
+ elif unknown_sign:
819
+ return
820
+ elif not nonpos and not nonneg and pos:
821
+ return True
822
+ elif not nonpos and pos:
823
+ return True
824
+ elif not pos and not nonneg:
825
+ return False
826
+
827
+ def _eval_is_extended_nonnegative(self):
828
+ if not self.is_number:
829
+ c, a = self.as_coeff_Add()
830
+ if not c.is_zero and a.is_extended_nonnegative:
831
+ from .exprtools import _monotonic_sign
832
+ v = _monotonic_sign(a)
833
+ if v is not None:
834
+ s = v + c
835
+ if s != self and s.is_extended_nonnegative:
836
+ return True
837
+ if len(self.free_symbols) == 1:
838
+ v = _monotonic_sign(self)
839
+ if v is not None and v != self and v.is_extended_nonnegative:
840
+ return True
841
+
842
+ def _eval_is_extended_nonpositive(self):
843
+ if not self.is_number:
844
+ c, a = self.as_coeff_Add()
845
+ if not c.is_zero and a.is_extended_nonpositive:
846
+ from .exprtools import _monotonic_sign
847
+ v = _monotonic_sign(a)
848
+ if v is not None:
849
+ s = v + c
850
+ if s != self and s.is_extended_nonpositive:
851
+ return True
852
+ if len(self.free_symbols) == 1:
853
+ v = _monotonic_sign(self)
854
+ if v is not None and v != self and v.is_extended_nonpositive:
855
+ return True
856
+
857
+ def _eval_is_extended_negative(self):
858
+ if self.is_number:
859
+ return super()._eval_is_extended_negative()
860
+ c, a = self.as_coeff_Add()
861
+ if not c.is_zero:
862
+ from .exprtools import _monotonic_sign
863
+ v = _monotonic_sign(a)
864
+ if v is not None:
865
+ s = v + c
866
+ if s != self and s.is_extended_negative and a.is_extended_nonpositive:
867
+ return True
868
+ if len(self.free_symbols) == 1:
869
+ v = _monotonic_sign(self)
870
+ if v is not None and v != self and v.is_extended_negative:
871
+ return True
872
+ neg = nonpos = nonneg = unknown_sign = False
873
+ saw_INF = set()
874
+ args = [a for a in self.args if not a.is_zero]
875
+ if not args:
876
+ return False
877
+ for a in args:
878
+ isneg = a.is_extended_negative
879
+ infinite = a.is_infinite
880
+ if infinite:
881
+ saw_INF.add(fuzzy_or((isneg, a.is_extended_nonpositive)))
882
+ if True in saw_INF and False in saw_INF:
883
+ return
884
+ if isneg:
885
+ neg = True
886
+ continue
887
+ elif a.is_extended_nonpositive:
888
+ nonpos = True
889
+ continue
890
+ elif a.is_extended_nonnegative:
891
+ nonneg = True
892
+ continue
893
+
894
+ if infinite is None:
895
+ return
896
+ unknown_sign = True
897
+
898
+ if saw_INF:
899
+ if len(saw_INF) > 1:
900
+ return
901
+ return saw_INF.pop()
902
+ elif unknown_sign:
903
+ return
904
+ elif not nonneg and not nonpos and neg:
905
+ return True
906
+ elif not nonneg and neg:
907
+ return True
908
+ elif not neg and not nonpos:
909
+ return False
910
+
911
+ def _eval_subs(self, old, new):
912
+ if not old.is_Add:
913
+ if old is S.Infinity and -old in self.args:
914
+ # foo - oo is foo + (-oo) internally
915
+ return self.xreplace({-old: -new})
916
+ return None
917
+
918
+ coeff_self, terms_self = self.as_coeff_Add()
919
+ coeff_old, terms_old = old.as_coeff_Add()
920
+
921
+ if coeff_self.is_Rational and coeff_old.is_Rational:
922
+ if terms_self == terms_old: # (2 + a).subs( 3 + a, y) -> -1 + y
923
+ return self.func(new, coeff_self, -coeff_old)
924
+ if terms_self == -terms_old: # (2 + a).subs(-3 - a, y) -> -1 - y
925
+ return self.func(-new, coeff_self, coeff_old)
926
+
927
+ if coeff_self.is_Rational and coeff_old.is_Rational \
928
+ or coeff_self == coeff_old:
929
+ args_old, args_self = self.func.make_args(
930
+ terms_old), self.func.make_args(terms_self)
931
+ if len(args_old) < len(args_self): # (a+b+c).subs(b+c,x) -> a+x
932
+ self_set = set(args_self)
933
+ old_set = set(args_old)
934
+
935
+ if old_set < self_set:
936
+ ret_set = self_set - old_set
937
+ return self.func(new, coeff_self, -coeff_old,
938
+ *[s._subs(old, new) for s in ret_set])
939
+
940
+ args_old = self.func.make_args(
941
+ -terms_old) # (a+b+c+d).subs(-b-c,x) -> a-x+d
942
+ old_set = set(args_old)
943
+ if old_set < self_set:
944
+ ret_set = self_set - old_set
945
+ return self.func(-new, coeff_self, coeff_old,
946
+ *[s._subs(old, new) for s in ret_set])
947
+
948
+ def removeO(self):
949
+ args = [a for a in self.args if not a.is_Order]
950
+ return self._new_rawargs(*args)
951
+
952
+ def getO(self):
953
+ args = [a for a in self.args if a.is_Order]
954
+ if args:
955
+ return self._new_rawargs(*args)
956
+
957
+ @cacheit
958
+ def extract_leading_order(self, symbols, point=None):
959
+ """
960
+ Returns the leading term and its order.
961
+
962
+ Examples
963
+ ========
964
+
965
+ >>> from sympy.abc import x
966
+ >>> (x + 1 + 1/x**5).extract_leading_order(x)
967
+ ((x**(-5), O(x**(-5))),)
968
+ >>> (1 + x).extract_leading_order(x)
969
+ ((1, O(1)),)
970
+ >>> (x + x**2).extract_leading_order(x)
971
+ ((x, O(x)),)
972
+
973
+ """
974
+ from sympy.series.order import Order
975
+ lst = []
976
+ symbols = list(symbols if is_sequence(symbols) else [symbols])
977
+ if not point:
978
+ point = [0]*len(symbols)
979
+ seq = [(f, Order(f, *zip(symbols, point))) for f in self.args]
980
+ for ef, of in seq:
981
+ for e, o in lst:
982
+ if o.contains(of) and o != of:
983
+ of = None
984
+ break
985
+ if of is None:
986
+ continue
987
+ new_lst = [(ef, of)]
988
+ for e, o in lst:
989
+ if of.contains(o) and o != of:
990
+ continue
991
+ new_lst.append((e, o))
992
+ lst = new_lst
993
+ return tuple(lst)
994
+
995
+ def as_real_imag(self, deep=True, **hints):
996
+ """
997
+ Return a tuple representing a complex number.
998
+
999
+ Examples
1000
+ ========
1001
+
1002
+ >>> from sympy import I
1003
+ >>> (7 + 9*I).as_real_imag()
1004
+ (7, 9)
1005
+ >>> ((1 + I)/(1 - I)).as_real_imag()
1006
+ (0, 1)
1007
+ >>> ((1 + 2*I)*(1 + 3*I)).as_real_imag()
1008
+ (-5, 5)
1009
+ """
1010
+ sargs = self.args
1011
+ re_part, im_part = [], []
1012
+ for term in sargs:
1013
+ re, im = term.as_real_imag(deep=deep)
1014
+ re_part.append(re)
1015
+ im_part.append(im)
1016
+ return (self.func(*re_part), self.func(*im_part))
1017
+
1018
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
1019
+ from sympy.core.symbol import Dummy, Symbol
1020
+ from sympy.series.order import Order
1021
+ from sympy.functions.elementary.exponential import log
1022
+ from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
1023
+ from .function import expand_mul
1024
+
1025
+ o = self.getO()
1026
+ if o is None:
1027
+ o = Order(0)
1028
+ old = self.removeO()
1029
+
1030
+ if old.has(Piecewise):
1031
+ old = piecewise_fold(old)
1032
+
1033
+ # This expansion is the last part of expand_log. expand_log also calls
1034
+ # expand_mul with factor=True, which would be more expensive
1035
+ if any(isinstance(a, log) for a in self.args):
1036
+ logflags = {"deep": True, "log": True, "mul": False, "power_exp": False,
1037
+ "power_base": False, "multinomial": False, "basic": False, "force": False,
1038
+ "factor": False}
1039
+ old = old.expand(**logflags)
1040
+ expr = expand_mul(old)
1041
+
1042
+ if not expr.is_Add:
1043
+ return expr.as_leading_term(x, logx=logx, cdir=cdir)
1044
+
1045
+ infinite = [t for t in expr.args if t.is_infinite]
1046
+
1047
+ _logx = Dummy('logx') if logx is None else logx
1048
+ leading_terms = [t.as_leading_term(x, logx=_logx, cdir=cdir) for t in expr.args]
1049
+
1050
+ min, new_expr = Order(0), 0
1051
+
1052
+ try:
1053
+ for term in leading_terms:
1054
+ order = Order(term, x)
1055
+ if not min or order not in min:
1056
+ min = order
1057
+ new_expr = term
1058
+ elif min in order:
1059
+ new_expr += term
1060
+
1061
+ except TypeError:
1062
+ return expr
1063
+
1064
+ if logx is None:
1065
+ new_expr = new_expr.subs(_logx, log(x))
1066
+
1067
+ is_zero = new_expr.is_zero
1068
+ if is_zero is None:
1069
+ new_expr = new_expr.trigsimp().cancel()
1070
+ is_zero = new_expr.is_zero
1071
+ if is_zero is True:
1072
+ # simple leading term analysis gave us cancelled terms but we have to send
1073
+ # back a term, so compute the leading term (via series)
1074
+ try:
1075
+ n0 = min.getn()
1076
+ except NotImplementedError:
1077
+ n0 = S.One
1078
+ if n0.has(Symbol):
1079
+ n0 = S.One
1080
+ res = Order(1)
1081
+ incr = S.One
1082
+ while res.is_Order:
1083
+ res = old._eval_nseries(x, n=n0+incr, logx=logx, cdir=cdir).cancel().powsimp().trigsimp()
1084
+ incr *= 2
1085
+ return res.as_leading_term(x, logx=logx, cdir=cdir)
1086
+
1087
+ elif new_expr is S.NaN:
1088
+ return old.func._from_args(infinite) + o
1089
+
1090
+ else:
1091
+ return new_expr
1092
+
1093
+ def _eval_adjoint(self):
1094
+ return self.func(*[t.adjoint() for t in self.args])
1095
+
1096
+ def _eval_conjugate(self):
1097
+ return self.func(*[t.conjugate() for t in self.args])
1098
+
1099
+ def _eval_transpose(self):
1100
+ return self.func(*[t.transpose() for t in self.args])
1101
+
1102
+ def primitive(self):
1103
+ """
1104
+ Return ``(R, self/R)`` where ``R``` is the Rational GCD of ``self```.
1105
+
1106
+ ``R`` is collected only from the leading coefficient of each term.
1107
+
1108
+ Examples
1109
+ ========
1110
+
1111
+ >>> from sympy.abc import x, y
1112
+
1113
+ >>> (2*x + 4*y).primitive()
1114
+ (2, x + 2*y)
1115
+
1116
+ >>> (2*x/3 + 4*y/9).primitive()
1117
+ (2/9, 3*x + 2*y)
1118
+
1119
+ >>> (2*x/3 + 4.2*y).primitive()
1120
+ (1/3, 2*x + 12.6*y)
1121
+
1122
+ No subprocessing of term factors is performed:
1123
+
1124
+ >>> ((2 + 2*x)*x + 2).primitive()
1125
+ (1, x*(2*x + 2) + 2)
1126
+
1127
+ Recursive processing can be done with the ``as_content_primitive()``
1128
+ method:
1129
+
1130
+ >>> ((2 + 2*x)*x + 2).as_content_primitive()
1131
+ (2, x*(x + 1) + 1)
1132
+
1133
+ See also: primitive() function in polytools.py
1134
+
1135
+ """
1136
+
1137
+ terms = []
1138
+ inf = False
1139
+ for a in self.args:
1140
+ c, m = a.as_coeff_Mul()
1141
+ if not c.is_Rational:
1142
+ c = S.One
1143
+ m = a
1144
+ inf = inf or m is S.ComplexInfinity
1145
+ terms.append((c.p, c.q, m))
1146
+
1147
+ if not inf:
1148
+ ngcd = reduce(igcd, [t[0] for t in terms], 0)
1149
+ dlcm = reduce(ilcm, [t[1] for t in terms], 1)
1150
+ else:
1151
+ ngcd = reduce(igcd, [t[0] for t in terms if t[1]], 0)
1152
+ dlcm = reduce(ilcm, [t[1] for t in terms if t[1]], 1)
1153
+
1154
+ if ngcd == dlcm == 1:
1155
+ return S.One, self
1156
+ if not inf:
1157
+ for i, (p, q, term) in enumerate(terms):
1158
+ terms[i] = _keep_coeff(Rational((p//ngcd)*(dlcm//q)), term)
1159
+ else:
1160
+ for i, (p, q, term) in enumerate(terms):
1161
+ if q:
1162
+ terms[i] = _keep_coeff(Rational((p//ngcd)*(dlcm//q)), term)
1163
+ else:
1164
+ terms[i] = _keep_coeff(Rational(p, q), term)
1165
+
1166
+ # we don't need a complete re-flattening since no new terms will join
1167
+ # so we just use the same sort as is used in Add.flatten. When the
1168
+ # coefficient changes, the ordering of terms may change, e.g.
1169
+ # (3*x, 6*y) -> (2*y, x)
1170
+ #
1171
+ # We do need to make sure that term[0] stays in position 0, however.
1172
+ #
1173
+ if terms[0].is_Number or terms[0] is S.ComplexInfinity:
1174
+ c = terms.pop(0)
1175
+ else:
1176
+ c = None
1177
+ _addsort(terms)
1178
+ if c:
1179
+ terms.insert(0, c)
1180
+ return Rational(ngcd, dlcm), self._new_rawargs(*terms)
1181
+
1182
+ def as_content_primitive(self, radical=False, clear=True):
1183
+ """Return the tuple (R, self/R) where R is the positive Rational
1184
+ extracted from self. If radical is True (default is False) then
1185
+ common radicals will be removed and included as a factor of the
1186
+ primitive expression.
1187
+
1188
+ Examples
1189
+ ========
1190
+
1191
+ >>> from sympy import sqrt
1192
+ >>> (3 + 3*sqrt(2)).as_content_primitive()
1193
+ (3, 1 + sqrt(2))
1194
+
1195
+ Radical content can also be factored out of the primitive:
1196
+
1197
+ >>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
1198
+ (2, sqrt(2)*(1 + 2*sqrt(5)))
1199
+
1200
+ See docstring of Expr.as_content_primitive for more examples.
1201
+ """
1202
+ con, prim = self.func(*[_keep_coeff(*a.as_content_primitive(
1203
+ radical=radical, clear=clear)) for a in self.args]).primitive()
1204
+ if not clear and not con.is_Integer and prim.is_Add:
1205
+ con, d = con.as_numer_denom()
1206
+ _p = prim/d
1207
+ if any(a.as_coeff_Mul()[0].is_Integer for a in _p.args):
1208
+ prim = _p
1209
+ else:
1210
+ con /= d
1211
+ if radical and prim.is_Add:
1212
+ # look for common radicals that can be removed
1213
+ args = prim.args
1214
+ rads = []
1215
+ common_q = None
1216
+ for m in args:
1217
+ term_rads = defaultdict(list)
1218
+ for ai in Mul.make_args(m):
1219
+ if ai.is_Pow:
1220
+ b, e = ai.as_base_exp()
1221
+ if e.is_Rational and b.is_Integer:
1222
+ term_rads[e.q].append(abs(int(b))**e.p)
1223
+ if not term_rads:
1224
+ break
1225
+ if common_q is None:
1226
+ common_q = set(term_rads.keys())
1227
+ else:
1228
+ common_q = common_q & set(term_rads.keys())
1229
+ if not common_q:
1230
+ break
1231
+ rads.append(term_rads)
1232
+ else:
1233
+ # process rads
1234
+ # keep only those in common_q
1235
+ for r in rads:
1236
+ for q in list(r.keys()):
1237
+ if q not in common_q:
1238
+ r.pop(q)
1239
+ for q in r:
1240
+ r[q] = Mul(*r[q])
1241
+ # find the gcd of bases for each q
1242
+ G = []
1243
+ for q in common_q:
1244
+ g = reduce(igcd, [r[q] for r in rads], 0)
1245
+ if g != 1:
1246
+ G.append(g**Rational(1, q))
1247
+ if G:
1248
+ G = Mul(*G)
1249
+ args = [ai/G for ai in args]
1250
+ prim = G*prim.func(*args)
1251
+
1252
+ return con, prim
1253
+
1254
+ @property
1255
+ def _sorted_args(self):
1256
+ from .sorting import default_sort_key
1257
+ return tuple(sorted(self.args, key=default_sort_key))
1258
+
1259
+ def _eval_difference_delta(self, n, step):
1260
+ from sympy.series.limitseq import difference_delta as dd
1261
+ return self.func(*[dd(a, n, step) for a in self.args])
1262
+
1263
+ @property
1264
+ def _mpc_(self):
1265
+ """
1266
+ Convert self to an mpmath mpc if possible
1267
+ """
1268
+ from .numbers import Float
1269
+ re_part, rest = self.as_coeff_Add()
1270
+ im_part, imag_unit = rest.as_coeff_Mul()
1271
+ if not imag_unit == S.ImaginaryUnit:
1272
+ # ValueError may seem more reasonable but since it's a @property,
1273
+ # we need to use AttributeError to keep from confusing things like
1274
+ # hasattr.
1275
+ raise AttributeError("Cannot convert Add to mpc. Must be of the form Number + Number*I")
1276
+
1277
+ return (Float(re_part)._mpf_, Float(im_part)._mpf_)
1278
+
1279
+ def __neg__(self):
1280
+ if not global_parameters.distribute:
1281
+ return super().__neg__()
1282
+ return Mul(S.NegativeOne, self)
1283
+
1284
+ add = AssocOpDispatcher('add')
1285
+
1286
+ from .mul import Mul, _keep_coeff, _unevaluated_Mul
1287
+ from .numbers import Rational
venv/lib/python3.10/site-packages/sympy/core/alphabets.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ greeks = ('alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',
2
+ 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu',
3
+ 'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon',
4
+ 'phi', 'chi', 'psi', 'omega')
venv/lib/python3.10/site-packages/sympy/core/backend.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ USE_SYMENGINE = os.getenv('USE_SYMENGINE', '0')
3
+ USE_SYMENGINE = USE_SYMENGINE.lower() in ('1', 't', 'true') # type: ignore
4
+
5
+ if USE_SYMENGINE:
6
+ from symengine import (Symbol, Integer, sympify, S,
7
+ SympifyError, exp, log, gamma, sqrt, I, E, pi, Matrix,
8
+ sin, cos, tan, cot, csc, sec, asin, acos, atan, acot, acsc, asec,
9
+ sinh, cosh, tanh, coth, asinh, acosh, atanh, acoth,
10
+ lambdify, symarray, diff, zeros, eye, diag, ones,
11
+ expand, Function, symbols, var, Add, Mul, Derivative,
12
+ ImmutableMatrix, MatrixBase, Rational, Basic)
13
+ from symengine.lib.symengine_wrapper import gcd as igcd
14
+ from symengine import AppliedUndef
15
+ else:
16
+ from sympy.core.add import Add
17
+ from sympy.core.basic import Basic
18
+ from sympy.core.function import (diff, Function, AppliedUndef,
19
+ expand, Derivative)
20
+ from sympy.core.mul import Mul
21
+ from sympy.core.numbers import igcd, pi, I, Integer, Rational, E
22
+ from sympy.core.singleton import S
23
+ from sympy.core.symbol import Symbol, var, symbols
24
+ from sympy.core.sympify import SympifyError, sympify
25
+ from sympy.functions.elementary.exponential import log, exp
26
+ from sympy.functions.elementary.hyperbolic import (coth, sinh,
27
+ acosh, acoth, tanh, asinh, atanh, cosh)
28
+ from sympy.functions.elementary.miscellaneous import sqrt
29
+ from sympy.functions.elementary.trigonometric import (csc,
30
+ asec, cos, atan, sec, acot, asin, tan, sin, cot, acsc, acos)
31
+ from sympy.functions.special.gamma_functions import gamma
32
+ from sympy.matrices.dense import (eye, zeros, diag, Matrix,
33
+ ones, symarray)
34
+ from sympy.matrices.immutable import ImmutableMatrix
35
+ from sympy.matrices.matrices import MatrixBase
36
+ from sympy.utilities.lambdify import lambdify
37
+
38
+
39
+ #
40
+ # XXX: Handling of immutable and mutable matrices in SymEngine is inconsistent
41
+ # with SymPy's matrix classes in at least SymEngine version 0.7.0. Until that
42
+ # is fixed the function below is needed for consistent behaviour when
43
+ # attempting to simplify a matrix.
44
+ #
45
+ # Expected behaviour of a SymPy mutable/immutable matrix .simplify() method:
46
+ #
47
+ # Matrix.simplify() : works in place, returns None
48
+ # ImmutableMatrix.simplify() : returns a simplified copy
49
+ #
50
+ # In SymEngine both mutable and immutable matrices simplify in place and return
51
+ # None. This is inconsistent with the matrix being "immutable" and also the
52
+ # returned None leads to problems in the mechanics module.
53
+ #
54
+ # The simplify function should not be used because simplify(M) sympifies the
55
+ # matrix M and the SymEngine matrices all sympify to SymPy matrices. If we want
56
+ # to work with SymEngine matrices then we need to use their .simplify() method
57
+ # but that method does not work correctly with immutable matrices.
58
+ #
59
+ # The _simplify_matrix function can be removed when the SymEngine bug is fixed.
60
+ # Since this should be a temporary problem we do not make this function part of
61
+ # the public API.
62
+ #
63
+ # SymEngine issue: https://github.com/symengine/symengine.py/issues/363
64
+ #
65
+
66
+ def _simplify_matrix(M):
67
+ """Return a simplified copy of the matrix M"""
68
+ assert isinstance(M, (Matrix, ImmutableMatrix))
69
+ Mnew = M.as_mutable() # makes a copy if mutable
70
+ Mnew.simplify()
71
+ if isinstance(M, ImmutableMatrix):
72
+ Mnew = Mnew.as_immutable()
73
+ return Mnew
74
+
75
+
76
+ __all__ = [
77
+ 'Symbol', 'Integer', 'sympify', 'S', 'SympifyError', 'exp', 'log',
78
+ 'gamma', 'sqrt', 'I', 'E', 'pi', 'Matrix', 'sin', 'cos', 'tan', 'cot',
79
+ 'csc', 'sec', 'asin', 'acos', 'atan', 'acot', 'acsc', 'asec', 'sinh',
80
+ 'cosh', 'tanh', 'coth', 'asinh', 'acosh', 'atanh', 'acoth', 'lambdify',
81
+ 'symarray', 'diff', 'zeros', 'eye', 'diag', 'ones', 'expand', 'Function',
82
+ 'symbols', 'var', 'Add', 'Mul', 'Derivative', 'ImmutableMatrix',
83
+ 'MatrixBase', 'Rational', 'Basic', 'igcd', 'AppliedUndef',
84
+ ]
venv/lib/python3.10/site-packages/sympy/core/core.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ The core's core. """
2
+ from __future__ import annotations
3
+
4
+
5
+ # used for canonical ordering of symbolic sequences
6
+ # via __cmp__ method:
7
+ # FIXME this is *so* irrelevant and outdated!
8
+ ordering_of_classes = [
9
+ # singleton numbers
10
+ 'Zero', 'One', 'Half', 'Infinity', 'NaN', 'NegativeOne', 'NegativeInfinity',
11
+ # numbers
12
+ 'Integer', 'Rational', 'Float',
13
+ # singleton symbols
14
+ 'Exp1', 'Pi', 'ImaginaryUnit',
15
+ # symbols
16
+ 'Symbol', 'Wild', 'Temporary',
17
+ # arithmetic operations
18
+ 'Pow', 'Mul', 'Add',
19
+ # function values
20
+ 'Derivative', 'Integral',
21
+ # defined singleton functions
22
+ 'Abs', 'Sign', 'Sqrt',
23
+ 'Floor', 'Ceiling',
24
+ 'Re', 'Im', 'Arg',
25
+ 'Conjugate',
26
+ 'Exp', 'Log',
27
+ 'Sin', 'Cos', 'Tan', 'Cot', 'ASin', 'ACos', 'ATan', 'ACot',
28
+ 'Sinh', 'Cosh', 'Tanh', 'Coth', 'ASinh', 'ACosh', 'ATanh', 'ACoth',
29
+ 'RisingFactorial', 'FallingFactorial',
30
+ 'factorial', 'binomial',
31
+ 'Gamma', 'LowerGamma', 'UpperGamma', 'PolyGamma',
32
+ 'Erf',
33
+ # special polynomials
34
+ 'Chebyshev', 'Chebyshev2',
35
+ # undefined functions
36
+ 'Function', 'WildFunction',
37
+ # anonymous functions
38
+ 'Lambda',
39
+ # Landau O symbol
40
+ 'Order',
41
+ # relational operations
42
+ 'Equality', 'Unequality', 'StrictGreaterThan', 'StrictLessThan',
43
+ 'GreaterThan', 'LessThan',
44
+ ]
45
+
46
+
47
+ class Registry:
48
+ """
49
+ Base class for registry objects.
50
+
51
+ Registries map a name to an object using attribute notation. Registry
52
+ classes behave singletonically: all their instances share the same state,
53
+ which is stored in the class object.
54
+
55
+ All subclasses should set `__slots__ = ()`.
56
+ """
57
+ __slots__ = ()
58
+
59
+ def __setattr__(self, name, obj):
60
+ setattr(self.__class__, name, obj)
61
+
62
+ def __delattr__(self, name):
63
+ delattr(self.__class__, name)
venv/lib/python3.10/site-packages/sympy/core/decorators.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SymPy core decorators.
3
+
4
+ The purpose of this module is to expose decorators without any other
5
+ dependencies, so that they can be easily imported anywhere in sympy/core.
6
+ """
7
+
8
+ from functools import wraps
9
+ from .sympify import SympifyError, sympify
10
+
11
+
12
+ def _sympifyit(arg, retval=None):
13
+ """
14
+ decorator to smartly _sympify function arguments
15
+
16
+ Explanation
17
+ ===========
18
+
19
+ @_sympifyit('other', NotImplemented)
20
+ def add(self, other):
21
+ ...
22
+
23
+ In add, other can be thought of as already being a SymPy object.
24
+
25
+ If it is not, the code is likely to catch an exception, then other will
26
+ be explicitly _sympified, and the whole code restarted.
27
+
28
+ if _sympify(arg) fails, NotImplemented will be returned
29
+
30
+ See also
31
+ ========
32
+
33
+ __sympifyit
34
+ """
35
+ def deco(func):
36
+ return __sympifyit(func, arg, retval)
37
+
38
+ return deco
39
+
40
+
41
+ def __sympifyit(func, arg, retval=None):
42
+ """Decorator to _sympify `arg` argument for function `func`.
43
+
44
+ Do not use directly -- use _sympifyit instead.
45
+ """
46
+
47
+ # we support f(a,b) only
48
+ if not func.__code__.co_argcount:
49
+ raise LookupError("func not found")
50
+ # only b is _sympified
51
+ assert func.__code__.co_varnames[1] == arg
52
+ if retval is None:
53
+ @wraps(func)
54
+ def __sympifyit_wrapper(a, b):
55
+ return func(a, sympify(b, strict=True))
56
+
57
+ else:
58
+ @wraps(func)
59
+ def __sympifyit_wrapper(a, b):
60
+ try:
61
+ # If an external class has _op_priority, it knows how to deal
62
+ # with SymPy objects. Otherwise, it must be converted.
63
+ if not hasattr(b, '_op_priority'):
64
+ b = sympify(b, strict=True)
65
+ return func(a, b)
66
+ except SympifyError:
67
+ return retval
68
+
69
+ return __sympifyit_wrapper
70
+
71
+
72
+ def call_highest_priority(method_name):
73
+ """A decorator for binary special methods to handle _op_priority.
74
+
75
+ Explanation
76
+ ===========
77
+
78
+ Binary special methods in Expr and its subclasses use a special attribute
79
+ '_op_priority' to determine whose special method will be called to
80
+ handle the operation. In general, the object having the highest value of
81
+ '_op_priority' will handle the operation. Expr and subclasses that define
82
+ custom binary special methods (__mul__, etc.) should decorate those
83
+ methods with this decorator to add the priority logic.
84
+
85
+ The ``method_name`` argument is the name of the method of the other class
86
+ that will be called. Use this decorator in the following manner::
87
+
88
+ # Call other.__rmul__ if other._op_priority > self._op_priority
89
+ @call_highest_priority('__rmul__')
90
+ def __mul__(self, other):
91
+ ...
92
+
93
+ # Call other.__mul__ if other._op_priority > self._op_priority
94
+ @call_highest_priority('__mul__')
95
+ def __rmul__(self, other):
96
+ ...
97
+ """
98
+ def priority_decorator(func):
99
+ @wraps(func)
100
+ def binary_op_wrapper(self, other):
101
+ if hasattr(other, '_op_priority'):
102
+ if other._op_priority > self._op_priority:
103
+ f = getattr(other, method_name, None)
104
+ if f is not None:
105
+ return f(self)
106
+ return func(self, other)
107
+ return binary_op_wrapper
108
+ return priority_decorator
109
+
110
+
111
+ def sympify_method_args(cls):
112
+ '''Decorator for a class with methods that sympify arguments.
113
+
114
+ Explanation
115
+ ===========
116
+
117
+ The sympify_method_args decorator is to be used with the sympify_return
118
+ decorator for automatic sympification of method arguments. This is
119
+ intended for the common idiom of writing a class like :
120
+
121
+ Examples
122
+ ========
123
+
124
+ >>> from sympy import Basic, SympifyError, S
125
+ >>> from sympy.core.sympify import _sympify
126
+
127
+ >>> class MyTuple(Basic):
128
+ ... def __add__(self, other):
129
+ ... try:
130
+ ... other = _sympify(other)
131
+ ... except SympifyError:
132
+ ... return NotImplemented
133
+ ... if not isinstance(other, MyTuple):
134
+ ... return NotImplemented
135
+ ... return MyTuple(*(self.args + other.args))
136
+
137
+ >>> MyTuple(S(1), S(2)) + MyTuple(S(3), S(4))
138
+ MyTuple(1, 2, 3, 4)
139
+
140
+ In the above it is important that we return NotImplemented when other is
141
+ not sympifiable and also when the sympified result is not of the expected
142
+ type. This allows the MyTuple class to be used cooperatively with other
143
+ classes that overload __add__ and want to do something else in combination
144
+ with instance of Tuple.
145
+
146
+ Using this decorator the above can be written as
147
+
148
+ >>> from sympy.core.decorators import sympify_method_args, sympify_return
149
+
150
+ >>> @sympify_method_args
151
+ ... class MyTuple(Basic):
152
+ ... @sympify_return([('other', 'MyTuple')], NotImplemented)
153
+ ... def __add__(self, other):
154
+ ... return MyTuple(*(self.args + other.args))
155
+
156
+ >>> MyTuple(S(1), S(2)) + MyTuple(S(3), S(4))
157
+ MyTuple(1, 2, 3, 4)
158
+
159
+ The idea here is that the decorators take care of the boiler-plate code
160
+ for making this happen in each method that potentially needs to accept
161
+ unsympified arguments. Then the body of e.g. the __add__ method can be
162
+ written without needing to worry about calling _sympify or checking the
163
+ type of the resulting object.
164
+
165
+ The parameters for sympify_return are a list of tuples of the form
166
+ (parameter_name, expected_type) and the value to return (e.g.
167
+ NotImplemented). The expected_type parameter can be a type e.g. Tuple or a
168
+ string 'Tuple'. Using a string is useful for specifying a Type within its
169
+ class body (as in the above example).
170
+
171
+ Notes: Currently sympify_return only works for methods that take a single
172
+ argument (not including self). Specifying an expected_type as a string
173
+ only works for the class in which the method is defined.
174
+ '''
175
+ # Extract the wrapped methods from each of the wrapper objects created by
176
+ # the sympify_return decorator. Doing this here allows us to provide the
177
+ # cls argument which is used for forward string referencing.
178
+ for attrname, obj in cls.__dict__.items():
179
+ if isinstance(obj, _SympifyWrapper):
180
+ setattr(cls, attrname, obj.make_wrapped(cls))
181
+ return cls
182
+
183
+
184
+ def sympify_return(*args):
185
+ '''Function/method decorator to sympify arguments automatically
186
+
187
+ See the docstring of sympify_method_args for explanation.
188
+ '''
189
+ # Store a wrapper object for the decorated method
190
+ def wrapper(func):
191
+ return _SympifyWrapper(func, args)
192
+ return wrapper
193
+
194
+
195
+ class _SympifyWrapper:
196
+ '''Internal class used by sympify_return and sympify_method_args'''
197
+
198
+ def __init__(self, func, args):
199
+ self.func = func
200
+ self.args = args
201
+
202
+ def make_wrapped(self, cls):
203
+ func = self.func
204
+ parameters, retval = self.args
205
+
206
+ # XXX: Handle more than one parameter?
207
+ [(parameter, expectedcls)] = parameters
208
+
209
+ # Handle forward references to the current class using strings
210
+ if expectedcls == cls.__name__:
211
+ expectedcls = cls
212
+
213
+ # Raise RuntimeError since this is a failure at import time and should
214
+ # not be recoverable.
215
+ nargs = func.__code__.co_argcount
216
+ # we support f(a, b) only
217
+ if nargs != 2:
218
+ raise RuntimeError('sympify_return can only be used with 2 argument functions')
219
+ # only b is _sympified
220
+ if func.__code__.co_varnames[1] != parameter:
221
+ raise RuntimeError('parameter name mismatch "%s" in %s' %
222
+ (parameter, func.__name__))
223
+
224
+ @wraps(func)
225
+ def _func(self, other):
226
+ # XXX: The check for _op_priority here should be removed. It is
227
+ # needed to stop mutable matrices from being sympified to
228
+ # immutable matrices which breaks things in quantum...
229
+ if not hasattr(other, '_op_priority'):
230
+ try:
231
+ other = sympify(other, strict=True)
232
+ except SympifyError:
233
+ return retval
234
+ if not isinstance(other, expectedcls):
235
+ return retval
236
+ return func(self, other)
237
+
238
+ return _func
venv/lib/python3.10/site-packages/sympy/core/evalf.py ADDED
@@ -0,0 +1,1801 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Adaptive numerical evaluation of SymPy expressions, using mpmath
3
+ for mathematical functions.
4
+ """
5
+ from __future__ import annotations
6
+ from typing import Tuple as tTuple, Optional, Union as tUnion, Callable, List, Dict as tDict, Type, TYPE_CHECKING, \
7
+ Any, overload
8
+
9
+ import math
10
+
11
+ import mpmath.libmp as libmp
12
+ from mpmath import (
13
+ make_mpc, make_mpf, mp, mpc, mpf, nsum, quadts, quadosc, workprec)
14
+ from mpmath import inf as mpmath_inf
15
+ from mpmath.libmp import (from_int, from_man_exp, from_rational, fhalf,
16
+ fnan, finf, fninf, fnone, fone, fzero, mpf_abs, mpf_add,
17
+ mpf_atan, mpf_atan2, mpf_cmp, mpf_cos, mpf_e, mpf_exp, mpf_log, mpf_lt,
18
+ mpf_mul, mpf_neg, mpf_pi, mpf_pow, mpf_pow_int, mpf_shift, mpf_sin,
19
+ mpf_sqrt, normalize, round_nearest, to_int, to_str)
20
+ from mpmath.libmp import bitcount as mpmath_bitcount
21
+ from mpmath.libmp.backend import MPZ
22
+ from mpmath.libmp.libmpc import _infs_nan
23
+ from mpmath.libmp.libmpf import dps_to_prec, prec_to_dps
24
+
25
+ from .sympify import sympify
26
+ from .singleton import S
27
+ from sympy.external.gmpy import SYMPY_INTS
28
+ from sympy.utilities.iterables import is_sequence
29
+ from sympy.utilities.lambdify import lambdify
30
+ from sympy.utilities.misc import as_int
31
+
32
+ if TYPE_CHECKING:
33
+ from sympy.core.expr import Expr
34
+ from sympy.core.add import Add
35
+ from sympy.core.mul import Mul
36
+ from sympy.core.power import Pow
37
+ from sympy.core.symbol import Symbol
38
+ from sympy.integrals.integrals import Integral
39
+ from sympy.concrete.summations import Sum
40
+ from sympy.concrete.products import Product
41
+ from sympy.functions.elementary.exponential import exp, log
42
+ from sympy.functions.elementary.complexes import Abs, re, im
43
+ from sympy.functions.elementary.integers import ceiling, floor
44
+ from sympy.functions.elementary.trigonometric import atan
45
+ from .numbers import Float, Rational, Integer, AlgebraicNumber, Number
46
+
47
+ LG10 = math.log(10, 2)
48
+ rnd = round_nearest
49
+
50
+
51
+ def bitcount(n):
52
+ """Return smallest integer, b, such that |n|/2**b < 1.
53
+ """
54
+ return mpmath_bitcount(abs(int(n)))
55
+
56
+ # Used in a few places as placeholder values to denote exponents and
57
+ # precision levels, e.g. of exact numbers. Must be careful to avoid
58
+ # passing these to mpmath functions or returning them in final results.
59
+ INF = float(mpmath_inf)
60
+ MINUS_INF = float(-mpmath_inf)
61
+
62
+ # ~= 100 digits. Real men set this to INF.
63
+ DEFAULT_MAXPREC = 333
64
+
65
+
66
+ class PrecisionExhausted(ArithmeticError):
67
+ pass
68
+
69
+ #----------------------------------------------------------------------------#
70
+ # #
71
+ # Helper functions for arithmetic and complex parts #
72
+ # #
73
+ #----------------------------------------------------------------------------#
74
+
75
+ """
76
+ An mpf value tuple is a tuple of integers (sign, man, exp, bc)
77
+ representing a floating-point number: [1, -1][sign]*man*2**exp where
78
+ sign is 0 or 1 and bc should correspond to the number of bits used to
79
+ represent the mantissa (man) in binary notation, e.g.
80
+ """
81
+ MPF_TUP = tTuple[int, int, int, int] # mpf value tuple
82
+
83
+ """
84
+ Explanation
85
+ ===========
86
+
87
+ >>> from sympy.core.evalf import bitcount
88
+ >>> sign, man, exp, bc = 0, 5, 1, 3
89
+ >>> n = [1, -1][sign]*man*2**exp
90
+ >>> n, bitcount(man)
91
+ (10, 3)
92
+
93
+ A temporary result is a tuple (re, im, re_acc, im_acc) where
94
+ re and im are nonzero mpf value tuples representing approximate
95
+ numbers, or None to denote exact zeros.
96
+
97
+ re_acc, im_acc are integers denoting log2(e) where e is the estimated
98
+ relative accuracy of the respective complex part, but may be anything
99
+ if the corresponding complex part is None.
100
+
101
+ """
102
+ TMP_RES = Any # temporary result, should be some variant of
103
+ # tUnion[tTuple[Optional[MPF_TUP], Optional[MPF_TUP],
104
+ # Optional[int], Optional[int]],
105
+ # 'ComplexInfinity']
106
+ # but mypy reports error because it doesn't know as we know
107
+ # 1. re and re_acc are either both None or both MPF_TUP
108
+ # 2. sometimes the result can't be zoo
109
+
110
+ # type of the "options" parameter in internal evalf functions
111
+ OPT_DICT = tDict[str, Any]
112
+
113
+
114
+ def fastlog(x: Optional[MPF_TUP]) -> tUnion[int, Any]:
115
+ """Fast approximation of log2(x) for an mpf value tuple x.
116
+
117
+ Explanation
118
+ ===========
119
+
120
+ Calculated as exponent + width of mantissa. This is an
121
+ approximation for two reasons: 1) it gives the ceil(log2(abs(x)))
122
+ value and 2) it is too high by 1 in the case that x is an exact
123
+ power of 2. Although this is easy to remedy by testing to see if
124
+ the odd mpf mantissa is 1 (indicating that one was dealing with
125
+ an exact power of 2) that would decrease the speed and is not
126
+ necessary as this is only being used as an approximation for the
127
+ number of bits in x. The correct return value could be written as
128
+ "x[2] + (x[3] if x[1] != 1 else 0)".
129
+ Since mpf tuples always have an odd mantissa, no check is done
130
+ to see if the mantissa is a multiple of 2 (in which case the
131
+ result would be too large by 1).
132
+
133
+ Examples
134
+ ========
135
+
136
+ >>> from sympy import log
137
+ >>> from sympy.core.evalf import fastlog, bitcount
138
+ >>> s, m, e = 0, 5, 1
139
+ >>> bc = bitcount(m)
140
+ >>> n = [1, -1][s]*m*2**e
141
+ >>> n, (log(n)/log(2)).evalf(2), fastlog((s, m, e, bc))
142
+ (10, 3.3, 4)
143
+ """
144
+
145
+ if not x or x == fzero:
146
+ return MINUS_INF
147
+ return x[2] + x[3]
148
+
149
+
150
+ def pure_complex(v: 'Expr', or_real=False) -> tuple['Number', 'Number'] | None:
151
+ """Return a and b if v matches a + I*b where b is not zero and
152
+ a and b are Numbers, else None. If `or_real` is True then 0 will
153
+ be returned for `b` if `v` is a real number.
154
+
155
+ Examples
156
+ ========
157
+
158
+ >>> from sympy.core.evalf import pure_complex
159
+ >>> from sympy import sqrt, I, S
160
+ >>> a, b, surd = S(2), S(3), sqrt(2)
161
+ >>> pure_complex(a)
162
+ >>> pure_complex(a, or_real=True)
163
+ (2, 0)
164
+ >>> pure_complex(surd)
165
+ >>> pure_complex(a + b*I)
166
+ (2, 3)
167
+ >>> pure_complex(I)
168
+ (0, 1)
169
+ """
170
+ h, t = v.as_coeff_Add()
171
+ if t:
172
+ c, i = t.as_coeff_Mul()
173
+ if i is S.ImaginaryUnit:
174
+ return h, c
175
+ elif or_real:
176
+ return h, S.Zero
177
+ return None
178
+
179
+
180
+ # I don't know what this is, see function scaled_zero below
181
+ SCALED_ZERO_TUP = tTuple[List[int], int, int, int]
182
+
183
+
184
+ @overload
185
+ def scaled_zero(mag: SCALED_ZERO_TUP, sign=1) -> MPF_TUP:
186
+ ...
187
+ @overload
188
+ def scaled_zero(mag: int, sign=1) -> tTuple[SCALED_ZERO_TUP, int]:
189
+ ...
190
+ def scaled_zero(mag: tUnion[SCALED_ZERO_TUP, int], sign=1) -> \
191
+ tUnion[MPF_TUP, tTuple[SCALED_ZERO_TUP, int]]:
192
+ """Return an mpf representing a power of two with magnitude ``mag``
193
+ and -1 for precision. Or, if ``mag`` is a scaled_zero tuple, then just
194
+ remove the sign from within the list that it was initially wrapped
195
+ in.
196
+
197
+ Examples
198
+ ========
199
+
200
+ >>> from sympy.core.evalf import scaled_zero
201
+ >>> from sympy import Float
202
+ >>> z, p = scaled_zero(100)
203
+ >>> z, p
204
+ (([0], 1, 100, 1), -1)
205
+ >>> ok = scaled_zero(z)
206
+ >>> ok
207
+ (0, 1, 100, 1)
208
+ >>> Float(ok)
209
+ 1.26765060022823e+30
210
+ >>> Float(ok, p)
211
+ 0.e+30
212
+ >>> ok, p = scaled_zero(100, -1)
213
+ >>> Float(scaled_zero(ok), p)
214
+ -0.e+30
215
+ """
216
+ if isinstance(mag, tuple) and len(mag) == 4 and iszero(mag, scaled=True):
217
+ return (mag[0][0],) + mag[1:]
218
+ elif isinstance(mag, SYMPY_INTS):
219
+ if sign not in [-1, 1]:
220
+ raise ValueError('sign must be +/-1')
221
+ rv, p = mpf_shift(fone, mag), -1
222
+ s = 0 if sign == 1 else 1
223
+ rv = ([s],) + rv[1:]
224
+ return rv, p
225
+ else:
226
+ raise ValueError('scaled zero expects int or scaled_zero tuple.')
227
+
228
+
229
+ def iszero(mpf: tUnion[MPF_TUP, SCALED_ZERO_TUP, None], scaled=False) -> Optional[bool]:
230
+ if not scaled:
231
+ return not mpf or not mpf[1] and not mpf[-1]
232
+ return mpf and isinstance(mpf[0], list) and mpf[1] == mpf[-1] == 1
233
+
234
+
235
+ def complex_accuracy(result: TMP_RES) -> tUnion[int, Any]:
236
+ """
237
+ Returns relative accuracy of a complex number with given accuracies
238
+ for the real and imaginary parts. The relative accuracy is defined
239
+ in the complex norm sense as ||z|+|error|| / |z| where error
240
+ is equal to (real absolute error) + (imag absolute error)*i.
241
+
242
+ The full expression for the (logarithmic) error can be approximated
243
+ easily by using the max norm to approximate the complex norm.
244
+
245
+ In the worst case (re and im equal), this is wrong by a factor
246
+ sqrt(2), or by log2(sqrt(2)) = 0.5 bit.
247
+ """
248
+ if result is S.ComplexInfinity:
249
+ return INF
250
+ re, im, re_acc, im_acc = result
251
+ if not im:
252
+ if not re:
253
+ return INF
254
+ return re_acc
255
+ if not re:
256
+ return im_acc
257
+ re_size = fastlog(re)
258
+ im_size = fastlog(im)
259
+ absolute_error = max(re_size - re_acc, im_size - im_acc)
260
+ relative_error = absolute_error - max(re_size, im_size)
261
+ return -relative_error
262
+
263
+
264
+ def get_abs(expr: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
265
+ result = evalf(expr, prec + 2, options)
266
+ if result is S.ComplexInfinity:
267
+ return finf, None, prec, None
268
+ re, im, re_acc, im_acc = result
269
+ if not re:
270
+ re, re_acc, im, im_acc = im, im_acc, re, re_acc
271
+ if im:
272
+ if expr.is_number:
273
+ abs_expr, _, acc, _ = evalf(abs(N(expr, prec + 2)),
274
+ prec + 2, options)
275
+ return abs_expr, None, acc, None
276
+ else:
277
+ if 'subs' in options:
278
+ return libmp.mpc_abs((re, im), prec), None, re_acc, None
279
+ return abs(expr), None, prec, None
280
+ elif re:
281
+ return mpf_abs(re), None, re_acc, None
282
+ else:
283
+ return None, None, None, None
284
+
285
+
286
+ def get_complex_part(expr: 'Expr', no: int, prec: int, options: OPT_DICT) -> TMP_RES:
287
+ """no = 0 for real part, no = 1 for imaginary part"""
288
+ workprec = prec
289
+ i = 0
290
+ while 1:
291
+ res = evalf(expr, workprec, options)
292
+ if res is S.ComplexInfinity:
293
+ return fnan, None, prec, None
294
+ value, accuracy = res[no::2]
295
+ # XXX is the last one correct? Consider re((1+I)**2).n()
296
+ if (not value) or accuracy >= prec or -value[2] > prec:
297
+ return value, None, accuracy, None
298
+ workprec += max(30, 2**i)
299
+ i += 1
300
+
301
+
302
+ def evalf_abs(expr: 'Abs', prec: int, options: OPT_DICT) -> TMP_RES:
303
+ return get_abs(expr.args[0], prec, options)
304
+
305
+
306
+ def evalf_re(expr: 're', prec: int, options: OPT_DICT) -> TMP_RES:
307
+ return get_complex_part(expr.args[0], 0, prec, options)
308
+
309
+
310
+ def evalf_im(expr: 'im', prec: int, options: OPT_DICT) -> TMP_RES:
311
+ return get_complex_part(expr.args[0], 1, prec, options)
312
+
313
+
314
+ def finalize_complex(re: MPF_TUP, im: MPF_TUP, prec: int) -> TMP_RES:
315
+ if re == fzero and im == fzero:
316
+ raise ValueError("got complex zero with unknown accuracy")
317
+ elif re == fzero:
318
+ return None, im, None, prec
319
+ elif im == fzero:
320
+ return re, None, prec, None
321
+
322
+ size_re = fastlog(re)
323
+ size_im = fastlog(im)
324
+ if size_re > size_im:
325
+ re_acc = prec
326
+ im_acc = prec + min(-(size_re - size_im), 0)
327
+ else:
328
+ im_acc = prec
329
+ re_acc = prec + min(-(size_im - size_re), 0)
330
+ return re, im, re_acc, im_acc
331
+
332
+
333
+ def chop_parts(value: TMP_RES, prec: int) -> TMP_RES:
334
+ """
335
+ Chop off tiny real or complex parts.
336
+ """
337
+ if value is S.ComplexInfinity:
338
+ return value
339
+ re, im, re_acc, im_acc = value
340
+ # Method 1: chop based on absolute value
341
+ if re and re not in _infs_nan and (fastlog(re) < -prec + 4):
342
+ re, re_acc = None, None
343
+ if im and im not in _infs_nan and (fastlog(im) < -prec + 4):
344
+ im, im_acc = None, None
345
+ # Method 2: chop if inaccurate and relatively small
346
+ if re and im:
347
+ delta = fastlog(re) - fastlog(im)
348
+ if re_acc < 2 and (delta - re_acc <= -prec + 4):
349
+ re, re_acc = None, None
350
+ if im_acc < 2 and (delta - im_acc >= prec - 4):
351
+ im, im_acc = None, None
352
+ return re, im, re_acc, im_acc
353
+
354
+
355
+ def check_target(expr: 'Expr', result: TMP_RES, prec: int):
356
+ a = complex_accuracy(result)
357
+ if a < prec:
358
+ raise PrecisionExhausted("Failed to distinguish the expression: \n\n%s\n\n"
359
+ "from zero. Try simplifying the input, using chop=True, or providing "
360
+ "a higher maxn for evalf" % (expr))
361
+
362
+
363
+ def get_integer_part(expr: 'Expr', no: int, options: OPT_DICT, return_ints=False) -> \
364
+ tUnion[TMP_RES, tTuple[int, int]]:
365
+ """
366
+ With no = 1, computes ceiling(expr)
367
+ With no = -1, computes floor(expr)
368
+
369
+ Note: this function either gives the exact result or signals failure.
370
+ """
371
+ from sympy.functions.elementary.complexes import re, im
372
+ # The expression is likely less than 2^30 or so
373
+ assumed_size = 30
374
+ result = evalf(expr, assumed_size, options)
375
+ if result is S.ComplexInfinity:
376
+ raise ValueError("Cannot get integer part of Complex Infinity")
377
+ ire, iim, ire_acc, iim_acc = result
378
+
379
+ # We now know the size, so we can calculate how much extra precision
380
+ # (if any) is needed to get within the nearest integer
381
+ if ire and iim:
382
+ gap = max(fastlog(ire) - ire_acc, fastlog(iim) - iim_acc)
383
+ elif ire:
384
+ gap = fastlog(ire) - ire_acc
385
+ elif iim:
386
+ gap = fastlog(iim) - iim_acc
387
+ else:
388
+ # ... or maybe the expression was exactly zero
389
+ if return_ints:
390
+ return 0, 0
391
+ else:
392
+ return None, None, None, None
393
+
394
+ margin = 10
395
+
396
+ if gap >= -margin:
397
+ prec = margin + assumed_size + gap
398
+ ire, iim, ire_acc, iim_acc = evalf(
399
+ expr, prec, options)
400
+ else:
401
+ prec = assumed_size
402
+
403
+ # We can now easily find the nearest integer, but to find floor/ceil, we
404
+ # must also calculate whether the difference to the nearest integer is
405
+ # positive or negative (which may fail if very close).
406
+ def calc_part(re_im: 'Expr', nexpr: MPF_TUP):
407
+ from .add import Add
408
+ _, _, exponent, _ = nexpr
409
+ is_int = exponent == 0
410
+ nint = int(to_int(nexpr, rnd))
411
+ if is_int:
412
+ # make sure that we had enough precision to distinguish
413
+ # between nint and the re or im part (re_im) of expr that
414
+ # was passed to calc_part
415
+ ire, iim, ire_acc, iim_acc = evalf(
416
+ re_im - nint, 10, options) # don't need much precision
417
+ assert not iim
418
+ size = -fastlog(ire) + 2 # -ve b/c ire is less than 1
419
+ if size > prec:
420
+ ire, iim, ire_acc, iim_acc = evalf(
421
+ re_im, size, options)
422
+ assert not iim
423
+ nexpr = ire
424
+ nint = int(to_int(nexpr, rnd))
425
+ _, _, new_exp, _ = ire
426
+ is_int = new_exp == 0
427
+ if not is_int:
428
+ # if there are subs and they all contain integer re/im parts
429
+ # then we can (hopefully) safely substitute them into the
430
+ # expression
431
+ s = options.get('subs', False)
432
+ if s:
433
+ doit = True
434
+ # use strict=False with as_int because we take
435
+ # 2.0 == 2
436
+ for v in s.values():
437
+ try:
438
+ as_int(v, strict=False)
439
+ except ValueError:
440
+ try:
441
+ [as_int(i, strict=False) for i in v.as_real_imag()]
442
+ continue
443
+ except (ValueError, AttributeError):
444
+ doit = False
445
+ break
446
+ if doit:
447
+ re_im = re_im.subs(s)
448
+
449
+ re_im = Add(re_im, -nint, evaluate=False)
450
+ x, _, x_acc, _ = evalf(re_im, 10, options)
451
+ try:
452
+ check_target(re_im, (x, None, x_acc, None), 3)
453
+ except PrecisionExhausted:
454
+ if not re_im.equals(0):
455
+ raise PrecisionExhausted
456
+ x = fzero
457
+ nint += int(no*(mpf_cmp(x or fzero, fzero) == no))
458
+ nint = from_int(nint)
459
+ return nint, INF
460
+
461
+ re_, im_, re_acc, im_acc = None, None, None, None
462
+
463
+ if ire:
464
+ re_, re_acc = calc_part(re(expr, evaluate=False), ire)
465
+ if iim:
466
+ im_, im_acc = calc_part(im(expr, evaluate=False), iim)
467
+
468
+ if return_ints:
469
+ return int(to_int(re_ or fzero)), int(to_int(im_ or fzero))
470
+ return re_, im_, re_acc, im_acc
471
+
472
+
473
+ def evalf_ceiling(expr: 'ceiling', prec: int, options: OPT_DICT) -> TMP_RES:
474
+ return get_integer_part(expr.args[0], 1, options)
475
+
476
+
477
+ def evalf_floor(expr: 'floor', prec: int, options: OPT_DICT) -> TMP_RES:
478
+ return get_integer_part(expr.args[0], -1, options)
479
+
480
+
481
+ def evalf_float(expr: 'Float', prec: int, options: OPT_DICT) -> TMP_RES:
482
+ return expr._mpf_, None, prec, None
483
+
484
+
485
+ def evalf_rational(expr: 'Rational', prec: int, options: OPT_DICT) -> TMP_RES:
486
+ return from_rational(expr.p, expr.q, prec), None, prec, None
487
+
488
+
489
+ def evalf_integer(expr: 'Integer', prec: int, options: OPT_DICT) -> TMP_RES:
490
+ return from_int(expr.p, prec), None, prec, None
491
+
492
+ #----------------------------------------------------------------------------#
493
+ # #
494
+ # Arithmetic operations #
495
+ # #
496
+ #----------------------------------------------------------------------------#
497
+
498
+
499
+ def add_terms(terms: list, prec: int, target_prec: int) -> \
500
+ tTuple[tUnion[MPF_TUP, SCALED_ZERO_TUP, None], Optional[int]]:
501
+ """
502
+ Helper for evalf_add. Adds a list of (mpfval, accuracy) terms.
503
+
504
+ Returns
505
+ =======
506
+
507
+ - None, None if there are no non-zero terms;
508
+ - terms[0] if there is only 1 term;
509
+ - scaled_zero if the sum of the terms produces a zero by cancellation
510
+ e.g. mpfs representing 1 and -1 would produce a scaled zero which need
511
+ special handling since they are not actually zero and they are purposely
512
+ malformed to ensure that they cannot be used in anything but accuracy
513
+ calculations;
514
+ - a tuple that is scaled to target_prec that corresponds to the
515
+ sum of the terms.
516
+
517
+ The returned mpf tuple will be normalized to target_prec; the input
518
+ prec is used to define the working precision.
519
+
520
+ XXX explain why this is needed and why one cannot just loop using mpf_add
521
+ """
522
+
523
+ terms = [t for t in terms if not iszero(t[0])]
524
+ if not terms:
525
+ return None, None
526
+ elif len(terms) == 1:
527
+ return terms[0]
528
+
529
+ # see if any argument is NaN or oo and thus warrants a special return
530
+ special = []
531
+ from .numbers import Float
532
+ for t in terms:
533
+ arg = Float._new(t[0], 1)
534
+ if arg is S.NaN or arg.is_infinite:
535
+ special.append(arg)
536
+ if special:
537
+ from .add import Add
538
+ rv = evalf(Add(*special), prec + 4, {})
539
+ return rv[0], rv[2]
540
+
541
+ working_prec = 2*prec
542
+ sum_man, sum_exp = 0, 0
543
+ absolute_err: List[int] = []
544
+
545
+ for x, accuracy in terms:
546
+ sign, man, exp, bc = x
547
+ if sign:
548
+ man = -man
549
+ absolute_err.append(bc + exp - accuracy)
550
+ delta = exp - sum_exp
551
+ if exp >= sum_exp:
552
+ # x much larger than existing sum?
553
+ # first: quick test
554
+ if ((delta > working_prec) and
555
+ ((not sum_man) or
556
+ delta - bitcount(abs(sum_man)) > working_prec)):
557
+ sum_man = man
558
+ sum_exp = exp
559
+ else:
560
+ sum_man += (man << delta)
561
+ else:
562
+ delta = -delta
563
+ # x much smaller than existing sum?
564
+ if delta - bc > working_prec:
565
+ if not sum_man:
566
+ sum_man, sum_exp = man, exp
567
+ else:
568
+ sum_man = (sum_man << delta) + man
569
+ sum_exp = exp
570
+ absolute_error = max(absolute_err)
571
+ if not sum_man:
572
+ return scaled_zero(absolute_error)
573
+ if sum_man < 0:
574
+ sum_sign = 1
575
+ sum_man = -sum_man
576
+ else:
577
+ sum_sign = 0
578
+ sum_bc = bitcount(sum_man)
579
+ sum_accuracy = sum_exp + sum_bc - absolute_error
580
+ r = normalize(sum_sign, sum_man, sum_exp, sum_bc, target_prec,
581
+ rnd), sum_accuracy
582
+ return r
583
+
584
+
585
+ def evalf_add(v: 'Add', prec: int, options: OPT_DICT) -> TMP_RES:
586
+ res = pure_complex(v)
587
+ if res:
588
+ h, c = res
589
+ re, _, re_acc, _ = evalf(h, prec, options)
590
+ im, _, im_acc, _ = evalf(c, prec, options)
591
+ return re, im, re_acc, im_acc
592
+
593
+ oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC)
594
+
595
+ i = 0
596
+ target_prec = prec
597
+ while 1:
598
+ options['maxprec'] = min(oldmaxprec, 2*prec)
599
+
600
+ terms = [evalf(arg, prec + 10, options) for arg in v.args]
601
+ n = terms.count(S.ComplexInfinity)
602
+ if n >= 2:
603
+ return fnan, None, prec, None
604
+ re, re_acc = add_terms(
605
+ [a[0::2] for a in terms if isinstance(a, tuple) and a[0]], prec, target_prec)
606
+ im, im_acc = add_terms(
607
+ [a[1::2] for a in terms if isinstance(a, tuple) and a[1]], prec, target_prec)
608
+ if n == 1:
609
+ if re in (finf, fninf, fnan) or im in (finf, fninf, fnan):
610
+ return fnan, None, prec, None
611
+ return S.ComplexInfinity
612
+ acc = complex_accuracy((re, im, re_acc, im_acc))
613
+ if acc >= target_prec:
614
+ if options.get('verbose'):
615
+ print("ADD: wanted", target_prec, "accurate bits, got", re_acc, im_acc)
616
+ break
617
+ else:
618
+ if (prec - target_prec) > options['maxprec']:
619
+ break
620
+
621
+ prec = prec + max(10 + 2**i, target_prec - acc)
622
+ i += 1
623
+ if options.get('verbose'):
624
+ print("ADD: restarting with prec", prec)
625
+
626
+ options['maxprec'] = oldmaxprec
627
+ if iszero(re, scaled=True):
628
+ re = scaled_zero(re)
629
+ if iszero(im, scaled=True):
630
+ im = scaled_zero(im)
631
+ return re, im, re_acc, im_acc
632
+
633
+
634
+ def evalf_mul(v: 'Mul', prec: int, options: OPT_DICT) -> TMP_RES:
635
+ res = pure_complex(v)
636
+ if res:
637
+ # the only pure complex that is a mul is h*I
638
+ _, h = res
639
+ im, _, im_acc, _ = evalf(h, prec, options)
640
+ return None, im, None, im_acc
641
+ args = list(v.args)
642
+
643
+ # see if any argument is NaN or oo and thus warrants a special return
644
+ has_zero = False
645
+ special = []
646
+ from .numbers import Float
647
+ for arg in args:
648
+ result = evalf(arg, prec, options)
649
+ if result is S.ComplexInfinity:
650
+ special.append(result)
651
+ continue
652
+ if result[0] is None:
653
+ if result[1] is None:
654
+ has_zero = True
655
+ continue
656
+ num = Float._new(result[0], 1)
657
+ if num is S.NaN:
658
+ return fnan, None, prec, None
659
+ if num.is_infinite:
660
+ special.append(num)
661
+ if special:
662
+ if has_zero:
663
+ return fnan, None, prec, None
664
+ from .mul import Mul
665
+ return evalf(Mul(*special), prec + 4, {})
666
+ if has_zero:
667
+ return None, None, None, None
668
+
669
+ # With guard digits, multiplication in the real case does not destroy
670
+ # accuracy. This is also true in the complex case when considering the
671
+ # total accuracy; however accuracy for the real or imaginary parts
672
+ # separately may be lower.
673
+ acc = prec
674
+
675
+ # XXX: big overestimate
676
+ working_prec = prec + len(args) + 5
677
+
678
+ # Empty product is 1
679
+ start = man, exp, bc = MPZ(1), 0, 1
680
+
681
+ # First, we multiply all pure real or pure imaginary numbers.
682
+ # direction tells us that the result should be multiplied by
683
+ # I**direction; all other numbers get put into complex_factors
684
+ # to be multiplied out after the first phase.
685
+ last = len(args)
686
+ direction = 0
687
+ args.append(S.One)
688
+ complex_factors = []
689
+
690
+ for i, arg in enumerate(args):
691
+ if i != last and pure_complex(arg):
692
+ args[-1] = (args[-1]*arg).expand()
693
+ continue
694
+ elif i == last and arg is S.One:
695
+ continue
696
+ re, im, re_acc, im_acc = evalf(arg, working_prec, options)
697
+ if re and im:
698
+ complex_factors.append((re, im, re_acc, im_acc))
699
+ continue
700
+ elif re:
701
+ (s, m, e, b), w_acc = re, re_acc
702
+ elif im:
703
+ (s, m, e, b), w_acc = im, im_acc
704
+ direction += 1
705
+ else:
706
+ return None, None, None, None
707
+ direction += 2*s
708
+ man *= m
709
+ exp += e
710
+ bc += b
711
+ while bc > 3*working_prec:
712
+ man >>= working_prec
713
+ exp += working_prec
714
+ bc -= working_prec
715
+ acc = min(acc, w_acc)
716
+ sign = (direction & 2) >> 1
717
+ if not complex_factors:
718
+ v = normalize(sign, man, exp, bitcount(man), prec, rnd)
719
+ # multiply by i
720
+ if direction & 1:
721
+ return None, v, None, acc
722
+ else:
723
+ return v, None, acc, None
724
+ else:
725
+ # initialize with the first term
726
+ if (man, exp, bc) != start:
727
+ # there was a real part; give it an imaginary part
728
+ re, im = (sign, man, exp, bitcount(man)), (0, MPZ(0), 0, 0)
729
+ i0 = 0
730
+ else:
731
+ # there is no real part to start (other than the starting 1)
732
+ wre, wim, wre_acc, wim_acc = complex_factors[0]
733
+ acc = min(acc,
734
+ complex_accuracy((wre, wim, wre_acc, wim_acc)))
735
+ re = wre
736
+ im = wim
737
+ i0 = 1
738
+
739
+ for wre, wim, wre_acc, wim_acc in complex_factors[i0:]:
740
+ # acc is the overall accuracy of the product; we aren't
741
+ # computing exact accuracies of the product.
742
+ acc = min(acc,
743
+ complex_accuracy((wre, wim, wre_acc, wim_acc)))
744
+
745
+ use_prec = working_prec
746
+ A = mpf_mul(re, wre, use_prec)
747
+ B = mpf_mul(mpf_neg(im), wim, use_prec)
748
+ C = mpf_mul(re, wim, use_prec)
749
+ D = mpf_mul(im, wre, use_prec)
750
+ re = mpf_add(A, B, use_prec)
751
+ im = mpf_add(C, D, use_prec)
752
+ if options.get('verbose'):
753
+ print("MUL: wanted", prec, "accurate bits, got", acc)
754
+ # multiply by I
755
+ if direction & 1:
756
+ re, im = mpf_neg(im), re
757
+ return re, im, acc, acc
758
+
759
+
760
+ def evalf_pow(v: 'Pow', prec: int, options) -> TMP_RES:
761
+
762
+ target_prec = prec
763
+ base, exp = v.args
764
+
765
+ # We handle x**n separately. This has two purposes: 1) it is much
766
+ # faster, because we avoid calling evalf on the exponent, and 2) it
767
+ # allows better handling of real/imaginary parts that are exactly zero
768
+ if exp.is_Integer:
769
+ p: int = exp.p # type: ignore
770
+ # Exact
771
+ if not p:
772
+ return fone, None, prec, None
773
+ # Exponentiation by p magnifies relative error by |p|, so the
774
+ # base must be evaluated with increased precision if p is large
775
+ prec += int(math.log(abs(p), 2))
776
+ result = evalf(base, prec + 5, options)
777
+ if result is S.ComplexInfinity:
778
+ if p < 0:
779
+ return None, None, None, None
780
+ return result
781
+ re, im, re_acc, im_acc = result
782
+ # Real to integer power
783
+ if re and not im:
784
+ return mpf_pow_int(re, p, target_prec), None, target_prec, None
785
+ # (x*I)**n = I**n * x**n
786
+ if im and not re:
787
+ z = mpf_pow_int(im, p, target_prec)
788
+ case = p % 4
789
+ if case == 0:
790
+ return z, None, target_prec, None
791
+ if case == 1:
792
+ return None, z, None, target_prec
793
+ if case == 2:
794
+ return mpf_neg(z), None, target_prec, None
795
+ if case == 3:
796
+ return None, mpf_neg(z), None, target_prec
797
+ # Zero raised to an integer power
798
+ if not re:
799
+ if p < 0:
800
+ return S.ComplexInfinity
801
+ return None, None, None, None
802
+ # General complex number to arbitrary integer power
803
+ re, im = libmp.mpc_pow_int((re, im), p, prec)
804
+ # Assumes full accuracy in input
805
+ return finalize_complex(re, im, target_prec)
806
+
807
+ result = evalf(base, prec + 5, options)
808
+ if result is S.ComplexInfinity:
809
+ if exp.is_Rational:
810
+ if exp < 0:
811
+ return None, None, None, None
812
+ return result
813
+ raise NotImplementedError
814
+
815
+ # Pure square root
816
+ if exp is S.Half:
817
+ xre, xim, _, _ = result
818
+ # General complex square root
819
+ if xim:
820
+ re, im = libmp.mpc_sqrt((xre or fzero, xim), prec)
821
+ return finalize_complex(re, im, prec)
822
+ if not xre:
823
+ return None, None, None, None
824
+ # Square root of a negative real number
825
+ if mpf_lt(xre, fzero):
826
+ return None, mpf_sqrt(mpf_neg(xre), prec), None, prec
827
+ # Positive square root
828
+ return mpf_sqrt(xre, prec), None, prec, None
829
+
830
+ # We first evaluate the exponent to find its magnitude
831
+ # This determines the working precision that must be used
832
+ prec += 10
833
+ result = evalf(exp, prec, options)
834
+ if result is S.ComplexInfinity:
835
+ return fnan, None, prec, None
836
+ yre, yim, _, _ = result
837
+ # Special cases: x**0
838
+ if not (yre or yim):
839
+ return fone, None, prec, None
840
+
841
+ ysize = fastlog(yre)
842
+ # Restart if too big
843
+ # XXX: prec + ysize might exceed maxprec
844
+ if ysize > 5:
845
+ prec += ysize
846
+ yre, yim, _, _ = evalf(exp, prec, options)
847
+
848
+ # Pure exponential function; no need to evalf the base
849
+ if base is S.Exp1:
850
+ if yim:
851
+ re, im = libmp.mpc_exp((yre or fzero, yim), prec)
852
+ return finalize_complex(re, im, target_prec)
853
+ return mpf_exp(yre, target_prec), None, target_prec, None
854
+
855
+ xre, xim, _, _ = evalf(base, prec + 5, options)
856
+ # 0**y
857
+ if not (xre or xim):
858
+ if yim:
859
+ return fnan, None, prec, None
860
+ if yre[0] == 1: # y < 0
861
+ return S.ComplexInfinity
862
+ return None, None, None, None
863
+
864
+ # (real ** complex) or (complex ** complex)
865
+ if yim:
866
+ re, im = libmp.mpc_pow(
867
+ (xre or fzero, xim or fzero), (yre or fzero, yim),
868
+ target_prec)
869
+ return finalize_complex(re, im, target_prec)
870
+ # complex ** real
871
+ if xim:
872
+ re, im = libmp.mpc_pow_mpf((xre or fzero, xim), yre, target_prec)
873
+ return finalize_complex(re, im, target_prec)
874
+ # negative ** real
875
+ elif mpf_lt(xre, fzero):
876
+ re, im = libmp.mpc_pow_mpf((xre, fzero), yre, target_prec)
877
+ return finalize_complex(re, im, target_prec)
878
+ # positive ** real
879
+ else:
880
+ return mpf_pow(xre, yre, target_prec), None, target_prec, None
881
+
882
+
883
+ #----------------------------------------------------------------------------#
884
+ # #
885
+ # Special functions #
886
+ # #
887
+ #----------------------------------------------------------------------------#
888
+
889
+
890
+ def evalf_exp(expr: 'exp', prec: int, options: OPT_DICT) -> TMP_RES:
891
+ from .power import Pow
892
+ return evalf_pow(Pow(S.Exp1, expr.exp, evaluate=False), prec, options)
893
+
894
+
895
+ def evalf_trig(v: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
896
+ """
897
+ This function handles sin and cos of complex arguments.
898
+
899
+ TODO: should also handle tan of complex arguments.
900
+ """
901
+ from sympy.functions.elementary.trigonometric import cos, sin
902
+ if isinstance(v, cos):
903
+ func = mpf_cos
904
+ elif isinstance(v, sin):
905
+ func = mpf_sin
906
+ else:
907
+ raise NotImplementedError
908
+ arg = v.args[0]
909
+ # 20 extra bits is possibly overkill. It does make the need
910
+ # to restart very unlikely
911
+ xprec = prec + 20
912
+ re, im, re_acc, im_acc = evalf(arg, xprec, options)
913
+ if im:
914
+ if 'subs' in options:
915
+ v = v.subs(options['subs'])
916
+ return evalf(v._eval_evalf(prec), prec, options)
917
+ if not re:
918
+ if isinstance(v, cos):
919
+ return fone, None, prec, None
920
+ elif isinstance(v, sin):
921
+ return None, None, None, None
922
+ else:
923
+ raise NotImplementedError
924
+ # For trigonometric functions, we are interested in the
925
+ # fixed-point (absolute) accuracy of the argument.
926
+ xsize = fastlog(re)
927
+ # Magnitude <= 1.0. OK to compute directly, because there is no
928
+ # danger of hitting the first root of cos (with sin, magnitude
929
+ # <= 2.0 would actually be ok)
930
+ if xsize < 1:
931
+ return func(re, prec, rnd), None, prec, None
932
+ # Very large
933
+ if xsize >= 10:
934
+ xprec = prec + xsize
935
+ re, im, re_acc, im_acc = evalf(arg, xprec, options)
936
+ # Need to repeat in case the argument is very close to a
937
+ # multiple of pi (or pi/2), hitting close to a root
938
+ while 1:
939
+ y = func(re, prec, rnd)
940
+ ysize = fastlog(y)
941
+ gap = -ysize
942
+ accuracy = (xprec - xsize) - gap
943
+ if accuracy < prec:
944
+ if options.get('verbose'):
945
+ print("SIN/COS", accuracy, "wanted", prec, "gap", gap)
946
+ print(to_str(y, 10))
947
+ if xprec > options.get('maxprec', DEFAULT_MAXPREC):
948
+ return y, None, accuracy, None
949
+ xprec += gap
950
+ re, im, re_acc, im_acc = evalf(arg, xprec, options)
951
+ continue
952
+ else:
953
+ return y, None, prec, None
954
+
955
+
956
+ def evalf_log(expr: 'log', prec: int, options: OPT_DICT) -> TMP_RES:
957
+ if len(expr.args)>1:
958
+ expr = expr.doit()
959
+ return evalf(expr, prec, options)
960
+ arg = expr.args[0]
961
+ workprec = prec + 10
962
+ result = evalf(arg, workprec, options)
963
+ if result is S.ComplexInfinity:
964
+ return result
965
+ xre, xim, xacc, _ = result
966
+
967
+ # evalf can return NoneTypes if chop=True
968
+ # issue 18516, 19623
969
+ if xre is xim is None:
970
+ # Dear reviewer, I do not know what -inf is;
971
+ # it looks to be (1, 0, -789, -3)
972
+ # but I'm not sure in general,
973
+ # so we just let mpmath figure
974
+ # it out by taking log of 0 directly.
975
+ # It would be better to return -inf instead.
976
+ xre = fzero
977
+
978
+ if xim:
979
+ from sympy.functions.elementary.complexes import Abs
980
+ from sympy.functions.elementary.exponential import log
981
+
982
+ # XXX: use get_abs etc instead
983
+ re = evalf_log(
984
+ log(Abs(arg, evaluate=False), evaluate=False), prec, options)
985
+ im = mpf_atan2(xim, xre or fzero, prec)
986
+ return re[0], im, re[2], prec
987
+
988
+ imaginary_term = (mpf_cmp(xre, fzero) < 0)
989
+
990
+ re = mpf_log(mpf_abs(xre), prec, rnd)
991
+ size = fastlog(re)
992
+ if prec - size > workprec and re != fzero:
993
+ from .add import Add
994
+ # We actually need to compute 1+x accurately, not x
995
+ add = Add(S.NegativeOne, arg, evaluate=False)
996
+ xre, xim, _, _ = evalf_add(add, prec, options)
997
+ prec2 = workprec - fastlog(xre)
998
+ # xre is now x - 1 so we add 1 back here to calculate x
999
+ re = mpf_log(mpf_abs(mpf_add(xre, fone, prec2)), prec, rnd)
1000
+
1001
+ re_acc = prec
1002
+
1003
+ if imaginary_term:
1004
+ return re, mpf_pi(prec), re_acc, prec
1005
+ else:
1006
+ return re, None, re_acc, None
1007
+
1008
+
1009
+ def evalf_atan(v: 'atan', prec: int, options: OPT_DICT) -> TMP_RES:
1010
+ arg = v.args[0]
1011
+ xre, xim, reacc, imacc = evalf(arg, prec + 5, options)
1012
+ if xre is xim is None:
1013
+ return (None,)*4
1014
+ if xim:
1015
+ raise NotImplementedError
1016
+ return mpf_atan(xre, prec, rnd), None, prec, None
1017
+
1018
+
1019
+ def evalf_subs(prec: int, subs: dict) -> dict:
1020
+ """ Change all Float entries in `subs` to have precision prec. """
1021
+ newsubs = {}
1022
+ for a, b in subs.items():
1023
+ b = S(b)
1024
+ if b.is_Float:
1025
+ b = b._eval_evalf(prec)
1026
+ newsubs[a] = b
1027
+ return newsubs
1028
+
1029
+
1030
+ def evalf_piecewise(expr: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
1031
+ from .numbers import Float, Integer
1032
+ if 'subs' in options:
1033
+ expr = expr.subs(evalf_subs(prec, options['subs']))
1034
+ newopts = options.copy()
1035
+ del newopts['subs']
1036
+ if hasattr(expr, 'func'):
1037
+ return evalf(expr, prec, newopts)
1038
+ if isinstance(expr, float):
1039
+ return evalf(Float(expr), prec, newopts)
1040
+ if isinstance(expr, int):
1041
+ return evalf(Integer(expr), prec, newopts)
1042
+
1043
+ # We still have undefined symbols
1044
+ raise NotImplementedError
1045
+
1046
+
1047
+ def evalf_alg_num(a: 'AlgebraicNumber', prec: int, options: OPT_DICT) -> TMP_RES:
1048
+ return evalf(a.to_root(), prec, options)
1049
+
1050
+ #----------------------------------------------------------------------------#
1051
+ # #
1052
+ # High-level operations #
1053
+ # #
1054
+ #----------------------------------------------------------------------------#
1055
+
1056
+
1057
+ def as_mpmath(x: Any, prec: int, options: OPT_DICT) -> tUnion[mpc, mpf]:
1058
+ from .numbers import Infinity, NegativeInfinity, Zero
1059
+ x = sympify(x)
1060
+ if isinstance(x, Zero) or x == 0.0:
1061
+ return mpf(0)
1062
+ if isinstance(x, Infinity):
1063
+ return mpf('inf')
1064
+ if isinstance(x, NegativeInfinity):
1065
+ return mpf('-inf')
1066
+ # XXX
1067
+ result = evalf(x, prec, options)
1068
+ return quad_to_mpmath(result)
1069
+
1070
+
1071
+ def do_integral(expr: 'Integral', prec: int, options: OPT_DICT) -> TMP_RES:
1072
+ func = expr.args[0]
1073
+ x, xlow, xhigh = expr.args[1]
1074
+ if xlow == xhigh:
1075
+ xlow = xhigh = 0
1076
+ elif x not in func.free_symbols:
1077
+ # only the difference in limits matters in this case
1078
+ # so if there is a symbol in common that will cancel
1079
+ # out when taking the difference, then use that
1080
+ # difference
1081
+ if xhigh.free_symbols & xlow.free_symbols:
1082
+ diff = xhigh - xlow
1083
+ if diff.is_number:
1084
+ xlow, xhigh = 0, diff
1085
+
1086
+ oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC)
1087
+ options['maxprec'] = min(oldmaxprec, 2*prec)
1088
+
1089
+ with workprec(prec + 5):
1090
+ xlow = as_mpmath(xlow, prec + 15, options)
1091
+ xhigh = as_mpmath(xhigh, prec + 15, options)
1092
+
1093
+ # Integration is like summation, and we can phone home from
1094
+ # the integrand function to update accuracy summation style
1095
+ # Note that this accuracy is inaccurate, since it fails
1096
+ # to account for the variable quadrature weights,
1097
+ # but it is better than nothing
1098
+
1099
+ from sympy.functions.elementary.trigonometric import cos, sin
1100
+ from .symbol import Wild
1101
+
1102
+ have_part = [False, False]
1103
+ max_real_term: tUnion[float, int] = MINUS_INF
1104
+ max_imag_term: tUnion[float, int] = MINUS_INF
1105
+
1106
+ def f(t: 'Expr') -> tUnion[mpc, mpf]:
1107
+ nonlocal max_real_term, max_imag_term
1108
+ re, im, re_acc, im_acc = evalf(func, mp.prec, {'subs': {x: t}})
1109
+
1110
+ have_part[0] = re or have_part[0]
1111
+ have_part[1] = im or have_part[1]
1112
+
1113
+ max_real_term = max(max_real_term, fastlog(re))
1114
+ max_imag_term = max(max_imag_term, fastlog(im))
1115
+
1116
+ if im:
1117
+ return mpc(re or fzero, im)
1118
+ return mpf(re or fzero)
1119
+
1120
+ if options.get('quad') == 'osc':
1121
+ A = Wild('A', exclude=[x])
1122
+ B = Wild('B', exclude=[x])
1123
+ D = Wild('D')
1124
+ m = func.match(cos(A*x + B)*D)
1125
+ if not m:
1126
+ m = func.match(sin(A*x + B)*D)
1127
+ if not m:
1128
+ raise ValueError("An integrand of the form sin(A*x+B)*f(x) "
1129
+ "or cos(A*x+B)*f(x) is required for oscillatory quadrature")
1130
+ period = as_mpmath(2*S.Pi/m[A], prec + 15, options)
1131
+ result = quadosc(f, [xlow, xhigh], period=period)
1132
+ # XXX: quadosc does not do error detection yet
1133
+ quadrature_error = MINUS_INF
1134
+ else:
1135
+ result, quadrature_err = quadts(f, [xlow, xhigh], error=1)
1136
+ quadrature_error = fastlog(quadrature_err._mpf_)
1137
+
1138
+ options['maxprec'] = oldmaxprec
1139
+
1140
+ if have_part[0]:
1141
+ re: Optional[MPF_TUP] = result.real._mpf_
1142
+ re_acc: Optional[int]
1143
+ if re == fzero:
1144
+ re_s, re_acc = scaled_zero(int(-max(prec, max_real_term, quadrature_error)))
1145
+ re = scaled_zero(re_s) # handled ok in evalf_integral
1146
+ else:
1147
+ re_acc = int(-max(max_real_term - fastlog(re) - prec, quadrature_error))
1148
+ else:
1149
+ re, re_acc = None, None
1150
+
1151
+ if have_part[1]:
1152
+ im: Optional[MPF_TUP] = result.imag._mpf_
1153
+ im_acc: Optional[int]
1154
+ if im == fzero:
1155
+ im_s, im_acc = scaled_zero(int(-max(prec, max_imag_term, quadrature_error)))
1156
+ im = scaled_zero(im_s) # handled ok in evalf_integral
1157
+ else:
1158
+ im_acc = int(-max(max_imag_term - fastlog(im) - prec, quadrature_error))
1159
+ else:
1160
+ im, im_acc = None, None
1161
+
1162
+ result = re, im, re_acc, im_acc
1163
+ return result
1164
+
1165
+
1166
+ def evalf_integral(expr: 'Integral', prec: int, options: OPT_DICT) -> TMP_RES:
1167
+ limits = expr.limits
1168
+ if len(limits) != 1 or len(limits[0]) != 3:
1169
+ raise NotImplementedError
1170
+ workprec = prec
1171
+ i = 0
1172
+ maxprec = options.get('maxprec', INF)
1173
+ while 1:
1174
+ result = do_integral(expr, workprec, options)
1175
+ accuracy = complex_accuracy(result)
1176
+ if accuracy >= prec: # achieved desired precision
1177
+ break
1178
+ if workprec >= maxprec: # can't increase accuracy any more
1179
+ break
1180
+ if accuracy == -1:
1181
+ # maybe the answer really is zero and maybe we just haven't increased
1182
+ # the precision enough. So increase by doubling to not take too long
1183
+ # to get to maxprec.
1184
+ workprec *= 2
1185
+ else:
1186
+ workprec += max(prec, 2**i)
1187
+ workprec = min(workprec, maxprec)
1188
+ i += 1
1189
+ return result
1190
+
1191
+
1192
+ def check_convergence(numer: 'Expr', denom: 'Expr', n: 'Symbol') -> tTuple[int, Any, Any]:
1193
+ """
1194
+ Returns
1195
+ =======
1196
+
1197
+ (h, g, p) where
1198
+ -- h is:
1199
+ > 0 for convergence of rate 1/factorial(n)**h
1200
+ < 0 for divergence of rate factorial(n)**(-h)
1201
+ = 0 for geometric or polynomial convergence or divergence
1202
+
1203
+ -- abs(g) is:
1204
+ > 1 for geometric convergence of rate 1/h**n
1205
+ < 1 for geometric divergence of rate h**n
1206
+ = 1 for polynomial convergence or divergence
1207
+
1208
+ (g < 0 indicates an alternating series)
1209
+
1210
+ -- p is:
1211
+ > 1 for polynomial convergence of rate 1/n**h
1212
+ <= 1 for polynomial divergence of rate n**(-h)
1213
+
1214
+ """
1215
+ from sympy.polys.polytools import Poly
1216
+ npol = Poly(numer, n)
1217
+ dpol = Poly(denom, n)
1218
+ p = npol.degree()
1219
+ q = dpol.degree()
1220
+ rate = q - p
1221
+ if rate:
1222
+ return rate, None, None
1223
+ constant = dpol.LC() / npol.LC()
1224
+ from .numbers import equal_valued
1225
+ if not equal_valued(abs(constant), 1):
1226
+ return rate, constant, None
1227
+ if npol.degree() == dpol.degree() == 0:
1228
+ return rate, constant, 0
1229
+ pc = npol.all_coeffs()[1]
1230
+ qc = dpol.all_coeffs()[1]
1231
+ return rate, constant, (qc - pc)/dpol.LC()
1232
+
1233
+
1234
+ def hypsum(expr: 'Expr', n: 'Symbol', start: int, prec: int) -> mpf:
1235
+ """
1236
+ Sum a rapidly convergent infinite hypergeometric series with
1237
+ given general term, e.g. e = hypsum(1/factorial(n), n). The
1238
+ quotient between successive terms must be a quotient of integer
1239
+ polynomials.
1240
+ """
1241
+ from .numbers import Float, equal_valued
1242
+ from sympy.simplify.simplify import hypersimp
1243
+
1244
+ if prec == float('inf'):
1245
+ raise NotImplementedError('does not support inf prec')
1246
+
1247
+ if start:
1248
+ expr = expr.subs(n, n + start)
1249
+ hs = hypersimp(expr, n)
1250
+ if hs is None:
1251
+ raise NotImplementedError("a hypergeometric series is required")
1252
+ num, den = hs.as_numer_denom()
1253
+
1254
+ func1 = lambdify(n, num)
1255
+ func2 = lambdify(n, den)
1256
+
1257
+ h, g, p = check_convergence(num, den, n)
1258
+
1259
+ if h < 0:
1260
+ raise ValueError("Sum diverges like (n!)^%i" % (-h))
1261
+
1262
+ term = expr.subs(n, 0)
1263
+ if not term.is_Rational:
1264
+ raise NotImplementedError("Non rational term functionality is not implemented.")
1265
+
1266
+ # Direct summation if geometric or faster
1267
+ if h > 0 or (h == 0 and abs(g) > 1):
1268
+ term = (MPZ(term.p) << prec) // term.q
1269
+ s = term
1270
+ k = 1
1271
+ while abs(term) > 5:
1272
+ term *= MPZ(func1(k - 1))
1273
+ term //= MPZ(func2(k - 1))
1274
+ s += term
1275
+ k += 1
1276
+ return from_man_exp(s, -prec)
1277
+ else:
1278
+ alt = g < 0
1279
+ if abs(g) < 1:
1280
+ raise ValueError("Sum diverges like (%i)^n" % abs(1/g))
1281
+ if p < 1 or (equal_valued(p, 1) and not alt):
1282
+ raise ValueError("Sum diverges like n^%i" % (-p))
1283
+ # We have polynomial convergence: use Richardson extrapolation
1284
+ vold = None
1285
+ ndig = prec_to_dps(prec)
1286
+ while True:
1287
+ # Need to use at least quad precision because a lot of cancellation
1288
+ # might occur in the extrapolation process; we check the answer to
1289
+ # make sure that the desired precision has been reached, too.
1290
+ prec2 = 4*prec
1291
+ term0 = (MPZ(term.p) << prec2) // term.q
1292
+
1293
+ def summand(k, _term=[term0]):
1294
+ if k:
1295
+ k = int(k)
1296
+ _term[0] *= MPZ(func1(k - 1))
1297
+ _term[0] //= MPZ(func2(k - 1))
1298
+ return make_mpf(from_man_exp(_term[0], -prec2))
1299
+
1300
+ with workprec(prec):
1301
+ v = nsum(summand, [0, mpmath_inf], method='richardson')
1302
+ vf = Float(v, ndig)
1303
+ if vold is not None and vold == vf:
1304
+ break
1305
+ prec += prec # double precision each time
1306
+ vold = vf
1307
+
1308
+ return v._mpf_
1309
+
1310
+
1311
+ def evalf_prod(expr: 'Product', prec: int, options: OPT_DICT) -> TMP_RES:
1312
+ if all((l[1] - l[2]).is_Integer for l in expr.limits):
1313
+ result = evalf(expr.doit(), prec=prec, options=options)
1314
+ else:
1315
+ from sympy.concrete.summations import Sum
1316
+ result = evalf(expr.rewrite(Sum), prec=prec, options=options)
1317
+ return result
1318
+
1319
+
1320
+ def evalf_sum(expr: 'Sum', prec: int, options: OPT_DICT) -> TMP_RES:
1321
+ from .numbers import Float
1322
+ if 'subs' in options:
1323
+ expr = expr.subs(options['subs'])
1324
+ func = expr.function
1325
+ limits = expr.limits
1326
+ if len(limits) != 1 or len(limits[0]) != 3:
1327
+ raise NotImplementedError
1328
+ if func.is_zero:
1329
+ return None, None, prec, None
1330
+ prec2 = prec + 10
1331
+ try:
1332
+ n, a, b = limits[0]
1333
+ if b is not S.Infinity or a is S.NegativeInfinity or a != int(a):
1334
+ raise NotImplementedError
1335
+ # Use fast hypergeometric summation if possible
1336
+ v = hypsum(func, n, int(a), prec2)
1337
+ delta = prec - fastlog(v)
1338
+ if fastlog(v) < -10:
1339
+ v = hypsum(func, n, int(a), delta)
1340
+ return v, None, min(prec, delta), None
1341
+ except NotImplementedError:
1342
+ # Euler-Maclaurin summation for general series
1343
+ eps = Float(2.0)**(-prec)
1344
+ for i in range(1, 5):
1345
+ m = n = 2**i * prec
1346
+ s, err = expr.euler_maclaurin(m=m, n=n, eps=eps,
1347
+ eval_integral=False)
1348
+ err = err.evalf()
1349
+ if err is S.NaN:
1350
+ raise NotImplementedError
1351
+ if err <= eps:
1352
+ break
1353
+ err = fastlog(evalf(abs(err), 20, options)[0])
1354
+ re, im, re_acc, im_acc = evalf(s, prec2, options)
1355
+ if re_acc is None:
1356
+ re_acc = -err
1357
+ if im_acc is None:
1358
+ im_acc = -err
1359
+ return re, im, re_acc, im_acc
1360
+
1361
+
1362
+ #----------------------------------------------------------------------------#
1363
+ # #
1364
+ # Symbolic interface #
1365
+ # #
1366
+ #----------------------------------------------------------------------------#
1367
+
1368
+ def evalf_symbol(x: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
1369
+ val = options['subs'][x]
1370
+ if isinstance(val, mpf):
1371
+ if not val:
1372
+ return None, None, None, None
1373
+ return val._mpf_, None, prec, None
1374
+ else:
1375
+ if '_cache' not in options:
1376
+ options['_cache'] = {}
1377
+ cache = options['_cache']
1378
+ cached, cached_prec = cache.get(x, (None, MINUS_INF))
1379
+ if cached_prec >= prec:
1380
+ return cached
1381
+ v = evalf(sympify(val), prec, options)
1382
+ cache[x] = (v, prec)
1383
+ return v
1384
+
1385
+
1386
+ evalf_table: tDict[Type['Expr'], Callable[['Expr', int, OPT_DICT], TMP_RES]] = {}
1387
+
1388
+
1389
+ def _create_evalf_table():
1390
+ global evalf_table
1391
+ from sympy.concrete.products import Product
1392
+ from sympy.concrete.summations import Sum
1393
+ from .add import Add
1394
+ from .mul import Mul
1395
+ from .numbers import Exp1, Float, Half, ImaginaryUnit, Integer, NaN, NegativeOne, One, Pi, Rational, \
1396
+ Zero, ComplexInfinity, AlgebraicNumber
1397
+ from .power import Pow
1398
+ from .symbol import Dummy, Symbol
1399
+ from sympy.functions.elementary.complexes import Abs, im, re
1400
+ from sympy.functions.elementary.exponential import exp, log
1401
+ from sympy.functions.elementary.integers import ceiling, floor
1402
+ from sympy.functions.elementary.piecewise import Piecewise
1403
+ from sympy.functions.elementary.trigonometric import atan, cos, sin
1404
+ from sympy.integrals.integrals import Integral
1405
+ evalf_table = {
1406
+ Symbol: evalf_symbol,
1407
+ Dummy: evalf_symbol,
1408
+ Float: evalf_float,
1409
+ Rational: evalf_rational,
1410
+ Integer: evalf_integer,
1411
+ Zero: lambda x, prec, options: (None, None, prec, None),
1412
+ One: lambda x, prec, options: (fone, None, prec, None),
1413
+ Half: lambda x, prec, options: (fhalf, None, prec, None),
1414
+ Pi: lambda x, prec, options: (mpf_pi(prec), None, prec, None),
1415
+ Exp1: lambda x, prec, options: (mpf_e(prec), None, prec, None),
1416
+ ImaginaryUnit: lambda x, prec, options: (None, fone, None, prec),
1417
+ NegativeOne: lambda x, prec, options: (fnone, None, prec, None),
1418
+ ComplexInfinity: lambda x, prec, options: S.ComplexInfinity,
1419
+ NaN: lambda x, prec, options: (fnan, None, prec, None),
1420
+
1421
+ exp: evalf_exp,
1422
+
1423
+ cos: evalf_trig,
1424
+ sin: evalf_trig,
1425
+
1426
+ Add: evalf_add,
1427
+ Mul: evalf_mul,
1428
+ Pow: evalf_pow,
1429
+
1430
+ log: evalf_log,
1431
+ atan: evalf_atan,
1432
+ Abs: evalf_abs,
1433
+
1434
+ re: evalf_re,
1435
+ im: evalf_im,
1436
+ floor: evalf_floor,
1437
+ ceiling: evalf_ceiling,
1438
+
1439
+ Integral: evalf_integral,
1440
+ Sum: evalf_sum,
1441
+ Product: evalf_prod,
1442
+ Piecewise: evalf_piecewise,
1443
+
1444
+ AlgebraicNumber: evalf_alg_num,
1445
+ }
1446
+
1447
+
1448
+ def evalf(x: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
1449
+ """
1450
+ Evaluate the ``Expr`` instance, ``x``
1451
+ to a binary precision of ``prec``. This
1452
+ function is supposed to be used internally.
1453
+
1454
+ Parameters
1455
+ ==========
1456
+
1457
+ x : Expr
1458
+ The formula to evaluate to a float.
1459
+ prec : int
1460
+ The binary precision that the output should have.
1461
+ options : dict
1462
+ A dictionary with the same entries as
1463
+ ``EvalfMixin.evalf`` and in addition,
1464
+ ``maxprec`` which is the maximum working precision.
1465
+
1466
+ Returns
1467
+ =======
1468
+
1469
+ An optional tuple, ``(re, im, re_acc, im_acc)``
1470
+ which are the real, imaginary, real accuracy
1471
+ and imaginary accuracy respectively. ``re`` is
1472
+ an mpf value tuple and so is ``im``. ``re_acc``
1473
+ and ``im_acc`` are ints.
1474
+
1475
+ NB: all these return values can be ``None``.
1476
+ If all values are ``None``, then that represents 0.
1477
+ Note that 0 is also represented as ``fzero = (0, 0, 0, 0)``.
1478
+ """
1479
+ from sympy.functions.elementary.complexes import re as re_, im as im_
1480
+ try:
1481
+ rf = evalf_table[type(x)]
1482
+ r = rf(x, prec, options)
1483
+ except KeyError:
1484
+ # Fall back to ordinary evalf if possible
1485
+ if 'subs' in options:
1486
+ x = x.subs(evalf_subs(prec, options['subs']))
1487
+ xe = x._eval_evalf(prec)
1488
+ if xe is None:
1489
+ raise NotImplementedError
1490
+ as_real_imag = getattr(xe, "as_real_imag", None)
1491
+ if as_real_imag is None:
1492
+ raise NotImplementedError # e.g. FiniteSet(-1.0, 1.0).evalf()
1493
+ re, im = as_real_imag()
1494
+ if re.has(re_) or im.has(im_):
1495
+ raise NotImplementedError
1496
+ if re == 0.0:
1497
+ re = None
1498
+ reprec = None
1499
+ elif re.is_number:
1500
+ re = re._to_mpmath(prec, allow_ints=False)._mpf_
1501
+ reprec = prec
1502
+ else:
1503
+ raise NotImplementedError
1504
+ if im == 0.0:
1505
+ im = None
1506
+ imprec = None
1507
+ elif im.is_number:
1508
+ im = im._to_mpmath(prec, allow_ints=False)._mpf_
1509
+ imprec = prec
1510
+ else:
1511
+ raise NotImplementedError
1512
+ r = re, im, reprec, imprec
1513
+
1514
+ if options.get("verbose"):
1515
+ print("### input", x)
1516
+ print("### output", to_str(r[0] or fzero, 50) if isinstance(r, tuple) else r)
1517
+ print("### raw", r) # r[0], r[2]
1518
+ print()
1519
+ chop = options.get('chop', False)
1520
+ if chop:
1521
+ if chop is True:
1522
+ chop_prec = prec
1523
+ else:
1524
+ # convert (approximately) from given tolerance;
1525
+ # the formula here will will make 1e-i rounds to 0 for
1526
+ # i in the range +/-27 while 2e-i will not be chopped
1527
+ chop_prec = int(round(-3.321*math.log10(chop) + 2.5))
1528
+ if chop_prec == 3:
1529
+ chop_prec -= 1
1530
+ r = chop_parts(r, chop_prec)
1531
+ if options.get("strict"):
1532
+ check_target(x, r, prec)
1533
+ return r
1534
+
1535
+
1536
+ def quad_to_mpmath(q, ctx=None):
1537
+ """Turn the quad returned by ``evalf`` into an ``mpf`` or ``mpc``. """
1538
+ mpc = make_mpc if ctx is None else ctx.make_mpc
1539
+ mpf = make_mpf if ctx is None else ctx.make_mpf
1540
+ if q is S.ComplexInfinity:
1541
+ raise NotImplementedError
1542
+ re, im, _, _ = q
1543
+ if im:
1544
+ if not re:
1545
+ re = fzero
1546
+ return mpc((re, im))
1547
+ elif re:
1548
+ return mpf(re)
1549
+ else:
1550
+ return mpf(fzero)
1551
+
1552
+
1553
+ class EvalfMixin:
1554
+ """Mixin class adding evalf capability."""
1555
+
1556
+ __slots__ = () # type: tTuple[str, ...]
1557
+
1558
+ def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False):
1559
+ """
1560
+ Evaluate the given formula to an accuracy of *n* digits.
1561
+
1562
+ Parameters
1563
+ ==========
1564
+
1565
+ subs : dict, optional
1566
+ Substitute numerical values for symbols, e.g.
1567
+ ``subs={x:3, y:1+pi}``. The substitutions must be given as a
1568
+ dictionary.
1569
+
1570
+ maxn : int, optional
1571
+ Allow a maximum temporary working precision of maxn digits.
1572
+
1573
+ chop : bool or number, optional
1574
+ Specifies how to replace tiny real or imaginary parts in
1575
+ subresults by exact zeros.
1576
+
1577
+ When ``True`` the chop value defaults to standard precision.
1578
+
1579
+ Otherwise the chop value is used to determine the
1580
+ magnitude of "small" for purposes of chopping.
1581
+
1582
+ >>> from sympy import N
1583
+ >>> x = 1e-4
1584
+ >>> N(x, chop=True)
1585
+ 0.000100000000000000
1586
+ >>> N(x, chop=1e-5)
1587
+ 0.000100000000000000
1588
+ >>> N(x, chop=1e-4)
1589
+ 0
1590
+
1591
+ strict : bool, optional
1592
+ Raise ``PrecisionExhausted`` if any subresult fails to
1593
+ evaluate to full accuracy, given the available maxprec.
1594
+
1595
+ quad : str, optional
1596
+ Choose algorithm for numerical quadrature. By default,
1597
+ tanh-sinh quadrature is used. For oscillatory
1598
+ integrals on an infinite interval, try ``quad='osc'``.
1599
+
1600
+ verbose : bool, optional
1601
+ Print debug information.
1602
+
1603
+ Notes
1604
+ =====
1605
+
1606
+ When Floats are naively substituted into an expression,
1607
+ precision errors may adversely affect the result. For example,
1608
+ adding 1e16 (a Float) to 1 will truncate to 1e16; if 1e16 is
1609
+ then subtracted, the result will be 0.
1610
+ That is exactly what happens in the following:
1611
+
1612
+ >>> from sympy.abc import x, y, z
1613
+ >>> values = {x: 1e16, y: 1, z: 1e16}
1614
+ >>> (x + y - z).subs(values)
1615
+ 0
1616
+
1617
+ Using the subs argument for evalf is the accurate way to
1618
+ evaluate such an expression:
1619
+
1620
+ >>> (x + y - z).evalf(subs=values)
1621
+ 1.00000000000000
1622
+ """
1623
+ from .numbers import Float, Number
1624
+ n = n if n is not None else 15
1625
+
1626
+ if subs and is_sequence(subs):
1627
+ raise TypeError('subs must be given as a dictionary')
1628
+
1629
+ # for sake of sage that doesn't like evalf(1)
1630
+ if n == 1 and isinstance(self, Number):
1631
+ from .expr import _mag
1632
+ rv = self.evalf(2, subs, maxn, chop, strict, quad, verbose)
1633
+ m = _mag(rv)
1634
+ rv = rv.round(1 - m)
1635
+ return rv
1636
+
1637
+ if not evalf_table:
1638
+ _create_evalf_table()
1639
+ prec = dps_to_prec(n)
1640
+ options = {'maxprec': max(prec, int(maxn*LG10)), 'chop': chop,
1641
+ 'strict': strict, 'verbose': verbose}
1642
+ if subs is not None:
1643
+ options['subs'] = subs
1644
+ if quad is not None:
1645
+ options['quad'] = quad
1646
+ try:
1647
+ result = evalf(self, prec + 4, options)
1648
+ except NotImplementedError:
1649
+ # Fall back to the ordinary evalf
1650
+ if hasattr(self, 'subs') and subs is not None: # issue 20291
1651
+ v = self.subs(subs)._eval_evalf(prec)
1652
+ else:
1653
+ v = self._eval_evalf(prec)
1654
+ if v is None:
1655
+ return self
1656
+ elif not v.is_number:
1657
+ return v
1658
+ try:
1659
+ # If the result is numerical, normalize it
1660
+ result = evalf(v, prec, options)
1661
+ except NotImplementedError:
1662
+ # Probably contains symbols or unknown functions
1663
+ return v
1664
+ if result is S.ComplexInfinity:
1665
+ return result
1666
+ re, im, re_acc, im_acc = result
1667
+ if re is S.NaN or im is S.NaN:
1668
+ return S.NaN
1669
+ if re:
1670
+ p = max(min(prec, re_acc), 1)
1671
+ re = Float._new(re, p)
1672
+ else:
1673
+ re = S.Zero
1674
+ if im:
1675
+ p = max(min(prec, im_acc), 1)
1676
+ im = Float._new(im, p)
1677
+ return re + im*S.ImaginaryUnit
1678
+ else:
1679
+ return re
1680
+
1681
+ n = evalf
1682
+
1683
+ def _evalf(self, prec):
1684
+ """Helper for evalf. Does the same thing but takes binary precision"""
1685
+ r = self._eval_evalf(prec)
1686
+ if r is None:
1687
+ r = self
1688
+ return r
1689
+
1690
+ def _eval_evalf(self, prec):
1691
+ return
1692
+
1693
+ def _to_mpmath(self, prec, allow_ints=True):
1694
+ # mpmath functions accept ints as input
1695
+ errmsg = "cannot convert to mpmath number"
1696
+ if allow_ints and self.is_Integer:
1697
+ return self.p
1698
+ if hasattr(self, '_as_mpf_val'):
1699
+ return make_mpf(self._as_mpf_val(prec))
1700
+ try:
1701
+ result = evalf(self, prec, {})
1702
+ return quad_to_mpmath(result)
1703
+ except NotImplementedError:
1704
+ v = self._eval_evalf(prec)
1705
+ if v is None:
1706
+ raise ValueError(errmsg)
1707
+ if v.is_Float:
1708
+ return make_mpf(v._mpf_)
1709
+ # Number + Number*I is also fine
1710
+ re, im = v.as_real_imag()
1711
+ if allow_ints and re.is_Integer:
1712
+ re = from_int(re.p)
1713
+ elif re.is_Float:
1714
+ re = re._mpf_
1715
+ else:
1716
+ raise ValueError(errmsg)
1717
+ if allow_ints and im.is_Integer:
1718
+ im = from_int(im.p)
1719
+ elif im.is_Float:
1720
+ im = im._mpf_
1721
+ else:
1722
+ raise ValueError(errmsg)
1723
+ return make_mpc((re, im))
1724
+
1725
+
1726
+ def N(x, n=15, **options):
1727
+ r"""
1728
+ Calls x.evalf(n, \*\*options).
1729
+
1730
+ Explanations
1731
+ ============
1732
+
1733
+ Both .n() and N() are equivalent to .evalf(); use the one that you like better.
1734
+ See also the docstring of .evalf() for information on the options.
1735
+
1736
+ Examples
1737
+ ========
1738
+
1739
+ >>> from sympy import Sum, oo, N
1740
+ >>> from sympy.abc import k
1741
+ >>> Sum(1/k**k, (k, 1, oo))
1742
+ Sum(k**(-k), (k, 1, oo))
1743
+ >>> N(_, 4)
1744
+ 1.291
1745
+
1746
+ """
1747
+ # by using rational=True, any evaluation of a string
1748
+ # will be done using exact values for the Floats
1749
+ return sympify(x, rational=True).evalf(n, **options)
1750
+
1751
+
1752
+ def _evalf_with_bounded_error(x: 'Expr', eps: 'Optional[Expr]' = None,
1753
+ m: int = 0,
1754
+ options: Optional[OPT_DICT] = None) -> TMP_RES:
1755
+ """
1756
+ Evaluate *x* to within a bounded absolute error.
1757
+
1758
+ Parameters
1759
+ ==========
1760
+
1761
+ x : Expr
1762
+ The quantity to be evaluated.
1763
+ eps : Expr, None, optional (default=None)
1764
+ Positive real upper bound on the acceptable error.
1765
+ m : int, optional (default=0)
1766
+ If *eps* is None, then use 2**(-m) as the upper bound on the error.
1767
+ options: OPT_DICT
1768
+ As in the ``evalf`` function.
1769
+
1770
+ Returns
1771
+ =======
1772
+
1773
+ A tuple ``(re, im, re_acc, im_acc)``, as returned by ``evalf``.
1774
+
1775
+ See Also
1776
+ ========
1777
+
1778
+ evalf
1779
+
1780
+ """
1781
+ if eps is not None:
1782
+ if not (eps.is_Rational or eps.is_Float) or not eps > 0:
1783
+ raise ValueError("eps must be positive")
1784
+ r, _, _, _ = evalf(1/eps, 1, {})
1785
+ m = fastlog(r)
1786
+
1787
+ c, d, _, _ = evalf(x, 1, {})
1788
+ # Note: If x = a + b*I, then |a| <= 2|c| and |b| <= 2|d|, with equality
1789
+ # only in the zero case.
1790
+ # If a is non-zero, then |c| = 2**nc for some integer nc, and c has
1791
+ # bitcount 1. Therefore 2**fastlog(c) = 2**(nc+1) = 2|c| is an upper bound
1792
+ # on |a|. Likewise for b and d.
1793
+ nr, ni = fastlog(c), fastlog(d)
1794
+ n = max(nr, ni) + 1
1795
+ # If x is 0, then n is MINUS_INF, and p will be 1. Otherwise,
1796
+ # n - 1 bits get us past the integer parts of a and b, and +1 accounts for
1797
+ # the factor of <= sqrt(2) that is |x|/max(|a|, |b|).
1798
+ p = max(1, m + n + 1)
1799
+
1800
+ options = options or {}
1801
+ return evalf(x, p, options)
venv/lib/python3.10/site-packages/sympy/core/mod.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .add import Add
2
+ from .exprtools import gcd_terms
3
+ from .function import Function
4
+ from .kind import NumberKind
5
+ from .logic import fuzzy_and, fuzzy_not
6
+ from .mul import Mul
7
+ from .numbers import equal_valued
8
+ from .singleton import S
9
+
10
+
11
+ class Mod(Function):
12
+ """Represents a modulo operation on symbolic expressions.
13
+
14
+ Parameters
15
+ ==========
16
+
17
+ p : Expr
18
+ Dividend.
19
+
20
+ q : Expr
21
+ Divisor.
22
+
23
+ Notes
24
+ =====
25
+
26
+ The convention used is the same as Python's: the remainder always has the
27
+ same sign as the divisor.
28
+
29
+ Examples
30
+ ========
31
+
32
+ >>> from sympy.abc import x, y
33
+ >>> x**2 % y
34
+ Mod(x**2, y)
35
+ >>> _.subs({x: 5, y: 6})
36
+ 1
37
+
38
+ """
39
+
40
+ kind = NumberKind
41
+
42
+ @classmethod
43
+ def eval(cls, p, q):
44
+ def number_eval(p, q):
45
+ """Try to return p % q if both are numbers or +/-p is known
46
+ to be less than or equal q.
47
+ """
48
+
49
+ if q.is_zero:
50
+ raise ZeroDivisionError("Modulo by zero")
51
+ if p is S.NaN or q is S.NaN or p.is_finite is False or q.is_finite is False:
52
+ return S.NaN
53
+ if p is S.Zero or p in (q, -q) or (p.is_integer and q == 1):
54
+ return S.Zero
55
+
56
+ if q.is_Number:
57
+ if p.is_Number:
58
+ return p%q
59
+ if q == 2:
60
+ if p.is_even:
61
+ return S.Zero
62
+ elif p.is_odd:
63
+ return S.One
64
+
65
+ if hasattr(p, '_eval_Mod'):
66
+ rv = getattr(p, '_eval_Mod')(q)
67
+ if rv is not None:
68
+ return rv
69
+
70
+ # by ratio
71
+ r = p/q
72
+ if r.is_integer:
73
+ return S.Zero
74
+ try:
75
+ d = int(r)
76
+ except TypeError:
77
+ pass
78
+ else:
79
+ if isinstance(d, int):
80
+ rv = p - d*q
81
+ if (rv*q < 0) == True:
82
+ rv += q
83
+ return rv
84
+
85
+ # by difference
86
+ # -2|q| < p < 2|q|
87
+ d = abs(p)
88
+ for _ in range(2):
89
+ d -= abs(q)
90
+ if d.is_negative:
91
+ if q.is_positive:
92
+ if p.is_positive:
93
+ return d + q
94
+ elif p.is_negative:
95
+ return -d
96
+ elif q.is_negative:
97
+ if p.is_positive:
98
+ return d
99
+ elif p.is_negative:
100
+ return -d + q
101
+ break
102
+
103
+ rv = number_eval(p, q)
104
+ if rv is not None:
105
+ return rv
106
+
107
+ # denest
108
+ if isinstance(p, cls):
109
+ qinner = p.args[1]
110
+ if qinner % q == 0:
111
+ return cls(p.args[0], q)
112
+ elif (qinner*(q - qinner)).is_nonnegative:
113
+ # |qinner| < |q| and have same sign
114
+ return p
115
+ elif isinstance(-p, cls):
116
+ qinner = (-p).args[1]
117
+ if qinner % q == 0:
118
+ return cls(-(-p).args[0], q)
119
+ elif (qinner*(q + qinner)).is_nonpositive:
120
+ # |qinner| < |q| and have different sign
121
+ return p
122
+ elif isinstance(p, Add):
123
+ # separating into modulus and non modulus
124
+ both_l = non_mod_l, mod_l = [], []
125
+ for arg in p.args:
126
+ both_l[isinstance(arg, cls)].append(arg)
127
+ # if q same for all
128
+ if mod_l and all(inner.args[1] == q for inner in mod_l):
129
+ net = Add(*non_mod_l) + Add(*[i.args[0] for i in mod_l])
130
+ return cls(net, q)
131
+
132
+ elif isinstance(p, Mul):
133
+ # separating into modulus and non modulus
134
+ both_l = non_mod_l, mod_l = [], []
135
+ for arg in p.args:
136
+ both_l[isinstance(arg, cls)].append(arg)
137
+
138
+ if mod_l and all(inner.args[1] == q for inner in mod_l) and all(t.is_integer for t in p.args) and q.is_integer:
139
+ # finding distributive term
140
+ non_mod_l = [cls(x, q) for x in non_mod_l]
141
+ mod = []
142
+ non_mod = []
143
+ for j in non_mod_l:
144
+ if isinstance(j, cls):
145
+ mod.append(j.args[0])
146
+ else:
147
+ non_mod.append(j)
148
+ prod_mod = Mul(*mod)
149
+ prod_non_mod = Mul(*non_mod)
150
+ prod_mod1 = Mul(*[i.args[0] for i in mod_l])
151
+ net = prod_mod1*prod_mod
152
+ return prod_non_mod*cls(net, q)
153
+
154
+ if q.is_Integer and q is not S.One:
155
+ non_mod_l = [i % q if i.is_Integer and (i % q is not S.Zero) else i for
156
+ i in non_mod_l]
157
+
158
+ p = Mul(*(non_mod_l + mod_l))
159
+
160
+ # XXX other possibilities?
161
+
162
+ from sympy.polys.polyerrors import PolynomialError
163
+ from sympy.polys.polytools import gcd
164
+
165
+ # extract gcd; any further simplification should be done by the user
166
+ try:
167
+ G = gcd(p, q)
168
+ if not equal_valued(G, 1):
169
+ p, q = [gcd_terms(i/G, clear=False, fraction=False)
170
+ for i in (p, q)]
171
+ except PolynomialError: # issue 21373
172
+ G = S.One
173
+ pwas, qwas = p, q
174
+
175
+ # simplify terms
176
+ # (x + y + 2) % x -> Mod(y + 2, x)
177
+ if p.is_Add:
178
+ args = []
179
+ for i in p.args:
180
+ a = cls(i, q)
181
+ if a.count(cls) > i.count(cls):
182
+ args.append(i)
183
+ else:
184
+ args.append(a)
185
+ if args != list(p.args):
186
+ p = Add(*args)
187
+
188
+ else:
189
+ # handle coefficients if they are not Rational
190
+ # since those are not handled by factor_terms
191
+ # e.g. Mod(.6*x, .3*y) -> 0.3*Mod(2*x, y)
192
+ cp, p = p.as_coeff_Mul()
193
+ cq, q = q.as_coeff_Mul()
194
+ ok = False
195
+ if not cp.is_Rational or not cq.is_Rational:
196
+ r = cp % cq
197
+ if equal_valued(r, 0):
198
+ G *= cq
199
+ p *= int(cp/cq)
200
+ ok = True
201
+ if not ok:
202
+ p = cp*p
203
+ q = cq*q
204
+
205
+ # simple -1 extraction
206
+ if p.could_extract_minus_sign() and q.could_extract_minus_sign():
207
+ G, p, q = [-i for i in (G, p, q)]
208
+
209
+ # check again to see if p and q can now be handled as numbers
210
+ rv = number_eval(p, q)
211
+ if rv is not None:
212
+ return rv*G
213
+
214
+ # put 1.0 from G on inside
215
+ if G.is_Float and equal_valued(G, 1):
216
+ p *= G
217
+ return cls(p, q, evaluate=False)
218
+ elif G.is_Mul and G.args[0].is_Float and equal_valued(G.args[0], 1):
219
+ p = G.args[0]*p
220
+ G = Mul._from_args(G.args[1:])
221
+ return G*cls(p, q, evaluate=(p, q) != (pwas, qwas))
222
+
223
+ def _eval_is_integer(self):
224
+ p, q = self.args
225
+ if fuzzy_and([p.is_integer, q.is_integer, fuzzy_not(q.is_zero)]):
226
+ return True
227
+
228
+ def _eval_is_nonnegative(self):
229
+ if self.args[1].is_positive:
230
+ return True
231
+
232
+ def _eval_is_nonpositive(self):
233
+ if self.args[1].is_negative:
234
+ return True
235
+
236
+ def _eval_rewrite_as_floor(self, a, b, **kwargs):
237
+ from sympy.functions.elementary.integers import floor
238
+ return a - b*floor(a/b)
venv/lib/python3.10/site-packages/sympy/core/parameters.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Thread-safe global parameters"""
2
+
3
+ from .cache import clear_cache
4
+ from contextlib import contextmanager
5
+ from threading import local
6
+
7
+ class _global_parameters(local):
8
+ """
9
+ Thread-local global parameters.
10
+
11
+ Explanation
12
+ ===========
13
+
14
+ This class generates thread-local container for SymPy's global parameters.
15
+ Every global parameters must be passed as keyword argument when generating
16
+ its instance.
17
+ A variable, `global_parameters` is provided as default instance for this class.
18
+
19
+ WARNING! Although the global parameters are thread-local, SymPy's cache is not
20
+ by now.
21
+ This may lead to undesired result in multi-threading operations.
22
+
23
+ Examples
24
+ ========
25
+
26
+ >>> from sympy.abc import x
27
+ >>> from sympy.core.cache import clear_cache
28
+ >>> from sympy.core.parameters import global_parameters as gp
29
+
30
+ >>> gp.evaluate
31
+ True
32
+ >>> x+x
33
+ 2*x
34
+
35
+ >>> log = []
36
+ >>> def f():
37
+ ... clear_cache()
38
+ ... gp.evaluate = False
39
+ ... log.append(x+x)
40
+ ... clear_cache()
41
+ >>> import threading
42
+ >>> thread = threading.Thread(target=f)
43
+ >>> thread.start()
44
+ >>> thread.join()
45
+
46
+ >>> print(log)
47
+ [x + x]
48
+
49
+ >>> gp.evaluate
50
+ True
51
+ >>> x+x
52
+ 2*x
53
+
54
+ References
55
+ ==========
56
+
57
+ .. [1] https://docs.python.org/3/library/threading.html
58
+
59
+ """
60
+ def __init__(self, **kwargs):
61
+ self.__dict__.update(kwargs)
62
+
63
+ def __setattr__(self, name, value):
64
+ if getattr(self, name) != value:
65
+ clear_cache()
66
+ return super().__setattr__(name, value)
67
+
68
+ global_parameters = _global_parameters(evaluate=True, distribute=True, exp_is_pow=False)
69
+
70
+ @contextmanager
71
+ def evaluate(x):
72
+ """ Control automatic evaluation
73
+
74
+ Explanation
75
+ ===========
76
+
77
+ This context manager controls whether or not all SymPy functions evaluate
78
+ by default.
79
+
80
+ Note that much of SymPy expects evaluated expressions. This functionality
81
+ is experimental and is unlikely to function as intended on large
82
+ expressions.
83
+
84
+ Examples
85
+ ========
86
+
87
+ >>> from sympy import evaluate
88
+ >>> from sympy.abc import x
89
+ >>> print(x + x)
90
+ 2*x
91
+ >>> with evaluate(False):
92
+ ... print(x + x)
93
+ x + x
94
+ """
95
+
96
+ old = global_parameters.evaluate
97
+
98
+ try:
99
+ global_parameters.evaluate = x
100
+ yield
101
+ finally:
102
+ global_parameters.evaluate = old
103
+
104
+
105
+ @contextmanager
106
+ def distribute(x):
107
+ """ Control automatic distribution of Number over Add
108
+
109
+ Explanation
110
+ ===========
111
+
112
+ This context manager controls whether or not Mul distribute Number over
113
+ Add. Plan is to avoid distributing Number over Add in all of sympy. Once
114
+ that is done, this contextmanager will be removed.
115
+
116
+ Examples
117
+ ========
118
+
119
+ >>> from sympy.abc import x
120
+ >>> from sympy.core.parameters import distribute
121
+ >>> print(2*(x + 1))
122
+ 2*x + 2
123
+ >>> with distribute(False):
124
+ ... print(2*(x + 1))
125
+ 2*(x + 1)
126
+ """
127
+
128
+ old = global_parameters.distribute
129
+
130
+ try:
131
+ global_parameters.distribute = x
132
+ yield
133
+ finally:
134
+ global_parameters.distribute = old
135
+
136
+
137
+ @contextmanager
138
+ def _exp_is_pow(x):
139
+ """
140
+ Control whether `e^x` should be represented as ``exp(x)`` or a ``Pow(E, x)``.
141
+
142
+ Examples
143
+ ========
144
+
145
+ >>> from sympy import exp
146
+ >>> from sympy.abc import x
147
+ >>> from sympy.core.parameters import _exp_is_pow
148
+ >>> with _exp_is_pow(True): print(type(exp(x)))
149
+ <class 'sympy.core.power.Pow'>
150
+ >>> with _exp_is_pow(False): print(type(exp(x)))
151
+ exp
152
+ """
153
+ old = global_parameters.exp_is_pow
154
+
155
+ clear_cache()
156
+ try:
157
+ global_parameters.exp_is_pow = x
158
+ yield
159
+ finally:
160
+ clear_cache()
161
+ global_parameters.exp_is_pow = old
venv/lib/python3.10/site-packages/sympy/core/power.py ADDED
@@ -0,0 +1,2004 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Callable
3
+ from math import log as _log, sqrt as _sqrt
4
+ from itertools import product
5
+
6
+ from .sympify import _sympify
7
+ from .cache import cacheit
8
+ from .singleton import S
9
+ from .expr import Expr
10
+ from .evalf import PrecisionExhausted
11
+ from .function import (expand_complex, expand_multinomial,
12
+ expand_mul, _mexpand, PoleError)
13
+ from .logic import fuzzy_bool, fuzzy_not, fuzzy_and, fuzzy_or
14
+ from .parameters import global_parameters
15
+ from .relational import is_gt, is_lt
16
+ from .kind import NumberKind, UndefinedKind
17
+ from sympy.external.gmpy import HAS_GMPY, gmpy
18
+ from sympy.utilities.iterables import sift
19
+ from sympy.utilities.exceptions import sympy_deprecation_warning
20
+ from sympy.utilities.misc import as_int
21
+ from sympy.multipledispatch import Dispatcher
22
+
23
+ from mpmath.libmp import sqrtrem as mpmath_sqrtrem
24
+
25
+
26
+
27
+ def isqrt(n):
28
+ """Return the largest integer less than or equal to sqrt(n)."""
29
+ if n < 0:
30
+ raise ValueError("n must be nonnegative")
31
+ n = int(n)
32
+
33
+ # Fast path: with IEEE 754 binary64 floats and a correctly-rounded
34
+ # math.sqrt, int(math.sqrt(n)) works for any integer n satisfying 0 <= n <
35
+ # 4503599761588224 = 2**52 + 2**27. But Python doesn't guarantee either
36
+ # IEEE 754 format floats *or* correct rounding of math.sqrt, so check the
37
+ # answer and fall back to the slow method if necessary.
38
+ if n < 4503599761588224:
39
+ s = int(_sqrt(n))
40
+ if 0 <= n - s*s <= 2*s:
41
+ return s
42
+
43
+ return integer_nthroot(n, 2)[0]
44
+
45
+
46
+ def integer_nthroot(y, n):
47
+ """
48
+ Return a tuple containing x = floor(y**(1/n))
49
+ and a boolean indicating whether the result is exact (that is,
50
+ whether x**n == y).
51
+
52
+ Examples
53
+ ========
54
+
55
+ >>> from sympy import integer_nthroot
56
+ >>> integer_nthroot(16, 2)
57
+ (4, True)
58
+ >>> integer_nthroot(26, 2)
59
+ (5, False)
60
+
61
+ To simply determine if a number is a perfect square, the is_square
62
+ function should be used:
63
+
64
+ >>> from sympy.ntheory.primetest import is_square
65
+ >>> is_square(26)
66
+ False
67
+
68
+ See Also
69
+ ========
70
+ sympy.ntheory.primetest.is_square
71
+ integer_log
72
+ """
73
+ y, n = as_int(y), as_int(n)
74
+ if y < 0:
75
+ raise ValueError("y must be nonnegative")
76
+ if n < 1:
77
+ raise ValueError("n must be positive")
78
+ if HAS_GMPY and n < 2**63:
79
+ # Currently it works only for n < 2**63, else it produces TypeError
80
+ # sympy issue: https://github.com/sympy/sympy/issues/18374
81
+ # gmpy2 issue: https://github.com/aleaxit/gmpy/issues/257
82
+ if HAS_GMPY >= 2:
83
+ x, t = gmpy.iroot(y, n)
84
+ else:
85
+ x, t = gmpy.root(y, n)
86
+ return as_int(x), bool(t)
87
+ return _integer_nthroot_python(y, n)
88
+
89
+ def _integer_nthroot_python(y, n):
90
+ if y in (0, 1):
91
+ return y, True
92
+ if n == 1:
93
+ return y, True
94
+ if n == 2:
95
+ x, rem = mpmath_sqrtrem(y)
96
+ return int(x), not rem
97
+ if n >= y.bit_length():
98
+ return 1, False
99
+ # Get initial estimate for Newton's method. Care must be taken to
100
+ # avoid overflow
101
+ try:
102
+ guess = int(y**(1./n) + 0.5)
103
+ except OverflowError:
104
+ exp = _log(y, 2)/n
105
+ if exp > 53:
106
+ shift = int(exp - 53)
107
+ guess = int(2.0**(exp - shift) + 1) << shift
108
+ else:
109
+ guess = int(2.0**exp)
110
+ if guess > 2**50:
111
+ # Newton iteration
112
+ xprev, x = -1, guess
113
+ while 1:
114
+ t = x**(n - 1)
115
+ xprev, x = x, ((n - 1)*x + y//t)//n
116
+ if abs(x - xprev) < 2:
117
+ break
118
+ else:
119
+ x = guess
120
+ # Compensate
121
+ t = x**n
122
+ while t < y:
123
+ x += 1
124
+ t = x**n
125
+ while t > y:
126
+ x -= 1
127
+ t = x**n
128
+ return int(x), t == y # int converts long to int if possible
129
+
130
+
131
+ def integer_log(y, x):
132
+ r"""
133
+ Returns ``(e, bool)`` where e is the largest nonnegative integer
134
+ such that :math:`|y| \geq |x^e|` and ``bool`` is True if $y = x^e$.
135
+
136
+ Examples
137
+ ========
138
+
139
+ >>> from sympy import integer_log
140
+ >>> integer_log(125, 5)
141
+ (3, True)
142
+ >>> integer_log(17, 9)
143
+ (1, False)
144
+ >>> integer_log(4, -2)
145
+ (2, True)
146
+ >>> integer_log(-125,-5)
147
+ (3, True)
148
+
149
+ See Also
150
+ ========
151
+ integer_nthroot
152
+ sympy.ntheory.primetest.is_square
153
+ sympy.ntheory.factor_.multiplicity
154
+ sympy.ntheory.factor_.perfect_power
155
+ """
156
+ if x == 1:
157
+ raise ValueError('x cannot take value as 1')
158
+ if y == 0:
159
+ raise ValueError('y cannot take value as 0')
160
+
161
+ if x in (-2, 2):
162
+ x = int(x)
163
+ y = as_int(y)
164
+ e = y.bit_length() - 1
165
+ return e, x**e == y
166
+ if x < 0:
167
+ n, b = integer_log(y if y > 0 else -y, -x)
168
+ return n, b and bool(n % 2 if y < 0 else not n % 2)
169
+
170
+ x = as_int(x)
171
+ y = as_int(y)
172
+ r = e = 0
173
+ while y >= x:
174
+ d = x
175
+ m = 1
176
+ while y >= d:
177
+ y, rem = divmod(y, d)
178
+ r = r or rem
179
+ e += m
180
+ if y > d:
181
+ d *= d
182
+ m *= 2
183
+ return e, r == 0 and y == 1
184
+
185
+
186
+ class Pow(Expr):
187
+ """
188
+ Defines the expression x**y as "x raised to a power y"
189
+
190
+ .. deprecated:: 1.7
191
+
192
+ Using arguments that aren't subclasses of :class:`~.Expr` in core
193
+ operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
194
+ deprecated. See :ref:`non-expr-args-deprecated` for details.
195
+
196
+ Singleton definitions involving (0, 1, -1, oo, -oo, I, -I):
197
+
198
+ +--------------+---------+-----------------------------------------------+
199
+ | expr | value | reason |
200
+ +==============+=========+===============================================+
201
+ | z**0 | 1 | Although arguments over 0**0 exist, see [2]. |
202
+ +--------------+---------+-----------------------------------------------+
203
+ | z**1 | z | |
204
+ +--------------+---------+-----------------------------------------------+
205
+ | (-oo)**(-1) | 0 | |
206
+ +--------------+---------+-----------------------------------------------+
207
+ | (-1)**-1 | -1 | |
208
+ +--------------+---------+-----------------------------------------------+
209
+ | S.Zero**-1 | zoo | This is not strictly true, as 0**-1 may be |
210
+ | | | undefined, but is convenient in some contexts |
211
+ | | | where the base is assumed to be positive. |
212
+ +--------------+---------+-----------------------------------------------+
213
+ | 1**-1 | 1 | |
214
+ +--------------+---------+-----------------------------------------------+
215
+ | oo**-1 | 0 | |
216
+ +--------------+---------+-----------------------------------------------+
217
+ | 0**oo | 0 | Because for all complex numbers z near |
218
+ | | | 0, z**oo -> 0. |
219
+ +--------------+---------+-----------------------------------------------+
220
+ | 0**-oo | zoo | This is not strictly true, as 0**oo may be |
221
+ | | | oscillating between positive and negative |
222
+ | | | values or rotating in the complex plane. |
223
+ | | | It is convenient, however, when the base |
224
+ | | | is positive. |
225
+ +--------------+---------+-----------------------------------------------+
226
+ | 1**oo | nan | Because there are various cases where |
227
+ | 1**-oo | | lim(x(t),t)=1, lim(y(t),t)=oo (or -oo), |
228
+ | | | but lim( x(t)**y(t), t) != 1. See [3]. |
229
+ +--------------+---------+-----------------------------------------------+
230
+ | b**zoo | nan | Because b**z has no limit as z -> zoo |
231
+ +--------------+---------+-----------------------------------------------+
232
+ | (-1)**oo | nan | Because of oscillations in the limit. |
233
+ | (-1)**(-oo) | | |
234
+ +--------------+---------+-----------------------------------------------+
235
+ | oo**oo | oo | |
236
+ +--------------+---------+-----------------------------------------------+
237
+ | oo**-oo | 0 | |
238
+ +--------------+---------+-----------------------------------------------+
239
+ | (-oo)**oo | nan | |
240
+ | (-oo)**-oo | | |
241
+ +--------------+---------+-----------------------------------------------+
242
+ | oo**I | nan | oo**e could probably be best thought of as |
243
+ | (-oo)**I | | the limit of x**e for real x as x tends to |
244
+ | | | oo. If e is I, then the limit does not exist |
245
+ | | | and nan is used to indicate that. |
246
+ +--------------+---------+-----------------------------------------------+
247
+ | oo**(1+I) | zoo | If the real part of e is positive, then the |
248
+ | (-oo)**(1+I) | | limit of abs(x**e) is oo. So the limit value |
249
+ | | | is zoo. |
250
+ +--------------+---------+-----------------------------------------------+
251
+ | oo**(-1+I) | 0 | If the real part of e is negative, then the |
252
+ | -oo**(-1+I) | | limit is 0. |
253
+ +--------------+---------+-----------------------------------------------+
254
+
255
+ Because symbolic computations are more flexible than floating point
256
+ calculations and we prefer to never return an incorrect answer,
257
+ we choose not to conform to all IEEE 754 conventions. This helps
258
+ us avoid extra test-case code in the calculation of limits.
259
+
260
+ See Also
261
+ ========
262
+
263
+ sympy.core.numbers.Infinity
264
+ sympy.core.numbers.NegativeInfinity
265
+ sympy.core.numbers.NaN
266
+
267
+ References
268
+ ==========
269
+
270
+ .. [1] https://en.wikipedia.org/wiki/Exponentiation
271
+ .. [2] https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero
272
+ .. [3] https://en.wikipedia.org/wiki/Indeterminate_forms
273
+
274
+ """
275
+ is_Pow = True
276
+
277
+ __slots__ = ('is_commutative',)
278
+
279
+ args: tuple[Expr, Expr]
280
+ _args: tuple[Expr, Expr]
281
+
282
+ @cacheit
283
+ def __new__(cls, b, e, evaluate=None):
284
+ if evaluate is None:
285
+ evaluate = global_parameters.evaluate
286
+
287
+ b = _sympify(b)
288
+ e = _sympify(e)
289
+
290
+ # XXX: This can be removed when non-Expr args are disallowed rather
291
+ # than deprecated.
292
+ from .relational import Relational
293
+ if isinstance(b, Relational) or isinstance(e, Relational):
294
+ raise TypeError('Relational cannot be used in Pow')
295
+
296
+ # XXX: This should raise TypeError once deprecation period is over:
297
+ for arg in [b, e]:
298
+ if not isinstance(arg, Expr):
299
+ sympy_deprecation_warning(
300
+ f"""
301
+ Using non-Expr arguments in Pow is deprecated (in this case, one of the
302
+ arguments is of type {type(arg).__name__!r}).
303
+
304
+ If you really did intend to construct a power with this base, use the **
305
+ operator instead.""",
306
+ deprecated_since_version="1.7",
307
+ active_deprecations_target="non-expr-args-deprecated",
308
+ stacklevel=4,
309
+ )
310
+
311
+ if evaluate:
312
+ if e is S.ComplexInfinity:
313
+ return S.NaN
314
+ if e is S.Infinity:
315
+ if is_gt(b, S.One):
316
+ return S.Infinity
317
+ if is_gt(b, S.NegativeOne) and is_lt(b, S.One):
318
+ return S.Zero
319
+ if is_lt(b, S.NegativeOne):
320
+ if b.is_finite:
321
+ return S.ComplexInfinity
322
+ if b.is_finite is False:
323
+ return S.NaN
324
+ if e is S.Zero:
325
+ return S.One
326
+ elif e is S.One:
327
+ return b
328
+ elif e == -1 and not b:
329
+ return S.ComplexInfinity
330
+ elif e.__class__.__name__ == "AccumulationBounds":
331
+ if b == S.Exp1:
332
+ from sympy.calculus.accumulationbounds import AccumBounds
333
+ return AccumBounds(Pow(b, e.min), Pow(b, e.max))
334
+ # autosimplification if base is a number and exp odd/even
335
+ # if base is Number then the base will end up positive; we
336
+ # do not do this with arbitrary expressions since symbolic
337
+ # cancellation might occur as in (x - 1)/(1 - x) -> -1. If
338
+ # we returned Piecewise((-1, Ne(x, 1))) for such cases then
339
+ # we could do this...but we don't
340
+ elif (e.is_Symbol and e.is_integer or e.is_Integer
341
+ ) and (b.is_number and b.is_Mul or b.is_Number
342
+ ) and b.could_extract_minus_sign():
343
+ if e.is_even:
344
+ b = -b
345
+ elif e.is_odd:
346
+ return -Pow(-b, e)
347
+ if S.NaN in (b, e): # XXX S.NaN**x -> S.NaN under assumption that x != 0
348
+ return S.NaN
349
+ elif b is S.One:
350
+ if abs(e).is_infinite:
351
+ return S.NaN
352
+ return S.One
353
+ else:
354
+ # recognize base as E
355
+ from sympy.functions.elementary.exponential import exp_polar
356
+ if not e.is_Atom and b is not S.Exp1 and not isinstance(b, exp_polar):
357
+ from .exprtools import factor_terms
358
+ from sympy.functions.elementary.exponential import log
359
+ from sympy.simplify.radsimp import fraction
360
+ c, ex = factor_terms(e, sign=False).as_coeff_Mul()
361
+ num, den = fraction(ex)
362
+ if isinstance(den, log) and den.args[0] == b:
363
+ return S.Exp1**(c*num)
364
+ elif den.is_Add:
365
+ from sympy.functions.elementary.complexes import sign, im
366
+ s = sign(im(b))
367
+ if s.is_Number and s and den == \
368
+ log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi:
369
+ return S.Exp1**(c*num)
370
+
371
+ obj = b._eval_power(e)
372
+ if obj is not None:
373
+ return obj
374
+ obj = Expr.__new__(cls, b, e)
375
+ obj = cls._exec_constructor_postprocessors(obj)
376
+ if not isinstance(obj, Pow):
377
+ return obj
378
+ obj.is_commutative = (b.is_commutative and e.is_commutative)
379
+ return obj
380
+
381
+ def inverse(self, argindex=1):
382
+ if self.base == S.Exp1:
383
+ from sympy.functions.elementary.exponential import log
384
+ return log
385
+ return None
386
+
387
+ @property
388
+ def base(self) -> Expr:
389
+ return self._args[0]
390
+
391
+ @property
392
+ def exp(self) -> Expr:
393
+ return self._args[1]
394
+
395
+ @property
396
+ def kind(self):
397
+ if self.exp.kind is NumberKind:
398
+ return self.base.kind
399
+ else:
400
+ return UndefinedKind
401
+
402
+ @classmethod
403
+ def class_key(cls):
404
+ return 3, 2, cls.__name__
405
+
406
+ def _eval_refine(self, assumptions):
407
+ from sympy.assumptions.ask import ask, Q
408
+ b, e = self.as_base_exp()
409
+ if ask(Q.integer(e), assumptions) and b.could_extract_minus_sign():
410
+ if ask(Q.even(e), assumptions):
411
+ return Pow(-b, e)
412
+ elif ask(Q.odd(e), assumptions):
413
+ return -Pow(-b, e)
414
+
415
+ def _eval_power(self, other):
416
+ b, e = self.as_base_exp()
417
+ if b is S.NaN:
418
+ return (b**e)**other # let __new__ handle it
419
+
420
+ s = None
421
+ if other.is_integer:
422
+ s = 1
423
+ elif b.is_polar: # e.g. exp_polar, besselj, var('p', polar=True)...
424
+ s = 1
425
+ elif e.is_extended_real is not None:
426
+ from sympy.functions.elementary.complexes import arg, im, re, sign
427
+ from sympy.functions.elementary.exponential import exp, log
428
+ from sympy.functions.elementary.integers import floor
429
+ # helper functions ===========================
430
+ def _half(e):
431
+ """Return True if the exponent has a literal 2 as the
432
+ denominator, else None."""
433
+ if getattr(e, 'q', None) == 2:
434
+ return True
435
+ n, d = e.as_numer_denom()
436
+ if n.is_integer and d == 2:
437
+ return True
438
+ def _n2(e):
439
+ """Return ``e`` evaluated to a Number with 2 significant
440
+ digits, else None."""
441
+ try:
442
+ rv = e.evalf(2, strict=True)
443
+ if rv.is_Number:
444
+ return rv
445
+ except PrecisionExhausted:
446
+ pass
447
+ # ===================================================
448
+ if e.is_extended_real:
449
+ # we need _half(other) with constant floor or
450
+ # floor(S.Half - e*arg(b)/2/pi) == 0
451
+
452
+
453
+ # handle -1 as special case
454
+ if e == -1:
455
+ # floor arg. is 1/2 + arg(b)/2/pi
456
+ if _half(other):
457
+ if b.is_negative is True:
458
+ return S.NegativeOne**other*Pow(-b, e*other)
459
+ elif b.is_negative is False: # XXX ok if im(b) != 0?
460
+ return Pow(b, -other)
461
+ elif e.is_even:
462
+ if b.is_extended_real:
463
+ b = abs(b)
464
+ if b.is_imaginary:
465
+ b = abs(im(b))*S.ImaginaryUnit
466
+
467
+ if (abs(e) < 1) == True or e == 1:
468
+ s = 1 # floor = 0
469
+ elif b.is_extended_nonnegative:
470
+ s = 1 # floor = 0
471
+ elif re(b).is_extended_nonnegative and (abs(e) < 2) == True:
472
+ s = 1 # floor = 0
473
+ elif _half(other):
474
+ s = exp(2*S.Pi*S.ImaginaryUnit*other*floor(
475
+ S.Half - e*arg(b)/(2*S.Pi)))
476
+ if s.is_extended_real and _n2(sign(s) - s) == 0:
477
+ s = sign(s)
478
+ else:
479
+ s = None
480
+ else:
481
+ # e.is_extended_real is False requires:
482
+ # _half(other) with constant floor or
483
+ # floor(S.Half - im(e*log(b))/2/pi) == 0
484
+ try:
485
+ s = exp(2*S.ImaginaryUnit*S.Pi*other*
486
+ floor(S.Half - im(e*log(b))/2/S.Pi))
487
+ # be careful to test that s is -1 or 1 b/c sign(I) == I:
488
+ # so check that s is real
489
+ if s.is_extended_real and _n2(sign(s) - s) == 0:
490
+ s = sign(s)
491
+ else:
492
+ s = None
493
+ except PrecisionExhausted:
494
+ s = None
495
+
496
+ if s is not None:
497
+ return s*Pow(b, e*other)
498
+
499
+ def _eval_Mod(self, q):
500
+ r"""A dispatched function to compute `b^e \bmod q`, dispatched
501
+ by ``Mod``.
502
+
503
+ Notes
504
+ =====
505
+
506
+ Algorithms:
507
+
508
+ 1. For unevaluated integer power, use built-in ``pow`` function
509
+ with 3 arguments, if powers are not too large wrt base.
510
+
511
+ 2. For very large powers, use totient reduction if $e \ge \log(m)$.
512
+ Bound on m, is for safe factorization memory wise i.e. $m^{1/4}$.
513
+ For pollard-rho to be faster than built-in pow $\log(e) > m^{1/4}$
514
+ check is added.
515
+
516
+ 3. For any unevaluated power found in `b` or `e`, the step 2
517
+ will be recursed down to the base and the exponent
518
+ such that the $b \bmod q$ becomes the new base and
519
+ $\phi(q) + e \bmod \phi(q)$ becomes the new exponent, and then
520
+ the computation for the reduced expression can be done.
521
+ """
522
+
523
+ base, exp = self.base, self.exp
524
+
525
+ if exp.is_integer and exp.is_positive:
526
+ if q.is_integer and base % q == 0:
527
+ return S.Zero
528
+
529
+ from sympy.ntheory.factor_ import totient
530
+
531
+ if base.is_Integer and exp.is_Integer and q.is_Integer:
532
+ b, e, m = int(base), int(exp), int(q)
533
+ mb = m.bit_length()
534
+ if mb <= 80 and e >= mb and e.bit_length()**4 >= m:
535
+ phi = int(totient(m))
536
+ return Integer(pow(b, phi + e%phi, m))
537
+ return Integer(pow(b, e, m))
538
+
539
+ from .mod import Mod
540
+
541
+ if isinstance(base, Pow) and base.is_integer and base.is_number:
542
+ base = Mod(base, q)
543
+ return Mod(Pow(base, exp, evaluate=False), q)
544
+
545
+ if isinstance(exp, Pow) and exp.is_integer and exp.is_number:
546
+ bit_length = int(q).bit_length()
547
+ # XXX Mod-Pow actually attempts to do a hanging evaluation
548
+ # if this dispatched function returns None.
549
+ # May need some fixes in the dispatcher itself.
550
+ if bit_length <= 80:
551
+ phi = totient(q)
552
+ exp = phi + Mod(exp, phi)
553
+ return Mod(Pow(base, exp, evaluate=False), q)
554
+
555
+ def _eval_is_even(self):
556
+ if self.exp.is_integer and self.exp.is_positive:
557
+ return self.base.is_even
558
+
559
+ def _eval_is_negative(self):
560
+ ext_neg = Pow._eval_is_extended_negative(self)
561
+ if ext_neg is True:
562
+ return self.is_finite
563
+ return ext_neg
564
+
565
+ def _eval_is_extended_positive(self):
566
+ if self.base == self.exp:
567
+ if self.base.is_extended_nonnegative:
568
+ return True
569
+ elif self.base.is_positive:
570
+ if self.exp.is_real:
571
+ return True
572
+ elif self.base.is_extended_negative:
573
+ if self.exp.is_even:
574
+ return True
575
+ if self.exp.is_odd:
576
+ return False
577
+ elif self.base.is_zero:
578
+ if self.exp.is_extended_real:
579
+ return self.exp.is_zero
580
+ elif self.base.is_extended_nonpositive:
581
+ if self.exp.is_odd:
582
+ return False
583
+ elif self.base.is_imaginary:
584
+ if self.exp.is_integer:
585
+ m = self.exp % 4
586
+ if m.is_zero:
587
+ return True
588
+ if m.is_integer and m.is_zero is False:
589
+ return False
590
+ if self.exp.is_imaginary:
591
+ from sympy.functions.elementary.exponential import log
592
+ return log(self.base).is_imaginary
593
+
594
+ def _eval_is_extended_negative(self):
595
+ if self.exp is S.Half:
596
+ if self.base.is_complex or self.base.is_extended_real:
597
+ return False
598
+ if self.base.is_extended_negative:
599
+ if self.exp.is_odd and self.base.is_finite:
600
+ return True
601
+ if self.exp.is_even:
602
+ return False
603
+ elif self.base.is_extended_positive:
604
+ if self.exp.is_extended_real:
605
+ return False
606
+ elif self.base.is_zero:
607
+ if self.exp.is_extended_real:
608
+ return False
609
+ elif self.base.is_extended_nonnegative:
610
+ if self.exp.is_extended_nonnegative:
611
+ return False
612
+ elif self.base.is_extended_nonpositive:
613
+ if self.exp.is_even:
614
+ return False
615
+ elif self.base.is_extended_real:
616
+ if self.exp.is_even:
617
+ return False
618
+
619
+ def _eval_is_zero(self):
620
+ if self.base.is_zero:
621
+ if self.exp.is_extended_positive:
622
+ return True
623
+ elif self.exp.is_extended_nonpositive:
624
+ return False
625
+ elif self.base == S.Exp1:
626
+ return self.exp is S.NegativeInfinity
627
+ elif self.base.is_zero is False:
628
+ if self.base.is_finite and self.exp.is_finite:
629
+ return False
630
+ elif self.exp.is_negative:
631
+ return self.base.is_infinite
632
+ elif self.exp.is_nonnegative:
633
+ return False
634
+ elif self.exp.is_infinite and self.exp.is_extended_real:
635
+ if (1 - abs(self.base)).is_extended_positive:
636
+ return self.exp.is_extended_positive
637
+ elif (1 - abs(self.base)).is_extended_negative:
638
+ return self.exp.is_extended_negative
639
+ elif self.base.is_finite and self.exp.is_negative:
640
+ # when self.base.is_zero is None
641
+ return False
642
+
643
+ def _eval_is_integer(self):
644
+ b, e = self.args
645
+ if b.is_rational:
646
+ if b.is_integer is False and e.is_positive:
647
+ return False # rat**nonneg
648
+ if b.is_integer and e.is_integer:
649
+ if b is S.NegativeOne:
650
+ return True
651
+ if e.is_nonnegative or e.is_positive:
652
+ return True
653
+ if b.is_integer and e.is_negative and (e.is_finite or e.is_integer):
654
+ if fuzzy_not((b - 1).is_zero) and fuzzy_not((b + 1).is_zero):
655
+ return False
656
+ if b.is_Number and e.is_Number:
657
+ check = self.func(*self.args)
658
+ return check.is_Integer
659
+ if e.is_negative and b.is_positive and (b - 1).is_positive:
660
+ return False
661
+ if e.is_negative and b.is_negative and (b + 1).is_negative:
662
+ return False
663
+
664
+ def _eval_is_extended_real(self):
665
+ if self.base is S.Exp1:
666
+ if self.exp.is_extended_real:
667
+ return True
668
+ elif self.exp.is_imaginary:
669
+ return (2*S.ImaginaryUnit*self.exp/S.Pi).is_even
670
+
671
+ from sympy.functions.elementary.exponential import log, exp
672
+ real_b = self.base.is_extended_real
673
+ if real_b is None:
674
+ if self.base.func == exp and self.base.exp.is_imaginary:
675
+ return self.exp.is_imaginary
676
+ if self.base.func == Pow and self.base.base is S.Exp1 and self.base.exp.is_imaginary:
677
+ return self.exp.is_imaginary
678
+ return
679
+ real_e = self.exp.is_extended_real
680
+ if real_e is None:
681
+ return
682
+ if real_b and real_e:
683
+ if self.base.is_extended_positive:
684
+ return True
685
+ elif self.base.is_extended_nonnegative and self.exp.is_extended_nonnegative:
686
+ return True
687
+ elif self.exp.is_integer and self.base.is_extended_nonzero:
688
+ return True
689
+ elif self.exp.is_integer and self.exp.is_nonnegative:
690
+ return True
691
+ elif self.base.is_extended_negative:
692
+ if self.exp.is_Rational:
693
+ return False
694
+ if real_e and self.exp.is_extended_negative and self.base.is_zero is False:
695
+ return Pow(self.base, -self.exp).is_extended_real
696
+ im_b = self.base.is_imaginary
697
+ im_e = self.exp.is_imaginary
698
+ if im_b:
699
+ if self.exp.is_integer:
700
+ if self.exp.is_even:
701
+ return True
702
+ elif self.exp.is_odd:
703
+ return False
704
+ elif im_e and log(self.base).is_imaginary:
705
+ return True
706
+ elif self.exp.is_Add:
707
+ c, a = self.exp.as_coeff_Add()
708
+ if c and c.is_Integer:
709
+ return Mul(
710
+ self.base**c, self.base**a, evaluate=False).is_extended_real
711
+ elif self.base in (-S.ImaginaryUnit, S.ImaginaryUnit):
712
+ if (self.exp/2).is_integer is False:
713
+ return False
714
+ if real_b and im_e:
715
+ if self.base is S.NegativeOne:
716
+ return True
717
+ c = self.exp.coeff(S.ImaginaryUnit)
718
+ if c:
719
+ if self.base.is_rational and c.is_rational:
720
+ if self.base.is_nonzero and (self.base - 1).is_nonzero and c.is_nonzero:
721
+ return False
722
+ ok = (c*log(self.base)/S.Pi).is_integer
723
+ if ok is not None:
724
+ return ok
725
+
726
+ if real_b is False and real_e: # we already know it's not imag
727
+ from sympy.functions.elementary.complexes import arg
728
+ i = arg(self.base)*self.exp/S.Pi
729
+ if i.is_complex: # finite
730
+ return i.is_integer
731
+
732
+ def _eval_is_complex(self):
733
+
734
+ if self.base == S.Exp1:
735
+ return fuzzy_or([self.exp.is_complex, self.exp.is_extended_negative])
736
+
737
+ if all(a.is_complex for a in self.args) and self._eval_is_finite():
738
+ return True
739
+
740
+ def _eval_is_imaginary(self):
741
+ if self.base.is_commutative is False:
742
+ return False
743
+
744
+ if self.base.is_imaginary:
745
+ if self.exp.is_integer:
746
+ odd = self.exp.is_odd
747
+ if odd is not None:
748
+ return odd
749
+ return
750
+
751
+ if self.base == S.Exp1:
752
+ f = 2 * self.exp / (S.Pi*S.ImaginaryUnit)
753
+ # exp(pi*integer) = 1 or -1, so not imaginary
754
+ if f.is_even:
755
+ return False
756
+ # exp(pi*integer + pi/2) = I or -I, so it is imaginary
757
+ if f.is_odd:
758
+ return True
759
+ return None
760
+
761
+ if self.exp.is_imaginary:
762
+ from sympy.functions.elementary.exponential import log
763
+ imlog = log(self.base).is_imaginary
764
+ if imlog is not None:
765
+ return False # I**i -> real; (2*I)**i -> complex ==> not imaginary
766
+
767
+ if self.base.is_extended_real and self.exp.is_extended_real:
768
+ if self.base.is_positive:
769
+ return False
770
+ else:
771
+ rat = self.exp.is_rational
772
+ if not rat:
773
+ return rat
774
+ if self.exp.is_integer:
775
+ return False
776
+ else:
777
+ half = (2*self.exp).is_integer
778
+ if half:
779
+ return self.base.is_negative
780
+ return half
781
+
782
+ if self.base.is_extended_real is False: # we already know it's not imag
783
+ from sympy.functions.elementary.complexes import arg
784
+ i = arg(self.base)*self.exp/S.Pi
785
+ isodd = (2*i).is_odd
786
+ if isodd is not None:
787
+ return isodd
788
+
789
+ def _eval_is_odd(self):
790
+ if self.exp.is_integer:
791
+ if self.exp.is_positive:
792
+ return self.base.is_odd
793
+ elif self.exp.is_nonnegative and self.base.is_odd:
794
+ return True
795
+ elif self.base is S.NegativeOne:
796
+ return True
797
+
798
+ def _eval_is_finite(self):
799
+ if self.exp.is_negative:
800
+ if self.base.is_zero:
801
+ return False
802
+ if self.base.is_infinite or self.base.is_nonzero:
803
+ return True
804
+ c1 = self.base.is_finite
805
+ if c1 is None:
806
+ return
807
+ c2 = self.exp.is_finite
808
+ if c2 is None:
809
+ return
810
+ if c1 and c2:
811
+ if self.exp.is_nonnegative or fuzzy_not(self.base.is_zero):
812
+ return True
813
+
814
+ def _eval_is_prime(self):
815
+ '''
816
+ An integer raised to the n(>=2)-th power cannot be a prime.
817
+ '''
818
+ if self.base.is_integer and self.exp.is_integer and (self.exp - 1).is_positive:
819
+ return False
820
+
821
+ def _eval_is_composite(self):
822
+ """
823
+ A power is composite if both base and exponent are greater than 1
824
+ """
825
+ if (self.base.is_integer and self.exp.is_integer and
826
+ ((self.base - 1).is_positive and (self.exp - 1).is_positive or
827
+ (self.base + 1).is_negative and self.exp.is_positive and self.exp.is_even)):
828
+ return True
829
+
830
+ def _eval_is_polar(self):
831
+ return self.base.is_polar
832
+
833
+ def _eval_subs(self, old, new):
834
+ from sympy.calculus.accumulationbounds import AccumBounds
835
+
836
+ if isinstance(self.exp, AccumBounds):
837
+ b = self.base.subs(old, new)
838
+ e = self.exp.subs(old, new)
839
+ if isinstance(e, AccumBounds):
840
+ return e.__rpow__(b)
841
+ return self.func(b, e)
842
+
843
+ from sympy.functions.elementary.exponential import exp, log
844
+
845
+ def _check(ct1, ct2, old):
846
+ """Return (bool, pow, remainder_pow) where, if bool is True, then the
847
+ exponent of Pow `old` will combine with `pow` so the substitution
848
+ is valid, otherwise bool will be False.
849
+
850
+ For noncommutative objects, `pow` will be an integer, and a factor
851
+ `Pow(old.base, remainder_pow)` needs to be included. If there is
852
+ no such factor, None is returned. For commutative objects,
853
+ remainder_pow is always None.
854
+
855
+ cti are the coefficient and terms of an exponent of self or old
856
+ In this _eval_subs routine a change like (b**(2*x)).subs(b**x, y)
857
+ will give y**2 since (b**x)**2 == b**(2*x); if that equality does
858
+ not hold then the substitution should not occur so `bool` will be
859
+ False.
860
+
861
+ """
862
+ coeff1, terms1 = ct1
863
+ coeff2, terms2 = ct2
864
+ if terms1 == terms2:
865
+ if old.is_commutative:
866
+ # Allow fractional powers for commutative objects
867
+ pow = coeff1/coeff2
868
+ try:
869
+ as_int(pow, strict=False)
870
+ combines = True
871
+ except ValueError:
872
+ b, e = old.as_base_exp()
873
+ # These conditions ensure that (b**e)**f == b**(e*f) for any f
874
+ combines = b.is_positive and e.is_real or b.is_nonnegative and e.is_nonnegative
875
+
876
+ return combines, pow, None
877
+ else:
878
+ # With noncommutative symbols, substitute only integer powers
879
+ if not isinstance(terms1, tuple):
880
+ terms1 = (terms1,)
881
+ if not all(term.is_integer for term in terms1):
882
+ return False, None, None
883
+
884
+ try:
885
+ # Round pow toward zero
886
+ pow, remainder = divmod(as_int(coeff1), as_int(coeff2))
887
+ if pow < 0 and remainder != 0:
888
+ pow += 1
889
+ remainder -= as_int(coeff2)
890
+
891
+ if remainder == 0:
892
+ remainder_pow = None
893
+ else:
894
+ remainder_pow = Mul(remainder, *terms1)
895
+
896
+ return True, pow, remainder_pow
897
+ except ValueError:
898
+ # Can't substitute
899
+ pass
900
+
901
+ return False, None, None
902
+
903
+ if old == self.base or (old == exp and self.base == S.Exp1):
904
+ if new.is_Function and isinstance(new, Callable):
905
+ return new(self.exp._subs(old, new))
906
+ else:
907
+ return new**self.exp._subs(old, new)
908
+
909
+ # issue 10829: (4**x - 3*y + 2).subs(2**x, y) -> y**2 - 3*y + 2
910
+ if isinstance(old, self.func) and self.exp == old.exp:
911
+ l = log(self.base, old.base)
912
+ if l.is_Number:
913
+ return Pow(new, l)
914
+
915
+ if isinstance(old, self.func) and self.base == old.base:
916
+ if self.exp.is_Add is False:
917
+ ct1 = self.exp.as_independent(Symbol, as_Add=False)
918
+ ct2 = old.exp.as_independent(Symbol, as_Add=False)
919
+ ok, pow, remainder_pow = _check(ct1, ct2, old)
920
+ if ok:
921
+ # issue 5180: (x**(6*y)).subs(x**(3*y),z)->z**2
922
+ result = self.func(new, pow)
923
+ if remainder_pow is not None:
924
+ result = Mul(result, Pow(old.base, remainder_pow))
925
+ return result
926
+ else: # b**(6*x + a).subs(b**(3*x), y) -> y**2 * b**a
927
+ # exp(exp(x) + exp(x**2)).subs(exp(exp(x)), w) -> w * exp(exp(x**2))
928
+ oarg = old.exp
929
+ new_l = []
930
+ o_al = []
931
+ ct2 = oarg.as_coeff_mul()
932
+ for a in self.exp.args:
933
+ newa = a._subs(old, new)
934
+ ct1 = newa.as_coeff_mul()
935
+ ok, pow, remainder_pow = _check(ct1, ct2, old)
936
+ if ok:
937
+ new_l.append(new**pow)
938
+ if remainder_pow is not None:
939
+ o_al.append(remainder_pow)
940
+ continue
941
+ elif not old.is_commutative and not newa.is_integer:
942
+ # If any term in the exponent is non-integer,
943
+ # we do not do any substitutions in the noncommutative case
944
+ return
945
+ o_al.append(newa)
946
+ if new_l:
947
+ expo = Add(*o_al)
948
+ new_l.append(Pow(self.base, expo, evaluate=False) if expo != 1 else self.base)
949
+ return Mul(*new_l)
950
+
951
+ if (isinstance(old, exp) or (old.is_Pow and old.base is S.Exp1)) and self.exp.is_extended_real and self.base.is_positive:
952
+ ct1 = old.exp.as_independent(Symbol, as_Add=False)
953
+ ct2 = (self.exp*log(self.base)).as_independent(
954
+ Symbol, as_Add=False)
955
+ ok, pow, remainder_pow = _check(ct1, ct2, old)
956
+ if ok:
957
+ result = self.func(new, pow) # (2**x).subs(exp(x*log(2)), z) -> z
958
+ if remainder_pow is not None:
959
+ result = Mul(result, Pow(old.base, remainder_pow))
960
+ return result
961
+
962
+ def as_base_exp(self):
963
+ """Return base and exp of self.
964
+
965
+ Explanation
966
+ ===========
967
+
968
+ If base a Rational less than 1, then return 1/Rational, -exp.
969
+ If this extra processing is not needed, the base and exp
970
+ properties will give the raw arguments.
971
+
972
+ Examples
973
+ ========
974
+
975
+ >>> from sympy import Pow, S
976
+ >>> p = Pow(S.Half, 2, evaluate=False)
977
+ >>> p.as_base_exp()
978
+ (2, -2)
979
+ >>> p.args
980
+ (1/2, 2)
981
+ >>> p.base, p.exp
982
+ (1/2, 2)
983
+
984
+ """
985
+
986
+ b, e = self.args
987
+ if b.is_Rational and b.p < b.q and b.p > 0:
988
+ return 1/b, -e
989
+ return b, e
990
+
991
+ def _eval_adjoint(self):
992
+ from sympy.functions.elementary.complexes import adjoint
993
+ i, p = self.exp.is_integer, self.base.is_positive
994
+ if i:
995
+ return adjoint(self.base)**self.exp
996
+ if p:
997
+ return self.base**adjoint(self.exp)
998
+ if i is False and p is False:
999
+ expanded = expand_complex(self)
1000
+ if expanded != self:
1001
+ return adjoint(expanded)
1002
+
1003
+ def _eval_conjugate(self):
1004
+ from sympy.functions.elementary.complexes import conjugate as c
1005
+ i, p = self.exp.is_integer, self.base.is_positive
1006
+ if i:
1007
+ return c(self.base)**self.exp
1008
+ if p:
1009
+ return self.base**c(self.exp)
1010
+ if i is False and p is False:
1011
+ expanded = expand_complex(self)
1012
+ if expanded != self:
1013
+ return c(expanded)
1014
+ if self.is_extended_real:
1015
+ return self
1016
+
1017
+ def _eval_transpose(self):
1018
+ from sympy.functions.elementary.complexes import transpose
1019
+ if self.base == S.Exp1:
1020
+ return self.func(S.Exp1, self.exp.transpose())
1021
+ i, p = self.exp.is_integer, (self.base.is_complex or self.base.is_infinite)
1022
+ if p:
1023
+ return self.base**self.exp
1024
+ if i:
1025
+ return transpose(self.base)**self.exp
1026
+ if i is False and p is False:
1027
+ expanded = expand_complex(self)
1028
+ if expanded != self:
1029
+ return transpose(expanded)
1030
+
1031
+ def _eval_expand_power_exp(self, **hints):
1032
+ """a**(n + m) -> a**n*a**m"""
1033
+ b = self.base
1034
+ e = self.exp
1035
+ if b == S.Exp1:
1036
+ from sympy.concrete.summations import Sum
1037
+ if isinstance(e, Sum) and e.is_commutative:
1038
+ from sympy.concrete.products import Product
1039
+ return Product(self.func(b, e.function), *e.limits)
1040
+ if e.is_Add and (hints.get('force', False) or
1041
+ b.is_zero is False or e._all_nonneg_or_nonppos()):
1042
+ if e.is_commutative:
1043
+ return Mul(*[self.func(b, x) for x in e.args])
1044
+ if b.is_commutative:
1045
+ c, nc = sift(e.args, lambda x: x.is_commutative, binary=True)
1046
+ if c:
1047
+ return Mul(*[self.func(b, x) for x in c]
1048
+ )*b**Add._from_args(nc)
1049
+ return self
1050
+
1051
+ def _eval_expand_power_base(self, **hints):
1052
+ """(a*b)**n -> a**n * b**n"""
1053
+ force = hints.get('force', False)
1054
+
1055
+ b = self.base
1056
+ e = self.exp
1057
+ if not b.is_Mul:
1058
+ return self
1059
+
1060
+ cargs, nc = b.args_cnc(split_1=False)
1061
+
1062
+ # expand each term - this is top-level-only
1063
+ # expansion but we have to watch out for things
1064
+ # that don't have an _eval_expand method
1065
+ if nc:
1066
+ nc = [i._eval_expand_power_base(**hints)
1067
+ if hasattr(i, '_eval_expand_power_base') else i
1068
+ for i in nc]
1069
+
1070
+ if e.is_Integer:
1071
+ if e.is_positive:
1072
+ rv = Mul(*nc*e)
1073
+ else:
1074
+ rv = Mul(*[i**-1 for i in nc[::-1]]*-e)
1075
+ if cargs:
1076
+ rv *= Mul(*cargs)**e
1077
+ return rv
1078
+
1079
+ if not cargs:
1080
+ return self.func(Mul(*nc), e, evaluate=False)
1081
+
1082
+ nc = [Mul(*nc)]
1083
+
1084
+ # sift the commutative bases
1085
+ other, maybe_real = sift(cargs, lambda x: x.is_extended_real is False,
1086
+ binary=True)
1087
+ def pred(x):
1088
+ if x is S.ImaginaryUnit:
1089
+ return S.ImaginaryUnit
1090
+ polar = x.is_polar
1091
+ if polar:
1092
+ return True
1093
+ if polar is None:
1094
+ return fuzzy_bool(x.is_extended_nonnegative)
1095
+ sifted = sift(maybe_real, pred)
1096
+ nonneg = sifted[True]
1097
+ other += sifted[None]
1098
+ neg = sifted[False]
1099
+ imag = sifted[S.ImaginaryUnit]
1100
+ if imag:
1101
+ I = S.ImaginaryUnit
1102
+ i = len(imag) % 4
1103
+ if i == 0:
1104
+ pass
1105
+ elif i == 1:
1106
+ other.append(I)
1107
+ elif i == 2:
1108
+ if neg:
1109
+ nonn = -neg.pop()
1110
+ if nonn is not S.One:
1111
+ nonneg.append(nonn)
1112
+ else:
1113
+ neg.append(S.NegativeOne)
1114
+ else:
1115
+ if neg:
1116
+ nonn = -neg.pop()
1117
+ if nonn is not S.One:
1118
+ nonneg.append(nonn)
1119
+ else:
1120
+ neg.append(S.NegativeOne)
1121
+ other.append(I)
1122
+ del imag
1123
+
1124
+ # bring out the bases that can be separated from the base
1125
+
1126
+ if force or e.is_integer:
1127
+ # treat all commutatives the same and put nc in other
1128
+ cargs = nonneg + neg + other
1129
+ other = nc
1130
+ else:
1131
+ # this is just like what is happening automatically, except
1132
+ # that now we are doing it for an arbitrary exponent for which
1133
+ # no automatic expansion is done
1134
+
1135
+ assert not e.is_Integer
1136
+
1137
+ # handle negatives by making them all positive and putting
1138
+ # the residual -1 in other
1139
+ if len(neg) > 1:
1140
+ o = S.One
1141
+ if not other and neg[0].is_Number:
1142
+ o *= neg.pop(0)
1143
+ if len(neg) % 2:
1144
+ o = -o
1145
+ for n in neg:
1146
+ nonneg.append(-n)
1147
+ if o is not S.One:
1148
+ other.append(o)
1149
+ elif neg and other:
1150
+ if neg[0].is_Number and neg[0] is not S.NegativeOne:
1151
+ other.append(S.NegativeOne)
1152
+ nonneg.append(-neg[0])
1153
+ else:
1154
+ other.extend(neg)
1155
+ else:
1156
+ other.extend(neg)
1157
+ del neg
1158
+
1159
+ cargs = nonneg
1160
+ other += nc
1161
+
1162
+ rv = S.One
1163
+ if cargs:
1164
+ if e.is_Rational:
1165
+ npow, cargs = sift(cargs, lambda x: x.is_Pow and
1166
+ x.exp.is_Rational and x.base.is_number,
1167
+ binary=True)
1168
+ rv = Mul(*[self.func(b.func(*b.args), e) for b in npow])
1169
+ rv *= Mul(*[self.func(b, e, evaluate=False) for b in cargs])
1170
+ if other:
1171
+ rv *= self.func(Mul(*other), e, evaluate=False)
1172
+ return rv
1173
+
1174
+ def _eval_expand_multinomial(self, **hints):
1175
+ """(a + b + ..)**n -> a**n + n*a**(n-1)*b + .., n is nonzero integer"""
1176
+
1177
+ base, exp = self.args
1178
+ result = self
1179
+
1180
+ if exp.is_Rational and exp.p > 0 and base.is_Add:
1181
+ if not exp.is_Integer:
1182
+ n = Integer(exp.p // exp.q)
1183
+
1184
+ if not n:
1185
+ return result
1186
+ else:
1187
+ radical, result = self.func(base, exp - n), []
1188
+
1189
+ expanded_base_n = self.func(base, n)
1190
+ if expanded_base_n.is_Pow:
1191
+ expanded_base_n = \
1192
+ expanded_base_n._eval_expand_multinomial()
1193
+ for term in Add.make_args(expanded_base_n):
1194
+ result.append(term*radical)
1195
+
1196
+ return Add(*result)
1197
+
1198
+ n = int(exp)
1199
+
1200
+ if base.is_commutative:
1201
+ order_terms, other_terms = [], []
1202
+
1203
+ for b in base.args:
1204
+ if b.is_Order:
1205
+ order_terms.append(b)
1206
+ else:
1207
+ other_terms.append(b)
1208
+
1209
+ if order_terms:
1210
+ # (f(x) + O(x^n))^m -> f(x)^m + m*f(x)^{m-1} *O(x^n)
1211
+ f = Add(*other_terms)
1212
+ o = Add(*order_terms)
1213
+
1214
+ if n == 2:
1215
+ return expand_multinomial(f**n, deep=False) + n*f*o
1216
+ else:
1217
+ g = expand_multinomial(f**(n - 1), deep=False)
1218
+ return expand_mul(f*g, deep=False) + n*g*o
1219
+
1220
+ if base.is_number:
1221
+ # Efficiently expand expressions of the form (a + b*I)**n
1222
+ # where 'a' and 'b' are real numbers and 'n' is integer.
1223
+ a, b = base.as_real_imag()
1224
+
1225
+ if a.is_Rational and b.is_Rational:
1226
+ if not a.is_Integer:
1227
+ if not b.is_Integer:
1228
+ k = self.func(a.q * b.q, n)
1229
+ a, b = a.p*b.q, a.q*b.p
1230
+ else:
1231
+ k = self.func(a.q, n)
1232
+ a, b = a.p, a.q*b
1233
+ elif not b.is_Integer:
1234
+ k = self.func(b.q, n)
1235
+ a, b = a*b.q, b.p
1236
+ else:
1237
+ k = 1
1238
+
1239
+ a, b, c, d = int(a), int(b), 1, 0
1240
+
1241
+ while n:
1242
+ if n & 1:
1243
+ c, d = a*c - b*d, b*c + a*d
1244
+ n -= 1
1245
+ a, b = a*a - b*b, 2*a*b
1246
+ n //= 2
1247
+
1248
+ I = S.ImaginaryUnit
1249
+
1250
+ if k == 1:
1251
+ return c + I*d
1252
+ else:
1253
+ return Integer(c)/k + I*d/k
1254
+
1255
+ p = other_terms
1256
+ # (x + y)**3 -> x**3 + 3*x**2*y + 3*x*y**2 + y**3
1257
+ # in this particular example:
1258
+ # p = [x,y]; n = 3
1259
+ # so now it's easy to get the correct result -- we get the
1260
+ # coefficients first:
1261
+ from sympy.ntheory.multinomial import multinomial_coefficients
1262
+ from sympy.polys.polyutils import basic_from_dict
1263
+ expansion_dict = multinomial_coefficients(len(p), n)
1264
+ # in our example: {(3, 0): 1, (1, 2): 3, (0, 3): 1, (2, 1): 3}
1265
+ # and now construct the expression.
1266
+ return basic_from_dict(expansion_dict, *p)
1267
+ else:
1268
+ if n == 2:
1269
+ return Add(*[f*g for f in base.args for g in base.args])
1270
+ else:
1271
+ multi = (base**(n - 1))._eval_expand_multinomial()
1272
+ if multi.is_Add:
1273
+ return Add(*[f*g for f in base.args
1274
+ for g in multi.args])
1275
+ else:
1276
+ # XXX can this ever happen if base was an Add?
1277
+ return Add(*[f*multi for f in base.args])
1278
+ elif (exp.is_Rational and exp.p < 0 and base.is_Add and
1279
+ abs(exp.p) > exp.q):
1280
+ return 1 / self.func(base, -exp)._eval_expand_multinomial()
1281
+ elif exp.is_Add and base.is_Number and (hints.get('force', False) or
1282
+ base.is_zero is False or exp._all_nonneg_or_nonppos()):
1283
+ # a + b a b
1284
+ # n --> n n, where n, a, b are Numbers
1285
+ # XXX should be in expand_power_exp?
1286
+ coeff, tail = [], []
1287
+ for term in exp.args:
1288
+ if term.is_Number:
1289
+ coeff.append(self.func(base, term))
1290
+ else:
1291
+ tail.append(term)
1292
+ return Mul(*(coeff + [self.func(base, Add._from_args(tail))]))
1293
+ else:
1294
+ return result
1295
+
1296
+ def as_real_imag(self, deep=True, **hints):
1297
+ if self.exp.is_Integer:
1298
+ from sympy.polys.polytools import poly
1299
+
1300
+ exp = self.exp
1301
+ re_e, im_e = self.base.as_real_imag(deep=deep)
1302
+ if not im_e:
1303
+ return self, S.Zero
1304
+ a, b = symbols('a b', cls=Dummy)
1305
+ if exp >= 0:
1306
+ if re_e.is_Number and im_e.is_Number:
1307
+ # We can be more efficient in this case
1308
+ expr = expand_multinomial(self.base**exp)
1309
+ if expr != self:
1310
+ return expr.as_real_imag()
1311
+
1312
+ expr = poly(
1313
+ (a + b)**exp) # a = re, b = im; expr = (a + b*I)**exp
1314
+ else:
1315
+ mag = re_e**2 + im_e**2
1316
+ re_e, im_e = re_e/mag, -im_e/mag
1317
+ if re_e.is_Number and im_e.is_Number:
1318
+ # We can be more efficient in this case
1319
+ expr = expand_multinomial((re_e + im_e*S.ImaginaryUnit)**-exp)
1320
+ if expr != self:
1321
+ return expr.as_real_imag()
1322
+
1323
+ expr = poly((a + b)**-exp)
1324
+
1325
+ # Terms with even b powers will be real
1326
+ r = [i for i in expr.terms() if not i[0][1] % 2]
1327
+ re_part = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
1328
+ # Terms with odd b powers will be imaginary
1329
+ r = [i for i in expr.terms() if i[0][1] % 4 == 1]
1330
+ im_part1 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
1331
+ r = [i for i in expr.terms() if i[0][1] % 4 == 3]
1332
+ im_part3 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
1333
+
1334
+ return (re_part.subs({a: re_e, b: S.ImaginaryUnit*im_e}),
1335
+ im_part1.subs({a: re_e, b: im_e}) + im_part3.subs({a: re_e, b: -im_e}))
1336
+
1337
+ from sympy.functions.elementary.trigonometric import atan2, cos, sin
1338
+
1339
+ if self.exp.is_Rational:
1340
+ re_e, im_e = self.base.as_real_imag(deep=deep)
1341
+
1342
+ if im_e.is_zero and self.exp is S.Half:
1343
+ if re_e.is_extended_nonnegative:
1344
+ return self, S.Zero
1345
+ if re_e.is_extended_nonpositive:
1346
+ return S.Zero, (-self.base)**self.exp
1347
+
1348
+ # XXX: This is not totally correct since for x**(p/q) with
1349
+ # x being imaginary there are actually q roots, but
1350
+ # only a single one is returned from here.
1351
+ r = self.func(self.func(re_e, 2) + self.func(im_e, 2), S.Half)
1352
+
1353
+ t = atan2(im_e, re_e)
1354
+
1355
+ rp, tp = self.func(r, self.exp), t*self.exp
1356
+
1357
+ return rp*cos(tp), rp*sin(tp)
1358
+ elif self.base is S.Exp1:
1359
+ from sympy.functions.elementary.exponential import exp
1360
+ re_e, im_e = self.exp.as_real_imag()
1361
+ if deep:
1362
+ re_e = re_e.expand(deep, **hints)
1363
+ im_e = im_e.expand(deep, **hints)
1364
+ c, s = cos(im_e), sin(im_e)
1365
+ return exp(re_e)*c, exp(re_e)*s
1366
+ else:
1367
+ from sympy.functions.elementary.complexes import im, re
1368
+ if deep:
1369
+ hints['complex'] = False
1370
+
1371
+ expanded = self.expand(deep, **hints)
1372
+ if hints.get('ignore') == expanded:
1373
+ return None
1374
+ else:
1375
+ return (re(expanded), im(expanded))
1376
+ else:
1377
+ return re(self), im(self)
1378
+
1379
+ def _eval_derivative(self, s):
1380
+ from sympy.functions.elementary.exponential import log
1381
+ dbase = self.base.diff(s)
1382
+ dexp = self.exp.diff(s)
1383
+ return self * (dexp * log(self.base) + dbase * self.exp/self.base)
1384
+
1385
+ def _eval_evalf(self, prec):
1386
+ base, exp = self.as_base_exp()
1387
+ if base == S.Exp1:
1388
+ # Use mpmath function associated to class "exp":
1389
+ from sympy.functions.elementary.exponential import exp as exp_function
1390
+ return exp_function(self.exp, evaluate=False)._eval_evalf(prec)
1391
+ base = base._evalf(prec)
1392
+ if not exp.is_Integer:
1393
+ exp = exp._evalf(prec)
1394
+ if exp.is_negative and base.is_number and base.is_extended_real is False:
1395
+ base = base.conjugate() / (base * base.conjugate())._evalf(prec)
1396
+ exp = -exp
1397
+ return self.func(base, exp).expand()
1398
+ return self.func(base, exp)
1399
+
1400
+ def _eval_is_polynomial(self, syms):
1401
+ if self.exp.has(*syms):
1402
+ return False
1403
+
1404
+ if self.base.has(*syms):
1405
+ return bool(self.base._eval_is_polynomial(syms) and
1406
+ self.exp.is_Integer and (self.exp >= 0))
1407
+ else:
1408
+ return True
1409
+
1410
+ def _eval_is_rational(self):
1411
+ # The evaluation of self.func below can be very expensive in the case
1412
+ # of integer**integer if the exponent is large. We should try to exit
1413
+ # before that if possible:
1414
+ if (self.exp.is_integer and self.base.is_rational
1415
+ and fuzzy_not(fuzzy_and([self.exp.is_negative, self.base.is_zero]))):
1416
+ return True
1417
+ p = self.func(*self.as_base_exp()) # in case it's unevaluated
1418
+ if not p.is_Pow:
1419
+ return p.is_rational
1420
+ b, e = p.as_base_exp()
1421
+ if e.is_Rational and b.is_Rational:
1422
+ # we didn't check that e is not an Integer
1423
+ # because Rational**Integer autosimplifies
1424
+ return False
1425
+ if e.is_integer:
1426
+ if b.is_rational:
1427
+ if fuzzy_not(b.is_zero) or e.is_nonnegative:
1428
+ return True
1429
+ if b == e: # always rational, even for 0**0
1430
+ return True
1431
+ elif b.is_irrational:
1432
+ return e.is_zero
1433
+ if b is S.Exp1:
1434
+ if e.is_rational and e.is_nonzero:
1435
+ return False
1436
+
1437
+ def _eval_is_algebraic(self):
1438
+ def _is_one(expr):
1439
+ try:
1440
+ return (expr - 1).is_zero
1441
+ except ValueError:
1442
+ # when the operation is not allowed
1443
+ return False
1444
+
1445
+ if self.base.is_zero or _is_one(self.base):
1446
+ return True
1447
+ elif self.base is S.Exp1:
1448
+ s = self.func(*self.args)
1449
+ if s.func == self.func:
1450
+ if self.exp.is_nonzero:
1451
+ if self.exp.is_algebraic:
1452
+ return False
1453
+ elif (self.exp/S.Pi).is_rational:
1454
+ return False
1455
+ elif (self.exp/(S.ImaginaryUnit*S.Pi)).is_rational:
1456
+ return True
1457
+ else:
1458
+ return s.is_algebraic
1459
+ elif self.exp.is_rational:
1460
+ if self.base.is_algebraic is False:
1461
+ return self.exp.is_zero
1462
+ if self.base.is_zero is False:
1463
+ if self.exp.is_nonzero:
1464
+ return self.base.is_algebraic
1465
+ elif self.base.is_algebraic:
1466
+ return True
1467
+ if self.exp.is_positive:
1468
+ return self.base.is_algebraic
1469
+ elif self.base.is_algebraic and self.exp.is_algebraic:
1470
+ if ((fuzzy_not(self.base.is_zero)
1471
+ and fuzzy_not(_is_one(self.base)))
1472
+ or self.base.is_integer is False
1473
+ or self.base.is_irrational):
1474
+ return self.exp.is_rational
1475
+
1476
+ def _eval_is_rational_function(self, syms):
1477
+ if self.exp.has(*syms):
1478
+ return False
1479
+
1480
+ if self.base.has(*syms):
1481
+ return self.base._eval_is_rational_function(syms) and \
1482
+ self.exp.is_Integer
1483
+ else:
1484
+ return True
1485
+
1486
+ def _eval_is_meromorphic(self, x, a):
1487
+ # f**g is meromorphic if g is an integer and f is meromorphic.
1488
+ # E**(log(f)*g) is meromorphic if log(f)*g is meromorphic
1489
+ # and finite.
1490
+ base_merom = self.base._eval_is_meromorphic(x, a)
1491
+ exp_integer = self.exp.is_Integer
1492
+ if exp_integer:
1493
+ return base_merom
1494
+
1495
+ exp_merom = self.exp._eval_is_meromorphic(x, a)
1496
+ if base_merom is False:
1497
+ # f**g = E**(log(f)*g) may be meromorphic if the
1498
+ # singularities of log(f) and g cancel each other,
1499
+ # for example, if g = 1/log(f). Hence,
1500
+ return False if exp_merom else None
1501
+ elif base_merom is None:
1502
+ return None
1503
+
1504
+ b = self.base.subs(x, a)
1505
+ # b is extended complex as base is meromorphic.
1506
+ # log(base) is finite and meromorphic when b != 0, zoo.
1507
+ b_zero = b.is_zero
1508
+ if b_zero:
1509
+ log_defined = False
1510
+ else:
1511
+ log_defined = fuzzy_and((b.is_finite, fuzzy_not(b_zero)))
1512
+
1513
+ if log_defined is False: # zero or pole of base
1514
+ return exp_integer # False or None
1515
+ elif log_defined is None:
1516
+ return None
1517
+
1518
+ if not exp_merom:
1519
+ return exp_merom # False or None
1520
+
1521
+ return self.exp.subs(x, a).is_finite
1522
+
1523
+ def _eval_is_algebraic_expr(self, syms):
1524
+ if self.exp.has(*syms):
1525
+ return False
1526
+
1527
+ if self.base.has(*syms):
1528
+ return self.base._eval_is_algebraic_expr(syms) and \
1529
+ self.exp.is_Rational
1530
+ else:
1531
+ return True
1532
+
1533
+ def _eval_rewrite_as_exp(self, base, expo, **kwargs):
1534
+ from sympy.functions.elementary.exponential import exp, log
1535
+
1536
+ if base.is_zero or base.has(exp) or expo.has(exp):
1537
+ return base**expo
1538
+
1539
+ if base.has(Symbol):
1540
+ # delay evaluation if expo is non symbolic
1541
+ # (as exp(x*log(5)) automatically reduces to x**5)
1542
+ if global_parameters.exp_is_pow:
1543
+ return Pow(S.Exp1, log(base)*expo, evaluate=expo.has(Symbol))
1544
+ else:
1545
+ return exp(log(base)*expo, evaluate=expo.has(Symbol))
1546
+
1547
+ else:
1548
+ from sympy.functions.elementary.complexes import arg, Abs
1549
+ return exp((log(Abs(base)) + S.ImaginaryUnit*arg(base))*expo)
1550
+
1551
+ def as_numer_denom(self):
1552
+ if not self.is_commutative:
1553
+ return self, S.One
1554
+ base, exp = self.as_base_exp()
1555
+ n, d = base.as_numer_denom()
1556
+ # this should be the same as ExpBase.as_numer_denom wrt
1557
+ # exponent handling
1558
+ neg_exp = exp.is_negative
1559
+ if exp.is_Mul and not neg_exp and not exp.is_positive:
1560
+ neg_exp = exp.could_extract_minus_sign()
1561
+ int_exp = exp.is_integer
1562
+ # the denominator cannot be separated from the numerator if
1563
+ # its sign is unknown unless the exponent is an integer, e.g.
1564
+ # sqrt(a/b) != sqrt(a)/sqrt(b) when a=1 and b=-1. But if the
1565
+ # denominator is negative the numerator and denominator can
1566
+ # be negated and the denominator (now positive) separated.
1567
+ if not (d.is_extended_real or int_exp):
1568
+ n = base
1569
+ d = S.One
1570
+ dnonpos = d.is_nonpositive
1571
+ if dnonpos:
1572
+ n, d = -n, -d
1573
+ elif dnonpos is None and not int_exp:
1574
+ n = base
1575
+ d = S.One
1576
+ if neg_exp:
1577
+ n, d = d, n
1578
+ exp = -exp
1579
+ if exp.is_infinite:
1580
+ if n is S.One and d is not S.One:
1581
+ return n, self.func(d, exp)
1582
+ if n is not S.One and d is S.One:
1583
+ return self.func(n, exp), d
1584
+ return self.func(n, exp), self.func(d, exp)
1585
+
1586
+ def matches(self, expr, repl_dict=None, old=False):
1587
+ expr = _sympify(expr)
1588
+ if repl_dict is None:
1589
+ repl_dict = {}
1590
+
1591
+ # special case, pattern = 1 and expr.exp can match to 0
1592
+ if expr is S.One:
1593
+ d = self.exp.matches(S.Zero, repl_dict)
1594
+ if d is not None:
1595
+ return d
1596
+
1597
+ # make sure the expression to be matched is an Expr
1598
+ if not isinstance(expr, Expr):
1599
+ return None
1600
+
1601
+ b, e = expr.as_base_exp()
1602
+
1603
+ # special case number
1604
+ sb, se = self.as_base_exp()
1605
+ if sb.is_Symbol and se.is_Integer and expr:
1606
+ if e.is_rational:
1607
+ return sb.matches(b**(e/se), repl_dict)
1608
+ return sb.matches(expr**(1/se), repl_dict)
1609
+
1610
+ d = repl_dict.copy()
1611
+ d = self.base.matches(b, d)
1612
+ if d is None:
1613
+ return None
1614
+
1615
+ d = self.exp.xreplace(d).matches(e, d)
1616
+ if d is None:
1617
+ return Expr.matches(self, expr, repl_dict)
1618
+ return d
1619
+
1620
+ def _eval_nseries(self, x, n, logx, cdir=0):
1621
+ # NOTE! This function is an important part of the gruntz algorithm
1622
+ # for computing limits. It has to return a generalized power
1623
+ # series with coefficients in C(log, log(x)). In more detail:
1624
+ # It has to return an expression
1625
+ # c_0*x**e_0 + c_1*x**e_1 + ... (finitely many terms)
1626
+ # where e_i are numbers (not necessarily integers) and c_i are
1627
+ # expressions involving only numbers, the log function, and log(x).
1628
+ # The series expansion of b**e is computed as follows:
1629
+ # 1) We express b as f*(1 + g) where f is the leading term of b.
1630
+ # g has order O(x**d) where d is strictly positive.
1631
+ # 2) Then b**e = (f**e)*((1 + g)**e).
1632
+ # (1 + g)**e is computed using binomial series.
1633
+ from sympy.functions.elementary.exponential import exp, log
1634
+ from sympy.series.limits import limit
1635
+ from sympy.series.order import Order
1636
+ from sympy.core.sympify import sympify
1637
+ if self.base is S.Exp1:
1638
+ e_series = self.exp.nseries(x, n=n, logx=logx)
1639
+ if e_series.is_Order:
1640
+ return 1 + e_series
1641
+ e0 = limit(e_series.removeO(), x, 0)
1642
+ if e0 is S.NegativeInfinity:
1643
+ return Order(x**n, x)
1644
+ if e0 is S.Infinity:
1645
+ return self
1646
+ t = e_series - e0
1647
+ exp_series = term = exp(e0)
1648
+ # series of exp(e0 + t) in t
1649
+ for i in range(1, n):
1650
+ term *= t/i
1651
+ term = term.nseries(x, n=n, logx=logx)
1652
+ exp_series += term
1653
+ exp_series += Order(t**n, x)
1654
+ from sympy.simplify.powsimp import powsimp
1655
+ return powsimp(exp_series, deep=True, combine='exp')
1656
+ from sympy.simplify.powsimp import powdenest
1657
+ from .numbers import _illegal
1658
+ self = powdenest(self, force=True).trigsimp()
1659
+ b, e = self.as_base_exp()
1660
+
1661
+ if e.has(*_illegal):
1662
+ raise PoleError()
1663
+
1664
+ if e.has(x):
1665
+ return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
1666
+
1667
+ if logx is not None and b.has(log):
1668
+ from .symbol import Wild
1669
+ c, ex = symbols('c, ex', cls=Wild, exclude=[x])
1670
+ b = b.replace(log(c*x**ex), log(c) + ex*logx)
1671
+ self = b**e
1672
+
1673
+ b = b.removeO()
1674
+ try:
1675
+ from sympy.functions.special.gamma_functions import polygamma
1676
+ if b.has(polygamma, S.EulerGamma) and logx is not None:
1677
+ raise ValueError()
1678
+ _, m = b.leadterm(x)
1679
+ except (ValueError, NotImplementedError, PoleError):
1680
+ b = b._eval_nseries(x, n=max(2, n), logx=logx, cdir=cdir).removeO()
1681
+ if b.has(S.NaN, S.ComplexInfinity):
1682
+ raise NotImplementedError()
1683
+ _, m = b.leadterm(x)
1684
+
1685
+ if e.has(log):
1686
+ from sympy.simplify.simplify import logcombine
1687
+ e = logcombine(e).cancel()
1688
+
1689
+ if not (m.is_zero or e.is_number and e.is_real):
1690
+ if self == self._eval_as_leading_term(x, logx=logx, cdir=cdir):
1691
+ res = exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
1692
+ if res == exp(e*log(b)):
1693
+ return self
1694
+ return res
1695
+
1696
+ f = b.as_leading_term(x, logx=logx)
1697
+ g = (b/f - S.One).cancel(expand=False)
1698
+ if not m.is_number:
1699
+ raise NotImplementedError()
1700
+ maxpow = n - m*e
1701
+ if maxpow.has(Symbol):
1702
+ maxpow = sympify(n)
1703
+
1704
+ if maxpow.is_negative:
1705
+ return Order(x**(m*e), x)
1706
+
1707
+ if g.is_zero:
1708
+ r = f**e
1709
+ if r != self:
1710
+ r += Order(x**n, x)
1711
+ return r
1712
+
1713
+ def coeff_exp(term, x):
1714
+ coeff, exp = S.One, S.Zero
1715
+ for factor in Mul.make_args(term):
1716
+ if factor.has(x):
1717
+ base, exp = factor.as_base_exp()
1718
+ if base != x:
1719
+ try:
1720
+ return term.leadterm(x)
1721
+ except ValueError:
1722
+ return term, S.Zero
1723
+ else:
1724
+ coeff *= factor
1725
+ return coeff, exp
1726
+
1727
+ def mul(d1, d2):
1728
+ res = {}
1729
+ for e1, e2 in product(d1, d2):
1730
+ ex = e1 + e2
1731
+ if ex < maxpow:
1732
+ res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
1733
+ return res
1734
+
1735
+ try:
1736
+ c, d = g.leadterm(x, logx=logx)
1737
+ except (ValueError, NotImplementedError):
1738
+ if limit(g/x**maxpow, x, 0) == 0:
1739
+ # g has higher order zero
1740
+ return f**e + e*f**e*g # first term of binomial series
1741
+ else:
1742
+ raise NotImplementedError()
1743
+ if c.is_Float and d == S.Zero:
1744
+ # Convert floats like 0.5 to exact SymPy numbers like S.Half, to
1745
+ # prevent rounding errors which can induce wrong values of d leading
1746
+ # to a NotImplementedError being returned from the block below.
1747
+ from sympy.simplify.simplify import nsimplify
1748
+ _, d = nsimplify(g).leadterm(x, logx=logx)
1749
+ if not d.is_positive:
1750
+ g = g.simplify()
1751
+ if g.is_zero:
1752
+ return f**e
1753
+ _, d = g.leadterm(x, logx=logx)
1754
+ if not d.is_positive:
1755
+ g = ((b - f)/f).expand()
1756
+ _, d = g.leadterm(x, logx=logx)
1757
+ if not d.is_positive:
1758
+ raise NotImplementedError()
1759
+
1760
+ from sympy.functions.elementary.integers import ceiling
1761
+ gpoly = g._eval_nseries(x, n=ceiling(maxpow), logx=logx, cdir=cdir).removeO()
1762
+ gterms = {}
1763
+
1764
+ for term in Add.make_args(gpoly):
1765
+ co1, e1 = coeff_exp(term, x)
1766
+ gterms[e1] = gterms.get(e1, S.Zero) + co1
1767
+
1768
+ k = S.One
1769
+ terms = {S.Zero: S.One}
1770
+ tk = gterms
1771
+
1772
+ from sympy.functions.combinatorial.factorials import factorial, ff
1773
+
1774
+ while (k*d - maxpow).is_negative:
1775
+ coeff = ff(e, k)/factorial(k)
1776
+ for ex in tk:
1777
+ terms[ex] = terms.get(ex, S.Zero) + coeff*tk[ex]
1778
+ tk = mul(tk, gterms)
1779
+ k += S.One
1780
+
1781
+ from sympy.functions.elementary.complexes import im
1782
+
1783
+ if not e.is_integer and m.is_zero and f.is_negative:
1784
+ ndir = (b - f).dir(x, cdir)
1785
+ if im(ndir).is_negative:
1786
+ inco, inex = coeff_exp(f**e*(-1)**(-2*e), x)
1787
+ elif im(ndir).is_zero:
1788
+ inco, inex = coeff_exp(exp(e*log(b)).as_leading_term(x, logx=logx, cdir=cdir), x)
1789
+ else:
1790
+ inco, inex = coeff_exp(f**e, x)
1791
+ else:
1792
+ inco, inex = coeff_exp(f**e, x)
1793
+ res = S.Zero
1794
+
1795
+ for e1 in terms:
1796
+ ex = e1 + inex
1797
+ res += terms[e1]*inco*x**(ex)
1798
+
1799
+ if not (e.is_integer and e.is_positive and (e*d - n).is_nonpositive and
1800
+ res == _mexpand(self)):
1801
+ try:
1802
+ res += Order(x**n, x)
1803
+ except NotImplementedError:
1804
+ return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
1805
+ return res
1806
+
1807
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
1808
+ from sympy.functions.elementary.exponential import exp, log
1809
+ e = self.exp
1810
+ b = self.base
1811
+ if self.base is S.Exp1:
1812
+ arg = e.as_leading_term(x, logx=logx)
1813
+ arg0 = arg.subs(x, 0)
1814
+ if arg0 is S.NaN:
1815
+ arg0 = arg.limit(x, 0)
1816
+ if arg0.is_infinite is False:
1817
+ return S.Exp1**arg0
1818
+ raise PoleError("Cannot expand %s around 0" % (self))
1819
+ elif e.has(x):
1820
+ lt = exp(e * log(b))
1821
+ return lt.as_leading_term(x, logx=logx, cdir=cdir)
1822
+ else:
1823
+ from sympy.functions.elementary.complexes import im
1824
+ try:
1825
+ f = b.as_leading_term(x, logx=logx, cdir=cdir)
1826
+ except PoleError:
1827
+ return self
1828
+ if not e.is_integer and f.is_negative and not f.has(x):
1829
+ ndir = (b - f).dir(x, cdir)
1830
+ if im(ndir).is_negative:
1831
+ # Normally, f**e would evaluate to exp(e*log(f)) but on branch cuts
1832
+ # an other value is expected through the following computation
1833
+ # exp(e*(log(f) - 2*pi*I)) == f**e*exp(-2*e*pi*I) == f**e*(-1)**(-2*e).
1834
+ return self.func(f, e) * (-1)**(-2*e)
1835
+ elif im(ndir).is_zero:
1836
+ log_leadterm = log(b)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1837
+ if log_leadterm.is_infinite is False:
1838
+ return exp(e*log_leadterm)
1839
+ return self.func(f, e)
1840
+
1841
+ @cacheit
1842
+ def _taylor_term(self, n, x, *previous_terms): # of (1 + x)**e
1843
+ from sympy.functions.combinatorial.factorials import binomial
1844
+ return binomial(self.exp, n) * self.func(x, n)
1845
+
1846
+ def taylor_term(self, n, x, *previous_terms):
1847
+ if self.base is not S.Exp1:
1848
+ return super().taylor_term(n, x, *previous_terms)
1849
+ if n < 0:
1850
+ return S.Zero
1851
+ if n == 0:
1852
+ return S.One
1853
+ from .sympify import sympify
1854
+ x = sympify(x)
1855
+ if previous_terms:
1856
+ p = previous_terms[-1]
1857
+ if p is not None:
1858
+ return p * x / n
1859
+ from sympy.functions.combinatorial.factorials import factorial
1860
+ return x**n/factorial(n)
1861
+
1862
+ def _eval_rewrite_as_sin(self, base, exp):
1863
+ if self.base is S.Exp1:
1864
+ from sympy.functions.elementary.trigonometric import sin
1865
+ return sin(S.ImaginaryUnit*self.exp + S.Pi/2) - S.ImaginaryUnit*sin(S.ImaginaryUnit*self.exp)
1866
+
1867
+ def _eval_rewrite_as_cos(self, base, exp):
1868
+ if self.base is S.Exp1:
1869
+ from sympy.functions.elementary.trigonometric import cos
1870
+ return cos(S.ImaginaryUnit*self.exp) + S.ImaginaryUnit*cos(S.ImaginaryUnit*self.exp + S.Pi/2)
1871
+
1872
+ def _eval_rewrite_as_tanh(self, base, exp):
1873
+ if self.base is S.Exp1:
1874
+ from sympy.functions.elementary.hyperbolic import tanh
1875
+ return (1 + tanh(self.exp/2))/(1 - tanh(self.exp/2))
1876
+
1877
+ def _eval_rewrite_as_sqrt(self, base, exp, **kwargs):
1878
+ from sympy.functions.elementary.trigonometric import sin, cos
1879
+ if base is not S.Exp1:
1880
+ return None
1881
+ if exp.is_Mul:
1882
+ coeff = exp.coeff(S.Pi * S.ImaginaryUnit)
1883
+ if coeff and coeff.is_number:
1884
+ cosine, sine = cos(S.Pi*coeff), sin(S.Pi*coeff)
1885
+ if not isinstance(cosine, cos) and not isinstance (sine, sin):
1886
+ return cosine + S.ImaginaryUnit*sine
1887
+
1888
+ def as_content_primitive(self, radical=False, clear=True):
1889
+ """Return the tuple (R, self/R) where R is the positive Rational
1890
+ extracted from self.
1891
+
1892
+ Examples
1893
+ ========
1894
+
1895
+ >>> from sympy import sqrt
1896
+ >>> sqrt(4 + 4*sqrt(2)).as_content_primitive()
1897
+ (2, sqrt(1 + sqrt(2)))
1898
+ >>> sqrt(3 + 3*sqrt(2)).as_content_primitive()
1899
+ (1, sqrt(3)*sqrt(1 + sqrt(2)))
1900
+
1901
+ >>> from sympy import expand_power_base, powsimp, Mul
1902
+ >>> from sympy.abc import x, y
1903
+
1904
+ >>> ((2*x + 2)**2).as_content_primitive()
1905
+ (4, (x + 1)**2)
1906
+ >>> (4**((1 + y)/2)).as_content_primitive()
1907
+ (2, 4**(y/2))
1908
+ >>> (3**((1 + y)/2)).as_content_primitive()
1909
+ (1, 3**((y + 1)/2))
1910
+ >>> (3**((5 + y)/2)).as_content_primitive()
1911
+ (9, 3**((y + 1)/2))
1912
+ >>> eq = 3**(2 + 2*x)
1913
+ >>> powsimp(eq) == eq
1914
+ True
1915
+ >>> eq.as_content_primitive()
1916
+ (9, 3**(2*x))
1917
+ >>> powsimp(Mul(*_))
1918
+ 3**(2*x + 2)
1919
+
1920
+ >>> eq = (2 + 2*x)**y
1921
+ >>> s = expand_power_base(eq); s.is_Mul, s
1922
+ (False, (2*x + 2)**y)
1923
+ >>> eq.as_content_primitive()
1924
+ (1, (2*(x + 1))**y)
1925
+ >>> s = expand_power_base(_[1]); s.is_Mul, s
1926
+ (True, 2**y*(x + 1)**y)
1927
+
1928
+ See docstring of Expr.as_content_primitive for more examples.
1929
+ """
1930
+
1931
+ b, e = self.as_base_exp()
1932
+ b = _keep_coeff(*b.as_content_primitive(radical=radical, clear=clear))
1933
+ ce, pe = e.as_content_primitive(radical=radical, clear=clear)
1934
+ if b.is_Rational:
1935
+ #e
1936
+ #= ce*pe
1937
+ #= ce*(h + t)
1938
+ #= ce*h + ce*t
1939
+ #=> self
1940
+ #= b**(ce*h)*b**(ce*t)
1941
+ #= b**(cehp/cehq)*b**(ce*t)
1942
+ #= b**(iceh + r/cehq)*b**(ce*t)
1943
+ #= b**(iceh)*b**(r/cehq)*b**(ce*t)
1944
+ #= b**(iceh)*b**(ce*t + r/cehq)
1945
+ h, t = pe.as_coeff_Add()
1946
+ if h.is_Rational and b != S.Zero:
1947
+ ceh = ce*h
1948
+ c = self.func(b, ceh)
1949
+ r = S.Zero
1950
+ if not c.is_Rational:
1951
+ iceh, r = divmod(ceh.p, ceh.q)
1952
+ c = self.func(b, iceh)
1953
+ return c, self.func(b, _keep_coeff(ce, t + r/ce/ceh.q))
1954
+ e = _keep_coeff(ce, pe)
1955
+ # b**e = (h*t)**e = h**e*t**e = c*m*t**e
1956
+ if e.is_Rational and b.is_Mul:
1957
+ h, t = b.as_content_primitive(radical=radical, clear=clear) # h is positive
1958
+ c, m = self.func(h, e).as_coeff_Mul() # so c is positive
1959
+ m, me = m.as_base_exp()
1960
+ if m is S.One or me == e: # probably always true
1961
+ # return the following, not return c, m*Pow(t, e)
1962
+ # which would change Pow into Mul; we let SymPy
1963
+ # decide what to do by using the unevaluated Mul, e.g
1964
+ # should it stay as sqrt(2 + 2*sqrt(5)) or become
1965
+ # sqrt(2)*sqrt(1 + sqrt(5))
1966
+ return c, self.func(_keep_coeff(m, t), e)
1967
+ return S.One, self.func(b, e)
1968
+
1969
+ def is_constant(self, *wrt, **flags):
1970
+ expr = self
1971
+ if flags.get('simplify', True):
1972
+ expr = expr.simplify()
1973
+ b, e = expr.as_base_exp()
1974
+ bz = b.equals(0)
1975
+ if bz: # recalculate with assumptions in case it's unevaluated
1976
+ new = b**e
1977
+ if new != expr:
1978
+ return new.is_constant()
1979
+ econ = e.is_constant(*wrt)
1980
+ bcon = b.is_constant(*wrt)
1981
+ if bcon:
1982
+ if econ:
1983
+ return True
1984
+ bz = b.equals(0)
1985
+ if bz is False:
1986
+ return False
1987
+ elif bcon is None:
1988
+ return None
1989
+
1990
+ return e.equals(0)
1991
+
1992
+ def _eval_difference_delta(self, n, step):
1993
+ b, e = self.args
1994
+ if e.has(n) and not b.has(n):
1995
+ new_e = e.subs(n, n + step)
1996
+ return (b**(new_e - e) - 1) * self
1997
+
1998
+ power = Dispatcher('power')
1999
+ power.add((object, object), Pow)
2000
+
2001
+ from .add import Add
2002
+ from .numbers import Integer
2003
+ from .mul import Mul, _keep_coeff
2004
+ from .symbol import Symbol, Dummy, symbols
venv/lib/python3.10/site-packages/sympy/core/relational.py ADDED
@@ -0,0 +1,1587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from .basic import Atom, Basic
4
+ from .sorting import ordered
5
+ from .evalf import EvalfMixin
6
+ from .function import AppliedUndef
7
+ from .singleton import S
8
+ from .sympify import _sympify, SympifyError
9
+ from .parameters import global_parameters
10
+ from .logic import fuzzy_bool, fuzzy_xor, fuzzy_and, fuzzy_not
11
+ from sympy.logic.boolalg import Boolean, BooleanAtom
12
+ from sympy.utilities.iterables import sift
13
+ from sympy.utilities.misc import filldedent
14
+
15
+ __all__ = (
16
+ 'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge',
17
+ 'Relational', 'Equality', 'Unequality', 'StrictLessThan', 'LessThan',
18
+ 'StrictGreaterThan', 'GreaterThan',
19
+ )
20
+
21
+ from .expr import Expr
22
+ from sympy.multipledispatch import dispatch
23
+ from .containers import Tuple
24
+ from .symbol import Symbol
25
+
26
+
27
+ def _nontrivBool(side):
28
+ return isinstance(side, Boolean) and \
29
+ not isinstance(side, Atom)
30
+
31
+
32
+ # Note, see issue 4986. Ideally, we wouldn't want to subclass both Boolean
33
+ # and Expr.
34
+ # from .. import Expr
35
+
36
+
37
+ def _canonical(cond):
38
+ # return a condition in which all relationals are canonical
39
+ reps = {r: r.canonical for r in cond.atoms(Relational)}
40
+ return cond.xreplace(reps)
41
+ # XXX: AttributeError was being caught here but it wasn't triggered by any of
42
+ # the tests so I've removed it...
43
+
44
+
45
+ def _canonical_coeff(rel):
46
+ # return -2*x + 1 < 0 as x > 1/2
47
+ # XXX make this part of Relational.canonical?
48
+ rel = rel.canonical
49
+ if not rel.is_Relational or rel.rhs.is_Boolean:
50
+ return rel # Eq(x, True)
51
+ b, l = rel.lhs.as_coeff_Add(rational=True)
52
+ m, lhs = l.as_coeff_Mul(rational=True)
53
+ rhs = (rel.rhs - b)/m
54
+ if m < 0:
55
+ return rel.reversed.func(lhs, rhs)
56
+ return rel.func(lhs, rhs)
57
+
58
+
59
+ class Relational(Boolean, EvalfMixin):
60
+ """Base class for all relation types.
61
+
62
+ Explanation
63
+ ===========
64
+
65
+ Subclasses of Relational should generally be instantiated directly, but
66
+ Relational can be instantiated with a valid ``rop`` value to dispatch to
67
+ the appropriate subclass.
68
+
69
+ Parameters
70
+ ==========
71
+
72
+ rop : str or None
73
+ Indicates what subclass to instantiate. Valid values can be found
74
+ in the keys of Relational.ValidRelationOperator.
75
+
76
+ Examples
77
+ ========
78
+
79
+ >>> from sympy import Rel
80
+ >>> from sympy.abc import x, y
81
+ >>> Rel(y, x + x**2, '==')
82
+ Eq(y, x**2 + x)
83
+
84
+ A relation's type can be defined upon creation using ``rop``.
85
+ The relation type of an existing expression can be obtained
86
+ using its ``rel_op`` property.
87
+ Here is a table of all the relation types, along with their
88
+ ``rop`` and ``rel_op`` values:
89
+
90
+ +---------------------+----------------------------+------------+
91
+ |Relation |``rop`` |``rel_op`` |
92
+ +=====================+============================+============+
93
+ |``Equality`` |``==`` or ``eq`` or ``None``|``==`` |
94
+ +---------------------+----------------------------+------------+
95
+ |``Unequality`` |``!=`` or ``ne`` |``!=`` |
96
+ +---------------------+----------------------------+------------+
97
+ |``GreaterThan`` |``>=`` or ``ge`` |``>=`` |
98
+ +---------------------+----------------------------+------------+
99
+ |``LessThan`` |``<=`` or ``le`` |``<=`` |
100
+ +---------------------+----------------------------+------------+
101
+ |``StrictGreaterThan``|``>`` or ``gt`` |``>`` |
102
+ +---------------------+----------------------------+------------+
103
+ |``StrictLessThan`` |``<`` or ``lt`` |``<`` |
104
+ +---------------------+----------------------------+------------+
105
+
106
+ For example, setting ``rop`` to ``==`` produces an
107
+ ``Equality`` relation, ``Eq()``.
108
+ So does setting ``rop`` to ``eq``, or leaving ``rop`` unspecified.
109
+ That is, the first three ``Rel()`` below all produce the same result.
110
+ Using a ``rop`` from a different row in the table produces a
111
+ different relation type.
112
+ For example, the fourth ``Rel()`` below using ``lt`` for ``rop``
113
+ produces a ``StrictLessThan`` inequality:
114
+
115
+ >>> from sympy import Rel
116
+ >>> from sympy.abc import x, y
117
+ >>> Rel(y, x + x**2, '==')
118
+ Eq(y, x**2 + x)
119
+ >>> Rel(y, x + x**2, 'eq')
120
+ Eq(y, x**2 + x)
121
+ >>> Rel(y, x + x**2)
122
+ Eq(y, x**2 + x)
123
+ >>> Rel(y, x + x**2, 'lt')
124
+ y < x**2 + x
125
+
126
+ To obtain the relation type of an existing expression,
127
+ get its ``rel_op`` property.
128
+ For example, ``rel_op`` is ``==`` for the ``Equality`` relation above,
129
+ and ``<`` for the strict less than inequality above:
130
+
131
+ >>> from sympy import Rel
132
+ >>> from sympy.abc import x, y
133
+ >>> my_equality = Rel(y, x + x**2, '==')
134
+ >>> my_equality.rel_op
135
+ '=='
136
+ >>> my_inequality = Rel(y, x + x**2, 'lt')
137
+ >>> my_inequality.rel_op
138
+ '<'
139
+
140
+ """
141
+ __slots__ = ()
142
+
143
+ ValidRelationOperator: dict[str | None, type[Relational]] = {}
144
+
145
+ is_Relational = True
146
+
147
+ # ValidRelationOperator - Defined below, because the necessary classes
148
+ # have not yet been defined
149
+
150
+ def __new__(cls, lhs, rhs, rop=None, **assumptions):
151
+ # If called by a subclass, do nothing special and pass on to Basic.
152
+ if cls is not Relational:
153
+ return Basic.__new__(cls, lhs, rhs, **assumptions)
154
+
155
+ # XXX: Why do this? There should be a separate function to make a
156
+ # particular subclass of Relational from a string.
157
+ #
158
+ # If called directly with an operator, look up the subclass
159
+ # corresponding to that operator and delegate to it
160
+ cls = cls.ValidRelationOperator.get(rop, None)
161
+ if cls is None:
162
+ raise ValueError("Invalid relational operator symbol: %r" % rop)
163
+
164
+ if not issubclass(cls, (Eq, Ne)):
165
+ # validate that Booleans are not being used in a relational
166
+ # other than Eq/Ne;
167
+ # Note: Symbol is a subclass of Boolean but is considered
168
+ # acceptable here.
169
+ if any(map(_nontrivBool, (lhs, rhs))):
170
+ raise TypeError(filldedent('''
171
+ A Boolean argument can only be used in
172
+ Eq and Ne; all other relationals expect
173
+ real expressions.
174
+ '''))
175
+
176
+ return cls(lhs, rhs, **assumptions)
177
+
178
+ @property
179
+ def lhs(self):
180
+ """The left-hand side of the relation."""
181
+ return self._args[0]
182
+
183
+ @property
184
+ def rhs(self):
185
+ """The right-hand side of the relation."""
186
+ return self._args[1]
187
+
188
+ @property
189
+ def reversed(self):
190
+ """Return the relationship with sides reversed.
191
+
192
+ Examples
193
+ ========
194
+
195
+ >>> from sympy import Eq
196
+ >>> from sympy.abc import x
197
+ >>> Eq(x, 1)
198
+ Eq(x, 1)
199
+ >>> _.reversed
200
+ Eq(1, x)
201
+ >>> x < 1
202
+ x < 1
203
+ >>> _.reversed
204
+ 1 > x
205
+ """
206
+ ops = {Eq: Eq, Gt: Lt, Ge: Le, Lt: Gt, Le: Ge, Ne: Ne}
207
+ a, b = self.args
208
+ return Relational.__new__(ops.get(self.func, self.func), b, a)
209
+
210
+ @property
211
+ def reversedsign(self):
212
+ """Return the relationship with signs reversed.
213
+
214
+ Examples
215
+ ========
216
+
217
+ >>> from sympy import Eq
218
+ >>> from sympy.abc import x
219
+ >>> Eq(x, 1)
220
+ Eq(x, 1)
221
+ >>> _.reversedsign
222
+ Eq(-x, -1)
223
+ >>> x < 1
224
+ x < 1
225
+ >>> _.reversedsign
226
+ -x > -1
227
+ """
228
+ a, b = self.args
229
+ if not (isinstance(a, BooleanAtom) or isinstance(b, BooleanAtom)):
230
+ ops = {Eq: Eq, Gt: Lt, Ge: Le, Lt: Gt, Le: Ge, Ne: Ne}
231
+ return Relational.__new__(ops.get(self.func, self.func), -a, -b)
232
+ else:
233
+ return self
234
+
235
+ @property
236
+ def negated(self):
237
+ """Return the negated relationship.
238
+
239
+ Examples
240
+ ========
241
+
242
+ >>> from sympy import Eq
243
+ >>> from sympy.abc import x
244
+ >>> Eq(x, 1)
245
+ Eq(x, 1)
246
+ >>> _.negated
247
+ Ne(x, 1)
248
+ >>> x < 1
249
+ x < 1
250
+ >>> _.negated
251
+ x >= 1
252
+
253
+ Notes
254
+ =====
255
+
256
+ This works more or less identical to ``~``/``Not``. The difference is
257
+ that ``negated`` returns the relationship even if ``evaluate=False``.
258
+ Hence, this is useful in code when checking for e.g. negated relations
259
+ to existing ones as it will not be affected by the `evaluate` flag.
260
+
261
+ """
262
+ ops = {Eq: Ne, Ge: Lt, Gt: Le, Le: Gt, Lt: Ge, Ne: Eq}
263
+ # If there ever will be new Relational subclasses, the following line
264
+ # will work until it is properly sorted out
265
+ # return ops.get(self.func, lambda a, b, evaluate=False: ~(self.func(a,
266
+ # b, evaluate=evaluate)))(*self.args, evaluate=False)
267
+ return Relational.__new__(ops.get(self.func), *self.args)
268
+
269
+ @property
270
+ def weak(self):
271
+ """return the non-strict version of the inequality or self
272
+
273
+ EXAMPLES
274
+ ========
275
+
276
+ >>> from sympy.abc import x
277
+ >>> (x < 1).weak
278
+ x <= 1
279
+ >>> _.weak
280
+ x <= 1
281
+ """
282
+ return self
283
+
284
+ @property
285
+ def strict(self):
286
+ """return the strict version of the inequality or self
287
+
288
+ EXAMPLES
289
+ ========
290
+
291
+ >>> from sympy.abc import x
292
+ >>> (x <= 1).strict
293
+ x < 1
294
+ >>> _.strict
295
+ x < 1
296
+ """
297
+ return self
298
+
299
+ def _eval_evalf(self, prec):
300
+ return self.func(*[s._evalf(prec) for s in self.args])
301
+
302
+ @property
303
+ def canonical(self):
304
+ """Return a canonical form of the relational by putting a
305
+ number on the rhs, canonically removing a sign or else
306
+ ordering the args canonically. No other simplification is
307
+ attempted.
308
+
309
+ Examples
310
+ ========
311
+
312
+ >>> from sympy.abc import x, y
313
+ >>> x < 2
314
+ x < 2
315
+ >>> _.reversed.canonical
316
+ x < 2
317
+ >>> (-y < x).canonical
318
+ x > -y
319
+ >>> (-y > x).canonical
320
+ x < -y
321
+ >>> (-y < -x).canonical
322
+ x < y
323
+
324
+ The canonicalization is recursively applied:
325
+
326
+ >>> from sympy import Eq
327
+ >>> Eq(x < y, y > x).canonical
328
+ True
329
+ """
330
+ args = tuple([i.canonical if isinstance(i, Relational) else i for i in self.args])
331
+ if args != self.args:
332
+ r = self.func(*args)
333
+ if not isinstance(r, Relational):
334
+ return r
335
+ else:
336
+ r = self
337
+ if r.rhs.is_number:
338
+ if r.rhs.is_Number and r.lhs.is_Number and r.lhs > r.rhs:
339
+ r = r.reversed
340
+ elif r.lhs.is_number:
341
+ r = r.reversed
342
+ elif tuple(ordered(args)) != args:
343
+ r = r.reversed
344
+
345
+ LHS_CEMS = getattr(r.lhs, 'could_extract_minus_sign', None)
346
+ RHS_CEMS = getattr(r.rhs, 'could_extract_minus_sign', None)
347
+
348
+ if isinstance(r.lhs, BooleanAtom) or isinstance(r.rhs, BooleanAtom):
349
+ return r
350
+
351
+ # Check if first value has negative sign
352
+ if LHS_CEMS and LHS_CEMS():
353
+ return r.reversedsign
354
+ elif not r.rhs.is_number and RHS_CEMS and RHS_CEMS():
355
+ # Right hand side has a minus, but not lhs.
356
+ # How does the expression with reversed signs behave?
357
+ # This is so that expressions of the type
358
+ # Eq(x, -y) and Eq(-x, y)
359
+ # have the same canonical representation
360
+ expr1, _ = ordered([r.lhs, -r.rhs])
361
+ if expr1 != r.lhs:
362
+ return r.reversed.reversedsign
363
+
364
+ return r
365
+
366
+ def equals(self, other, failing_expression=False):
367
+ """Return True if the sides of the relationship are mathematically
368
+ identical and the type of relationship is the same.
369
+ If failing_expression is True, return the expression whose truth value
370
+ was unknown."""
371
+ if isinstance(other, Relational):
372
+ if other in (self, self.reversed):
373
+ return True
374
+ a, b = self, other
375
+ if a.func in (Eq, Ne) or b.func in (Eq, Ne):
376
+ if a.func != b.func:
377
+ return False
378
+ left, right = [i.equals(j,
379
+ failing_expression=failing_expression)
380
+ for i, j in zip(a.args, b.args)]
381
+ if left is True:
382
+ return right
383
+ if right is True:
384
+ return left
385
+ lr, rl = [i.equals(j, failing_expression=failing_expression)
386
+ for i, j in zip(a.args, b.reversed.args)]
387
+ if lr is True:
388
+ return rl
389
+ if rl is True:
390
+ return lr
391
+ e = (left, right, lr, rl)
392
+ if all(i is False for i in e):
393
+ return False
394
+ for i in e:
395
+ if i not in (True, False):
396
+ return i
397
+ else:
398
+ if b.func != a.func:
399
+ b = b.reversed
400
+ if a.func != b.func:
401
+ return False
402
+ left = a.lhs.equals(b.lhs,
403
+ failing_expression=failing_expression)
404
+ if left is False:
405
+ return False
406
+ right = a.rhs.equals(b.rhs,
407
+ failing_expression=failing_expression)
408
+ if right is False:
409
+ return False
410
+ if left is True:
411
+ return right
412
+ return left
413
+
414
+ def _eval_simplify(self, **kwargs):
415
+ from .add import Add
416
+ from .expr import Expr
417
+ r = self
418
+ r = r.func(*[i.simplify(**kwargs) for i in r.args])
419
+ if r.is_Relational:
420
+ if not isinstance(r.lhs, Expr) or not isinstance(r.rhs, Expr):
421
+ return r
422
+ dif = r.lhs - r.rhs
423
+ # replace dif with a valid Number that will
424
+ # allow a definitive comparison with 0
425
+ v = None
426
+ if dif.is_comparable:
427
+ v = dif.n(2)
428
+ elif dif.equals(0): # XXX this is expensive
429
+ v = S.Zero
430
+ if v is not None:
431
+ r = r.func._eval_relation(v, S.Zero)
432
+ r = r.canonical
433
+ # If there is only one symbol in the expression,
434
+ # try to write it on a simplified form
435
+ free = list(filter(lambda x: x.is_real is not False, r.free_symbols))
436
+ if len(free) == 1:
437
+ try:
438
+ from sympy.solvers.solveset import linear_coeffs
439
+ x = free.pop()
440
+ dif = r.lhs - r.rhs
441
+ m, b = linear_coeffs(dif, x)
442
+ if m.is_zero is False:
443
+ if m.is_negative:
444
+ # Dividing with a negative number, so change order of arguments
445
+ # canonical will put the symbol back on the lhs later
446
+ r = r.func(-b / m, x)
447
+ else:
448
+ r = r.func(x, -b / m)
449
+ else:
450
+ r = r.func(b, S.Zero)
451
+ except ValueError:
452
+ # maybe not a linear function, try polynomial
453
+ from sympy.polys.polyerrors import PolynomialError
454
+ from sympy.polys.polytools import gcd, Poly, poly
455
+ try:
456
+ p = poly(dif, x)
457
+ c = p.all_coeffs()
458
+ constant = c[-1]
459
+ c[-1] = 0
460
+ scale = gcd(c)
461
+ c = [ctmp / scale for ctmp in c]
462
+ r = r.func(Poly.from_list(c, x).as_expr(), -constant / scale)
463
+ except PolynomialError:
464
+ pass
465
+ elif len(free) >= 2:
466
+ try:
467
+ from sympy.solvers.solveset import linear_coeffs
468
+ from sympy.polys.polytools import gcd
469
+ free = list(ordered(free))
470
+ dif = r.lhs - r.rhs
471
+ m = linear_coeffs(dif, *free)
472
+ constant = m[-1]
473
+ del m[-1]
474
+ scale = gcd(m)
475
+ m = [mtmp / scale for mtmp in m]
476
+ nzm = list(filter(lambda f: f[0] != 0, list(zip(m, free))))
477
+ if scale.is_zero is False:
478
+ if constant != 0:
479
+ # lhs: expression, rhs: constant
480
+ newexpr = Add(*[i * j for i, j in nzm])
481
+ r = r.func(newexpr, -constant / scale)
482
+ else:
483
+ # keep first term on lhs
484
+ lhsterm = nzm[0][0] * nzm[0][1]
485
+ del nzm[0]
486
+ newexpr = Add(*[i * j for i, j in nzm])
487
+ r = r.func(lhsterm, -newexpr)
488
+
489
+ else:
490
+ r = r.func(constant, S.Zero)
491
+ except ValueError:
492
+ pass
493
+ # Did we get a simplified result?
494
+ r = r.canonical
495
+ measure = kwargs['measure']
496
+ if measure(r) < kwargs['ratio'] * measure(self):
497
+ return r
498
+ else:
499
+ return self
500
+
501
+ def _eval_trigsimp(self, **opts):
502
+ from sympy.simplify.trigsimp import trigsimp
503
+ return self.func(trigsimp(self.lhs, **opts), trigsimp(self.rhs, **opts))
504
+
505
+ def expand(self, **kwargs):
506
+ args = (arg.expand(**kwargs) for arg in self.args)
507
+ return self.func(*args)
508
+
509
+ def __bool__(self):
510
+ raise TypeError("cannot determine truth value of Relational")
511
+
512
+ def _eval_as_set(self):
513
+ # self is univariate and periodicity(self, x) in (0, None)
514
+ from sympy.solvers.inequalities import solve_univariate_inequality
515
+ from sympy.sets.conditionset import ConditionSet
516
+ syms = self.free_symbols
517
+ assert len(syms) == 1
518
+ x = syms.pop()
519
+ try:
520
+ xset = solve_univariate_inequality(self, x, relational=False)
521
+ except NotImplementedError:
522
+ # solve_univariate_inequality raises NotImplementedError for
523
+ # unsolvable equations/inequalities.
524
+ xset = ConditionSet(x, self, S.Reals)
525
+ return xset
526
+
527
+ @property
528
+ def binary_symbols(self):
529
+ # override where necessary
530
+ return set()
531
+
532
+
533
+ Rel = Relational
534
+
535
+
536
+ class Equality(Relational):
537
+ """
538
+ An equal relation between two objects.
539
+
540
+ Explanation
541
+ ===========
542
+
543
+ Represents that two objects are equal. If they can be easily shown
544
+ to be definitively equal (or unequal), this will reduce to True (or
545
+ False). Otherwise, the relation is maintained as an unevaluated
546
+ Equality object. Use the ``simplify`` function on this object for
547
+ more nontrivial evaluation of the equality relation.
548
+
549
+ As usual, the keyword argument ``evaluate=False`` can be used to
550
+ prevent any evaluation.
551
+
552
+ Examples
553
+ ========
554
+
555
+ >>> from sympy import Eq, simplify, exp, cos
556
+ >>> from sympy.abc import x, y
557
+ >>> Eq(y, x + x**2)
558
+ Eq(y, x**2 + x)
559
+ >>> Eq(2, 5)
560
+ False
561
+ >>> Eq(2, 5, evaluate=False)
562
+ Eq(2, 5)
563
+ >>> _.doit()
564
+ False
565
+ >>> Eq(exp(x), exp(x).rewrite(cos))
566
+ Eq(exp(x), sinh(x) + cosh(x))
567
+ >>> simplify(_)
568
+ True
569
+
570
+ See Also
571
+ ========
572
+
573
+ sympy.logic.boolalg.Equivalent : for representing equality between two
574
+ boolean expressions
575
+
576
+ Notes
577
+ =====
578
+
579
+ Python treats 1 and True (and 0 and False) as being equal; SymPy
580
+ does not. And integer will always compare as unequal to a Boolean:
581
+
582
+ >>> Eq(True, 1), True == 1
583
+ (False, True)
584
+
585
+ This class is not the same as the == operator. The == operator tests
586
+ for exact structural equality between two expressions; this class
587
+ compares expressions mathematically.
588
+
589
+ If either object defines an ``_eval_Eq`` method, it can be used in place of
590
+ the default algorithm. If ``lhs._eval_Eq(rhs)`` or ``rhs._eval_Eq(lhs)``
591
+ returns anything other than None, that return value will be substituted for
592
+ the Equality. If None is returned by ``_eval_Eq``, an Equality object will
593
+ be created as usual.
594
+
595
+ Since this object is already an expression, it does not respond to
596
+ the method ``as_expr`` if one tries to create `x - y` from ``Eq(x, y)``.
597
+ This can be done with the ``rewrite(Add)`` method.
598
+
599
+ .. deprecated:: 1.5
600
+
601
+ ``Eq(expr)`` with a single argument is a shorthand for ``Eq(expr, 0)``,
602
+ but this behavior is deprecated and will be removed in a future version
603
+ of SymPy.
604
+
605
+ """
606
+ rel_op = '=='
607
+
608
+ __slots__ = ()
609
+
610
+ is_Equality = True
611
+
612
+ def __new__(cls, lhs, rhs, **options):
613
+ evaluate = options.pop('evaluate', global_parameters.evaluate)
614
+ lhs = _sympify(lhs)
615
+ rhs = _sympify(rhs)
616
+ if evaluate:
617
+ val = is_eq(lhs, rhs)
618
+ if val is None:
619
+ return cls(lhs, rhs, evaluate=False)
620
+ else:
621
+ return _sympify(val)
622
+
623
+ return Relational.__new__(cls, lhs, rhs)
624
+
625
+ @classmethod
626
+ def _eval_relation(cls, lhs, rhs):
627
+ return _sympify(lhs == rhs)
628
+
629
+ def _eval_rewrite_as_Add(self, *args, **kwargs):
630
+ """
631
+ return Eq(L, R) as L - R. To control the evaluation of
632
+ the result set pass `evaluate=True` to give L - R;
633
+ if `evaluate=None` then terms in L and R will not cancel
634
+ but they will be listed in canonical order; otherwise
635
+ non-canonical args will be returned. If one side is 0, the
636
+ non-zero side will be returned.
637
+
638
+ Examples
639
+ ========
640
+
641
+ >>> from sympy import Eq, Add
642
+ >>> from sympy.abc import b, x
643
+ >>> eq = Eq(x + b, x - b)
644
+ >>> eq.rewrite(Add)
645
+ 2*b
646
+ >>> eq.rewrite(Add, evaluate=None).args
647
+ (b, b, x, -x)
648
+ >>> eq.rewrite(Add, evaluate=False).args
649
+ (b, x, b, -x)
650
+ """
651
+ from .add import _unevaluated_Add, Add
652
+ L, R = args
653
+ if L == 0:
654
+ return R
655
+ if R == 0:
656
+ return L
657
+ evaluate = kwargs.get('evaluate', True)
658
+ if evaluate:
659
+ # allow cancellation of args
660
+ return L - R
661
+ args = Add.make_args(L) + Add.make_args(-R)
662
+ if evaluate is None:
663
+ # no cancellation, but canonical
664
+ return _unevaluated_Add(*args)
665
+ # no cancellation, not canonical
666
+ return Add._from_args(args)
667
+
668
+ @property
669
+ def binary_symbols(self):
670
+ if S.true in self.args or S.false in self.args:
671
+ if self.lhs.is_Symbol:
672
+ return {self.lhs}
673
+ elif self.rhs.is_Symbol:
674
+ return {self.rhs}
675
+ return set()
676
+
677
+ def _eval_simplify(self, **kwargs):
678
+ # standard simplify
679
+ e = super()._eval_simplify(**kwargs)
680
+ if not isinstance(e, Equality):
681
+ return e
682
+ from .expr import Expr
683
+ if not isinstance(e.lhs, Expr) or not isinstance(e.rhs, Expr):
684
+ return e
685
+ free = self.free_symbols
686
+ if len(free) == 1:
687
+ try:
688
+ from .add import Add
689
+ from sympy.solvers.solveset import linear_coeffs
690
+ x = free.pop()
691
+ m, b = linear_coeffs(
692
+ e.rewrite(Add, evaluate=False), x)
693
+ if m.is_zero is False:
694
+ enew = e.func(x, -b / m)
695
+ else:
696
+ enew = e.func(m * x, -b)
697
+ measure = kwargs['measure']
698
+ if measure(enew) <= kwargs['ratio'] * measure(e):
699
+ e = enew
700
+ except ValueError:
701
+ pass
702
+ return e.canonical
703
+
704
+ def integrate(self, *args, **kwargs):
705
+ """See the integrate function in sympy.integrals"""
706
+ from sympy.integrals.integrals import integrate
707
+ return integrate(self, *args, **kwargs)
708
+
709
+ def as_poly(self, *gens, **kwargs):
710
+ '''Returns lhs-rhs as a Poly
711
+
712
+ Examples
713
+ ========
714
+
715
+ >>> from sympy import Eq
716
+ >>> from sympy.abc import x
717
+ >>> Eq(x**2, 1).as_poly(x)
718
+ Poly(x**2 - 1, x, domain='ZZ')
719
+ '''
720
+ return (self.lhs - self.rhs).as_poly(*gens, **kwargs)
721
+
722
+
723
+ Eq = Equality
724
+
725
+
726
+ class Unequality(Relational):
727
+ """An unequal relation between two objects.
728
+
729
+ Explanation
730
+ ===========
731
+
732
+ Represents that two objects are not equal. If they can be shown to be
733
+ definitively equal, this will reduce to False; if definitively unequal,
734
+ this will reduce to True. Otherwise, the relation is maintained as an
735
+ Unequality object.
736
+
737
+ Examples
738
+ ========
739
+
740
+ >>> from sympy import Ne
741
+ >>> from sympy.abc import x, y
742
+ >>> Ne(y, x+x**2)
743
+ Ne(y, x**2 + x)
744
+
745
+ See Also
746
+ ========
747
+ Equality
748
+
749
+ Notes
750
+ =====
751
+ This class is not the same as the != operator. The != operator tests
752
+ for exact structural equality between two expressions; this class
753
+ compares expressions mathematically.
754
+
755
+ This class is effectively the inverse of Equality. As such, it uses the
756
+ same algorithms, including any available `_eval_Eq` methods.
757
+
758
+ """
759
+ rel_op = '!='
760
+
761
+ __slots__ = ()
762
+
763
+ def __new__(cls, lhs, rhs, **options):
764
+ lhs = _sympify(lhs)
765
+ rhs = _sympify(rhs)
766
+ evaluate = options.pop('evaluate', global_parameters.evaluate)
767
+ if evaluate:
768
+ val = is_neq(lhs, rhs)
769
+ if val is None:
770
+ return cls(lhs, rhs, evaluate=False)
771
+ else:
772
+ return _sympify(val)
773
+
774
+ return Relational.__new__(cls, lhs, rhs, **options)
775
+
776
+ @classmethod
777
+ def _eval_relation(cls, lhs, rhs):
778
+ return _sympify(lhs != rhs)
779
+
780
+ @property
781
+ def binary_symbols(self):
782
+ if S.true in self.args or S.false in self.args:
783
+ if self.lhs.is_Symbol:
784
+ return {self.lhs}
785
+ elif self.rhs.is_Symbol:
786
+ return {self.rhs}
787
+ return set()
788
+
789
+ def _eval_simplify(self, **kwargs):
790
+ # simplify as an equality
791
+ eq = Equality(*self.args)._eval_simplify(**kwargs)
792
+ if isinstance(eq, Equality):
793
+ # send back Ne with the new args
794
+ return self.func(*eq.args)
795
+ return eq.negated # result of Ne is the negated Eq
796
+
797
+
798
+ Ne = Unequality
799
+
800
+
801
+ class _Inequality(Relational):
802
+ """Internal base class for all *Than types.
803
+
804
+ Each subclass must implement _eval_relation to provide the method for
805
+ comparing two real numbers.
806
+
807
+ """
808
+ __slots__ = ()
809
+
810
+ def __new__(cls, lhs, rhs, **options):
811
+
812
+ try:
813
+ lhs = _sympify(lhs)
814
+ rhs = _sympify(rhs)
815
+ except SympifyError:
816
+ return NotImplemented
817
+
818
+ evaluate = options.pop('evaluate', global_parameters.evaluate)
819
+ if evaluate:
820
+ for me in (lhs, rhs):
821
+ if me.is_extended_real is False:
822
+ raise TypeError("Invalid comparison of non-real %s" % me)
823
+ if me is S.NaN:
824
+ raise TypeError("Invalid NaN comparison")
825
+ # First we invoke the appropriate inequality method of `lhs`
826
+ # (e.g., `lhs.__lt__`). That method will try to reduce to
827
+ # boolean or raise an exception. It may keep calling
828
+ # superclasses until it reaches `Expr` (e.g., `Expr.__lt__`).
829
+ # In some cases, `Expr` will just invoke us again (if neither it
830
+ # nor a subclass was able to reduce to boolean or raise an
831
+ # exception). In that case, it must call us with
832
+ # `evaluate=False` to prevent infinite recursion.
833
+ return cls._eval_relation(lhs, rhs, **options)
834
+
835
+ # make a "non-evaluated" Expr for the inequality
836
+ return Relational.__new__(cls, lhs, rhs, **options)
837
+
838
+ @classmethod
839
+ def _eval_relation(cls, lhs, rhs, **options):
840
+ val = cls._eval_fuzzy_relation(lhs, rhs)
841
+ if val is None:
842
+ return cls(lhs, rhs, evaluate=False)
843
+ else:
844
+ return _sympify(val)
845
+
846
+
847
+ class _Greater(_Inequality):
848
+ """Not intended for general use
849
+
850
+ _Greater is only used so that GreaterThan and StrictGreaterThan may
851
+ subclass it for the .gts and .lts properties.
852
+
853
+ """
854
+ __slots__ = ()
855
+
856
+ @property
857
+ def gts(self):
858
+ return self._args[0]
859
+
860
+ @property
861
+ def lts(self):
862
+ return self._args[1]
863
+
864
+
865
+ class _Less(_Inequality):
866
+ """Not intended for general use.
867
+
868
+ _Less is only used so that LessThan and StrictLessThan may subclass it for
869
+ the .gts and .lts properties.
870
+
871
+ """
872
+ __slots__ = ()
873
+
874
+ @property
875
+ def gts(self):
876
+ return self._args[1]
877
+
878
+ @property
879
+ def lts(self):
880
+ return self._args[0]
881
+
882
+
883
+ class GreaterThan(_Greater):
884
+ r"""Class representations of inequalities.
885
+
886
+ Explanation
887
+ ===========
888
+
889
+ The ``*Than`` classes represent inequal relationships, where the left-hand
890
+ side is generally bigger or smaller than the right-hand side. For example,
891
+ the GreaterThan class represents an inequal relationship where the
892
+ left-hand side is at least as big as the right side, if not bigger. In
893
+ mathematical notation:
894
+
895
+ lhs $\ge$ rhs
896
+
897
+ In total, there are four ``*Than`` classes, to represent the four
898
+ inequalities:
899
+
900
+ +-----------------+--------+
901
+ |Class Name | Symbol |
902
+ +=================+========+
903
+ |GreaterThan | ``>=`` |
904
+ +-----------------+--------+
905
+ |LessThan | ``<=`` |
906
+ +-----------------+--------+
907
+ |StrictGreaterThan| ``>`` |
908
+ +-----------------+--------+
909
+ |StrictLessThan | ``<`` |
910
+ +-----------------+--------+
911
+
912
+ All classes take two arguments, lhs and rhs.
913
+
914
+ +----------------------------+-----------------+
915
+ |Signature Example | Math Equivalent |
916
+ +============================+=================+
917
+ |GreaterThan(lhs, rhs) | lhs $\ge$ rhs |
918
+ +----------------------------+-----------------+
919
+ |LessThan(lhs, rhs) | lhs $\le$ rhs |
920
+ +----------------------------+-----------------+
921
+ |StrictGreaterThan(lhs, rhs) | lhs $>$ rhs |
922
+ +----------------------------+-----------------+
923
+ |StrictLessThan(lhs, rhs) | lhs $<$ rhs |
924
+ +----------------------------+-----------------+
925
+
926
+ In addition to the normal .lhs and .rhs of Relations, ``*Than`` inequality
927
+ objects also have the .lts and .gts properties, which represent the "less
928
+ than side" and "greater than side" of the operator. Use of .lts and .gts
929
+ in an algorithm rather than .lhs and .rhs as an assumption of inequality
930
+ direction will make more explicit the intent of a certain section of code,
931
+ and will make it similarly more robust to client code changes:
932
+
933
+ >>> from sympy import GreaterThan, StrictGreaterThan
934
+ >>> from sympy import LessThan, StrictLessThan
935
+ >>> from sympy import And, Ge, Gt, Le, Lt, Rel, S
936
+ >>> from sympy.abc import x, y, z
937
+ >>> from sympy.core.relational import Relational
938
+
939
+ >>> e = GreaterThan(x, 1)
940
+ >>> e
941
+ x >= 1
942
+ >>> '%s >= %s is the same as %s <= %s' % (e.gts, e.lts, e.lts, e.gts)
943
+ 'x >= 1 is the same as 1 <= x'
944
+
945
+ Examples
946
+ ========
947
+
948
+ One generally does not instantiate these classes directly, but uses various
949
+ convenience methods:
950
+
951
+ >>> for f in [Ge, Gt, Le, Lt]: # convenience wrappers
952
+ ... print(f(x, 2))
953
+ x >= 2
954
+ x > 2
955
+ x <= 2
956
+ x < 2
957
+
958
+ Another option is to use the Python inequality operators (``>=``, ``>``,
959
+ ``<=``, ``<``) directly. Their main advantage over the ``Ge``, ``Gt``,
960
+ ``Le``, and ``Lt`` counterparts, is that one can write a more
961
+ "mathematical looking" statement rather than littering the math with
962
+ oddball function calls. However there are certain (minor) caveats of
963
+ which to be aware (search for 'gotcha', below).
964
+
965
+ >>> x >= 2
966
+ x >= 2
967
+ >>> _ == Ge(x, 2)
968
+ True
969
+
970
+ However, it is also perfectly valid to instantiate a ``*Than`` class less
971
+ succinctly and less conveniently:
972
+
973
+ >>> Rel(x, 1, ">")
974
+ x > 1
975
+ >>> Relational(x, 1, ">")
976
+ x > 1
977
+
978
+ >>> StrictGreaterThan(x, 1)
979
+ x > 1
980
+ >>> GreaterThan(x, 1)
981
+ x >= 1
982
+ >>> LessThan(x, 1)
983
+ x <= 1
984
+ >>> StrictLessThan(x, 1)
985
+ x < 1
986
+
987
+ Notes
988
+ =====
989
+
990
+ There are a couple of "gotchas" to be aware of when using Python's
991
+ operators.
992
+
993
+ The first is that what your write is not always what you get:
994
+
995
+ >>> 1 < x
996
+ x > 1
997
+
998
+ Due to the order that Python parses a statement, it may
999
+ not immediately find two objects comparable. When ``1 < x``
1000
+ is evaluated, Python recognizes that the number 1 is a native
1001
+ number and that x is *not*. Because a native Python number does
1002
+ not know how to compare itself with a SymPy object
1003
+ Python will try the reflective operation, ``x > 1`` and that is the
1004
+ form that gets evaluated, hence returned.
1005
+
1006
+ If the order of the statement is important (for visual output to
1007
+ the console, perhaps), one can work around this annoyance in a
1008
+ couple ways:
1009
+
1010
+ (1) "sympify" the literal before comparison
1011
+
1012
+ >>> S(1) < x
1013
+ 1 < x
1014
+
1015
+ (2) use one of the wrappers or less succinct methods described
1016
+ above
1017
+
1018
+ >>> Lt(1, x)
1019
+ 1 < x
1020
+ >>> Relational(1, x, "<")
1021
+ 1 < x
1022
+
1023
+ The second gotcha involves writing equality tests between relationals
1024
+ when one or both sides of the test involve a literal relational:
1025
+
1026
+ >>> e = x < 1; e
1027
+ x < 1
1028
+ >>> e == e # neither side is a literal
1029
+ True
1030
+ >>> e == x < 1 # expecting True, too
1031
+ False
1032
+ >>> e != x < 1 # expecting False
1033
+ x < 1
1034
+ >>> x < 1 != x < 1 # expecting False or the same thing as before
1035
+ Traceback (most recent call last):
1036
+ ...
1037
+ TypeError: cannot determine truth value of Relational
1038
+
1039
+ The solution for this case is to wrap literal relationals in
1040
+ parentheses:
1041
+
1042
+ >>> e == (x < 1)
1043
+ True
1044
+ >>> e != (x < 1)
1045
+ False
1046
+ >>> (x < 1) != (x < 1)
1047
+ False
1048
+
1049
+ The third gotcha involves chained inequalities not involving
1050
+ ``==`` or ``!=``. Occasionally, one may be tempted to write:
1051
+
1052
+ >>> e = x < y < z
1053
+ Traceback (most recent call last):
1054
+ ...
1055
+ TypeError: symbolic boolean expression has no truth value.
1056
+
1057
+ Due to an implementation detail or decision of Python [1]_,
1058
+ there is no way for SymPy to create a chained inequality with
1059
+ that syntax so one must use And:
1060
+
1061
+ >>> e = And(x < y, y < z)
1062
+ >>> type( e )
1063
+ And
1064
+ >>> e
1065
+ (x < y) & (y < z)
1066
+
1067
+ Although this can also be done with the '&' operator, it cannot
1068
+ be done with the 'and' operarator:
1069
+
1070
+ >>> (x < y) & (y < z)
1071
+ (x < y) & (y < z)
1072
+ >>> (x < y) and (y < z)
1073
+ Traceback (most recent call last):
1074
+ ...
1075
+ TypeError: cannot determine truth value of Relational
1076
+
1077
+ .. [1] This implementation detail is that Python provides no reliable
1078
+ method to determine that a chained inequality is being built.
1079
+ Chained comparison operators are evaluated pairwise, using "and"
1080
+ logic (see
1081
+ https://docs.python.org/3/reference/expressions.html#not-in). This
1082
+ is done in an efficient way, so that each object being compared
1083
+ is only evaluated once and the comparison can short-circuit. For
1084
+ example, ``1 > 2 > 3`` is evaluated by Python as ``(1 > 2) and (2
1085
+ > 3)``. The ``and`` operator coerces each side into a bool,
1086
+ returning the object itself when it short-circuits. The bool of
1087
+ the --Than operators will raise TypeError on purpose, because
1088
+ SymPy cannot determine the mathematical ordering of symbolic
1089
+ expressions. Thus, if we were to compute ``x > y > z``, with
1090
+ ``x``, ``y``, and ``z`` being Symbols, Python converts the
1091
+ statement (roughly) into these steps:
1092
+
1093
+ (1) x > y > z
1094
+ (2) (x > y) and (y > z)
1095
+ (3) (GreaterThanObject) and (y > z)
1096
+ (4) (GreaterThanObject.__bool__()) and (y > z)
1097
+ (5) TypeError
1098
+
1099
+ Because of the ``and`` added at step 2, the statement gets turned into a
1100
+ weak ternary statement, and the first object's ``__bool__`` method will
1101
+ raise TypeError. Thus, creating a chained inequality is not possible.
1102
+
1103
+ In Python, there is no way to override the ``and`` operator, or to
1104
+ control how it short circuits, so it is impossible to make something
1105
+ like ``x > y > z`` work. There was a PEP to change this,
1106
+ :pep:`335`, but it was officially closed in March, 2012.
1107
+
1108
+ """
1109
+ __slots__ = ()
1110
+
1111
+ rel_op = '>='
1112
+
1113
+ @classmethod
1114
+ def _eval_fuzzy_relation(cls, lhs, rhs):
1115
+ return is_ge(lhs, rhs)
1116
+
1117
+ @property
1118
+ def strict(self):
1119
+ return Gt(*self.args)
1120
+
1121
+ Ge = GreaterThan
1122
+
1123
+
1124
+ class LessThan(_Less):
1125
+ __doc__ = GreaterThan.__doc__
1126
+ __slots__ = ()
1127
+
1128
+ rel_op = '<='
1129
+
1130
+ @classmethod
1131
+ def _eval_fuzzy_relation(cls, lhs, rhs):
1132
+ return is_le(lhs, rhs)
1133
+
1134
+ @property
1135
+ def strict(self):
1136
+ return Lt(*self.args)
1137
+
1138
+ Le = LessThan
1139
+
1140
+
1141
+ class StrictGreaterThan(_Greater):
1142
+ __doc__ = GreaterThan.__doc__
1143
+ __slots__ = ()
1144
+
1145
+ rel_op = '>'
1146
+
1147
+ @classmethod
1148
+ def _eval_fuzzy_relation(cls, lhs, rhs):
1149
+ return is_gt(lhs, rhs)
1150
+
1151
+ @property
1152
+ def weak(self):
1153
+ return Ge(*self.args)
1154
+
1155
+
1156
+ Gt = StrictGreaterThan
1157
+
1158
+
1159
+ class StrictLessThan(_Less):
1160
+ __doc__ = GreaterThan.__doc__
1161
+ __slots__ = ()
1162
+
1163
+ rel_op = '<'
1164
+
1165
+ @classmethod
1166
+ def _eval_fuzzy_relation(cls, lhs, rhs):
1167
+ return is_lt(lhs, rhs)
1168
+
1169
+ @property
1170
+ def weak(self):
1171
+ return Le(*self.args)
1172
+
1173
+ Lt = StrictLessThan
1174
+
1175
+ # A class-specific (not object-specific) data item used for a minor speedup.
1176
+ # It is defined here, rather than directly in the class, because the classes
1177
+ # that it references have not been defined until now (e.g. StrictLessThan).
1178
+ Relational.ValidRelationOperator = {
1179
+ None: Equality,
1180
+ '==': Equality,
1181
+ 'eq': Equality,
1182
+ '!=': Unequality,
1183
+ '<>': Unequality,
1184
+ 'ne': Unequality,
1185
+ '>=': GreaterThan,
1186
+ 'ge': GreaterThan,
1187
+ '<=': LessThan,
1188
+ 'le': LessThan,
1189
+ '>': StrictGreaterThan,
1190
+ 'gt': StrictGreaterThan,
1191
+ '<': StrictLessThan,
1192
+ 'lt': StrictLessThan,
1193
+ }
1194
+
1195
+
1196
+ def _n2(a, b):
1197
+ """Return (a - b).evalf(2) if a and b are comparable, else None.
1198
+ This should only be used when a and b are already sympified.
1199
+ """
1200
+ # /!\ it is very important (see issue 8245) not to
1201
+ # use a re-evaluated number in the calculation of dif
1202
+ if a.is_comparable and b.is_comparable:
1203
+ dif = (a - b).evalf(2)
1204
+ if dif.is_comparable:
1205
+ return dif
1206
+
1207
+
1208
+ @dispatch(Expr, Expr)
1209
+ def _eval_is_ge(lhs, rhs):
1210
+ return None
1211
+
1212
+
1213
+ @dispatch(Basic, Basic)
1214
+ def _eval_is_eq(lhs, rhs):
1215
+ return None
1216
+
1217
+
1218
+ @dispatch(Tuple, Expr) # type: ignore
1219
+ def _eval_is_eq(lhs, rhs): # noqa:F811
1220
+ return False
1221
+
1222
+
1223
+ @dispatch(Tuple, AppliedUndef) # type: ignore
1224
+ def _eval_is_eq(lhs, rhs): # noqa:F811
1225
+ return None
1226
+
1227
+
1228
+ @dispatch(Tuple, Symbol) # type: ignore
1229
+ def _eval_is_eq(lhs, rhs): # noqa:F811
1230
+ return None
1231
+
1232
+
1233
+ @dispatch(Tuple, Tuple) # type: ignore
1234
+ def _eval_is_eq(lhs, rhs): # noqa:F811
1235
+ if len(lhs) != len(rhs):
1236
+ return False
1237
+
1238
+ return fuzzy_and(fuzzy_bool(is_eq(s, o)) for s, o in zip(lhs, rhs))
1239
+
1240
+
1241
+ def is_lt(lhs, rhs, assumptions=None):
1242
+ """Fuzzy bool for lhs is strictly less than rhs.
1243
+
1244
+ See the docstring for :func:`~.is_ge` for more.
1245
+ """
1246
+ return fuzzy_not(is_ge(lhs, rhs, assumptions))
1247
+
1248
+
1249
+ def is_gt(lhs, rhs, assumptions=None):
1250
+ """Fuzzy bool for lhs is strictly greater than rhs.
1251
+
1252
+ See the docstring for :func:`~.is_ge` for more.
1253
+ """
1254
+ return fuzzy_not(is_le(lhs, rhs, assumptions))
1255
+
1256
+
1257
+ def is_le(lhs, rhs, assumptions=None):
1258
+ """Fuzzy bool for lhs is less than or equal to rhs.
1259
+
1260
+ See the docstring for :func:`~.is_ge` for more.
1261
+ """
1262
+ return is_ge(rhs, lhs, assumptions)
1263
+
1264
+
1265
+ def is_ge(lhs, rhs, assumptions=None):
1266
+ """
1267
+ Fuzzy bool for *lhs* is greater than or equal to *rhs*.
1268
+
1269
+ Parameters
1270
+ ==========
1271
+
1272
+ lhs : Expr
1273
+ The left-hand side of the expression, must be sympified,
1274
+ and an instance of expression. Throws an exception if
1275
+ lhs is not an instance of expression.
1276
+
1277
+ rhs : Expr
1278
+ The right-hand side of the expression, must be sympified
1279
+ and an instance of expression. Throws an exception if
1280
+ lhs is not an instance of expression.
1281
+
1282
+ assumptions: Boolean, optional
1283
+ Assumptions taken to evaluate the inequality.
1284
+
1285
+ Returns
1286
+ =======
1287
+
1288
+ ``True`` if *lhs* is greater than or equal to *rhs*, ``False`` if *lhs*
1289
+ is less than *rhs*, and ``None`` if the comparison between *lhs* and
1290
+ *rhs* is indeterminate.
1291
+
1292
+ Explanation
1293
+ ===========
1294
+
1295
+ This function is intended to give a relatively fast determination and
1296
+ deliberately does not attempt slow calculations that might help in
1297
+ obtaining a determination of True or False in more difficult cases.
1298
+
1299
+ The four comparison functions ``is_le``, ``is_lt``, ``is_ge``, and ``is_gt`` are
1300
+ each implemented in terms of ``is_ge`` in the following way:
1301
+
1302
+ is_ge(x, y) := is_ge(x, y)
1303
+ is_le(x, y) := is_ge(y, x)
1304
+ is_lt(x, y) := fuzzy_not(is_ge(x, y))
1305
+ is_gt(x, y) := fuzzy_not(is_ge(y, x))
1306
+
1307
+ Therefore, supporting new type with this function will ensure behavior for
1308
+ other three functions as well.
1309
+
1310
+ To maintain these equivalences in fuzzy logic it is important that in cases where
1311
+ either x or y is non-real all comparisons will give None.
1312
+
1313
+ Examples
1314
+ ========
1315
+
1316
+ >>> from sympy import S, Q
1317
+ >>> from sympy.core.relational import is_ge, is_le, is_gt, is_lt
1318
+ >>> from sympy.abc import x
1319
+ >>> is_ge(S(2), S(0))
1320
+ True
1321
+ >>> is_ge(S(0), S(2))
1322
+ False
1323
+ >>> is_le(S(0), S(2))
1324
+ True
1325
+ >>> is_gt(S(0), S(2))
1326
+ False
1327
+ >>> is_lt(S(2), S(0))
1328
+ False
1329
+
1330
+ Assumptions can be passed to evaluate the quality which is otherwise
1331
+ indeterminate.
1332
+
1333
+ >>> print(is_ge(x, S(0)))
1334
+ None
1335
+ >>> is_ge(x, S(0), assumptions=Q.positive(x))
1336
+ True
1337
+
1338
+ New types can be supported by dispatching to ``_eval_is_ge``.
1339
+
1340
+ >>> from sympy import Expr, sympify
1341
+ >>> from sympy.multipledispatch import dispatch
1342
+ >>> class MyExpr(Expr):
1343
+ ... def __new__(cls, arg):
1344
+ ... return super().__new__(cls, sympify(arg))
1345
+ ... @property
1346
+ ... def value(self):
1347
+ ... return self.args[0]
1348
+ >>> @dispatch(MyExpr, MyExpr)
1349
+ ... def _eval_is_ge(a, b):
1350
+ ... return is_ge(a.value, b.value)
1351
+ >>> a = MyExpr(1)
1352
+ >>> b = MyExpr(2)
1353
+ >>> is_ge(b, a)
1354
+ True
1355
+ >>> is_le(a, b)
1356
+ True
1357
+ """
1358
+ from sympy.assumptions.wrapper import AssumptionsWrapper, is_extended_nonnegative
1359
+
1360
+ if not (isinstance(lhs, Expr) and isinstance(rhs, Expr)):
1361
+ raise TypeError("Can only compare inequalities with Expr")
1362
+
1363
+ retval = _eval_is_ge(lhs, rhs)
1364
+
1365
+ if retval is not None:
1366
+ return retval
1367
+ else:
1368
+ n2 = _n2(lhs, rhs)
1369
+ if n2 is not None:
1370
+ # use float comparison for infinity.
1371
+ # otherwise get stuck in infinite recursion
1372
+ if n2 in (S.Infinity, S.NegativeInfinity):
1373
+ n2 = float(n2)
1374
+ return n2 >= 0
1375
+
1376
+ _lhs = AssumptionsWrapper(lhs, assumptions)
1377
+ _rhs = AssumptionsWrapper(rhs, assumptions)
1378
+ if _lhs.is_extended_real and _rhs.is_extended_real:
1379
+ if (_lhs.is_infinite and _lhs.is_extended_positive) or (_rhs.is_infinite and _rhs.is_extended_negative):
1380
+ return True
1381
+ diff = lhs - rhs
1382
+ if diff is not S.NaN:
1383
+ rv = is_extended_nonnegative(diff, assumptions)
1384
+ if rv is not None:
1385
+ return rv
1386
+
1387
+
1388
+ def is_neq(lhs, rhs, assumptions=None):
1389
+ """Fuzzy bool for lhs does not equal rhs.
1390
+
1391
+ See the docstring for :func:`~.is_eq` for more.
1392
+ """
1393
+ return fuzzy_not(is_eq(lhs, rhs, assumptions))
1394
+
1395
+
1396
+ def is_eq(lhs, rhs, assumptions=None):
1397
+ """
1398
+ Fuzzy bool representing mathematical equality between *lhs* and *rhs*.
1399
+
1400
+ Parameters
1401
+ ==========
1402
+
1403
+ lhs : Expr
1404
+ The left-hand side of the expression, must be sympified.
1405
+
1406
+ rhs : Expr
1407
+ The right-hand side of the expression, must be sympified.
1408
+
1409
+ assumptions: Boolean, optional
1410
+ Assumptions taken to evaluate the equality.
1411
+
1412
+ Returns
1413
+ =======
1414
+
1415
+ ``True`` if *lhs* is equal to *rhs*, ``False`` is *lhs* is not equal to *rhs*,
1416
+ and ``None`` if the comparison between *lhs* and *rhs* is indeterminate.
1417
+
1418
+ Explanation
1419
+ ===========
1420
+
1421
+ This function is intended to give a relatively fast determination and
1422
+ deliberately does not attempt slow calculations that might help in
1423
+ obtaining a determination of True or False in more difficult cases.
1424
+
1425
+ :func:`~.is_neq` calls this function to return its value, so supporting
1426
+ new type with this function will ensure correct behavior for ``is_neq``
1427
+ as well.
1428
+
1429
+ Examples
1430
+ ========
1431
+
1432
+ >>> from sympy import Q, S
1433
+ >>> from sympy.core.relational import is_eq, is_neq
1434
+ >>> from sympy.abc import x
1435
+ >>> is_eq(S(0), S(0))
1436
+ True
1437
+ >>> is_neq(S(0), S(0))
1438
+ False
1439
+ >>> is_eq(S(0), S(2))
1440
+ False
1441
+ >>> is_neq(S(0), S(2))
1442
+ True
1443
+
1444
+ Assumptions can be passed to evaluate the equality which is otherwise
1445
+ indeterminate.
1446
+
1447
+ >>> print(is_eq(x, S(0)))
1448
+ None
1449
+ >>> is_eq(x, S(0), assumptions=Q.zero(x))
1450
+ True
1451
+
1452
+ New types can be supported by dispatching to ``_eval_is_eq``.
1453
+
1454
+ >>> from sympy import Basic, sympify
1455
+ >>> from sympy.multipledispatch import dispatch
1456
+ >>> class MyBasic(Basic):
1457
+ ... def __new__(cls, arg):
1458
+ ... return Basic.__new__(cls, sympify(arg))
1459
+ ... @property
1460
+ ... def value(self):
1461
+ ... return self.args[0]
1462
+ ...
1463
+ >>> @dispatch(MyBasic, MyBasic)
1464
+ ... def _eval_is_eq(a, b):
1465
+ ... return is_eq(a.value, b.value)
1466
+ ...
1467
+ >>> a = MyBasic(1)
1468
+ >>> b = MyBasic(1)
1469
+ >>> is_eq(a, b)
1470
+ True
1471
+ >>> is_neq(a, b)
1472
+ False
1473
+
1474
+ """
1475
+ # here, _eval_Eq is only called for backwards compatibility
1476
+ # new code should use is_eq with multiple dispatch as
1477
+ # outlined in the docstring
1478
+ for side1, side2 in (lhs, rhs), (rhs, lhs):
1479
+ eval_func = getattr(side1, '_eval_Eq', None)
1480
+ if eval_func is not None:
1481
+ retval = eval_func(side2)
1482
+ if retval is not None:
1483
+ return retval
1484
+
1485
+ retval = _eval_is_eq(lhs, rhs)
1486
+ if retval is not None:
1487
+ return retval
1488
+
1489
+ if dispatch(type(lhs), type(rhs)) != dispatch(type(rhs), type(lhs)):
1490
+ retval = _eval_is_eq(rhs, lhs)
1491
+ if retval is not None:
1492
+ return retval
1493
+
1494
+ # retval is still None, so go through the equality logic
1495
+ # If expressions have the same structure, they must be equal.
1496
+ if lhs == rhs:
1497
+ return True # e.g. True == True
1498
+ elif all(isinstance(i, BooleanAtom) for i in (rhs, lhs)):
1499
+ return False # True != False
1500
+ elif not (lhs.is_Symbol or rhs.is_Symbol) and (
1501
+ isinstance(lhs, Boolean) !=
1502
+ isinstance(rhs, Boolean)):
1503
+ return False # only Booleans can equal Booleans
1504
+
1505
+ from sympy.assumptions.wrapper import (AssumptionsWrapper,
1506
+ is_infinite, is_extended_real)
1507
+ from .add import Add
1508
+
1509
+ _lhs = AssumptionsWrapper(lhs, assumptions)
1510
+ _rhs = AssumptionsWrapper(rhs, assumptions)
1511
+
1512
+ if _lhs.is_infinite or _rhs.is_infinite:
1513
+ if fuzzy_xor([_lhs.is_infinite, _rhs.is_infinite]):
1514
+ return False
1515
+ if fuzzy_xor([_lhs.is_extended_real, _rhs.is_extended_real]):
1516
+ return False
1517
+ if fuzzy_and([_lhs.is_extended_real, _rhs.is_extended_real]):
1518
+ return fuzzy_xor([_lhs.is_extended_positive, fuzzy_not(_rhs.is_extended_positive)])
1519
+
1520
+ # Try to split real/imaginary parts and equate them
1521
+ I = S.ImaginaryUnit
1522
+
1523
+ def split_real_imag(expr):
1524
+ real_imag = lambda t: (
1525
+ 'real' if is_extended_real(t, assumptions) else
1526
+ 'imag' if is_extended_real(I*t, assumptions) else None)
1527
+ return sift(Add.make_args(expr), real_imag)
1528
+
1529
+ lhs_ri = split_real_imag(lhs)
1530
+ if not lhs_ri[None]:
1531
+ rhs_ri = split_real_imag(rhs)
1532
+ if not rhs_ri[None]:
1533
+ eq_real = is_eq(Add(*lhs_ri['real']), Add(*rhs_ri['real']), assumptions)
1534
+ eq_imag = is_eq(I * Add(*lhs_ri['imag']), I * Add(*rhs_ri['imag']), assumptions)
1535
+ return fuzzy_and(map(fuzzy_bool, [eq_real, eq_imag]))
1536
+
1537
+ from sympy.functions.elementary.complexes import arg
1538
+ # Compare e.g. zoo with 1+I*oo by comparing args
1539
+ arglhs = arg(lhs)
1540
+ argrhs = arg(rhs)
1541
+ # Guard against Eq(nan, nan) -> False
1542
+ if not (arglhs == S.NaN and argrhs == S.NaN):
1543
+ return fuzzy_bool(is_eq(arglhs, argrhs, assumptions))
1544
+
1545
+ if all(isinstance(i, Expr) for i in (lhs, rhs)):
1546
+ # see if the difference evaluates
1547
+ dif = lhs - rhs
1548
+ _dif = AssumptionsWrapper(dif, assumptions)
1549
+ z = _dif.is_zero
1550
+ if z is not None:
1551
+ if z is False and _dif.is_commutative: # issue 10728
1552
+ return False
1553
+ if z:
1554
+ return True
1555
+
1556
+ n2 = _n2(lhs, rhs)
1557
+ if n2 is not None:
1558
+ return _sympify(n2 == 0)
1559
+
1560
+ # see if the ratio evaluates
1561
+ n, d = dif.as_numer_denom()
1562
+ rv = None
1563
+ _n = AssumptionsWrapper(n, assumptions)
1564
+ _d = AssumptionsWrapper(d, assumptions)
1565
+ if _n.is_zero:
1566
+ rv = _d.is_nonzero
1567
+ elif _n.is_finite:
1568
+ if _d.is_infinite:
1569
+ rv = True
1570
+ elif _n.is_zero is False:
1571
+ rv = _d.is_infinite
1572
+ if rv is None:
1573
+ # if the condition that makes the denominator
1574
+ # infinite does not make the original expression
1575
+ # True then False can be returned
1576
+ from sympy.simplify.simplify import clear_coefficients
1577
+ l, r = clear_coefficients(d, S.Infinity)
1578
+ args = [_.subs(l, r) for _ in (lhs, rhs)]
1579
+ if args != [lhs, rhs]:
1580
+ rv = fuzzy_bool(is_eq(*args, assumptions))
1581
+ if rv is True:
1582
+ rv = None
1583
+ elif any(is_infinite(a, assumptions) for a in Add.make_args(n)):
1584
+ # (inf or nan)/x != 0
1585
+ rv = False
1586
+ if rv is not None:
1587
+ return rv
venv/lib/python3.10/site-packages/sympy/core/sorting.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ from .sympify import sympify, SympifyError
4
+ from sympy.utilities.iterables import iterable, uniq
5
+
6
+
7
+ __all__ = ['default_sort_key', 'ordered']
8
+
9
+
10
+ def default_sort_key(item, order=None):
11
+ """Return a key that can be used for sorting.
12
+
13
+ The key has the structure:
14
+
15
+ (class_key, (len(args), args), exponent.sort_key(), coefficient)
16
+
17
+ This key is supplied by the sort_key routine of Basic objects when
18
+ ``item`` is a Basic object or an object (other than a string) that
19
+ sympifies to a Basic object. Otherwise, this function produces the
20
+ key.
21
+
22
+ The ``order`` argument is passed along to the sort_key routine and is
23
+ used to determine how the terms *within* an expression are ordered.
24
+ (See examples below) ``order`` options are: 'lex', 'grlex', 'grevlex',
25
+ and reversed values of the same (e.g. 'rev-lex'). The default order
26
+ value is None (which translates to 'lex').
27
+
28
+ Examples
29
+ ========
30
+
31
+ >>> from sympy import S, I, default_sort_key, sin, cos, sqrt
32
+ >>> from sympy.core.function import UndefinedFunction
33
+ >>> from sympy.abc import x
34
+
35
+ The following are equivalent ways of getting the key for an object:
36
+
37
+ >>> x.sort_key() == default_sort_key(x)
38
+ True
39
+
40
+ Here are some examples of the key that is produced:
41
+
42
+ >>> default_sort_key(UndefinedFunction('f'))
43
+ ((0, 0, 'UndefinedFunction'), (1, ('f',)), ((1, 0, 'Number'),
44
+ (0, ()), (), 1), 1)
45
+ >>> default_sort_key('1')
46
+ ((0, 0, 'str'), (1, ('1',)), ((1, 0, 'Number'), (0, ()), (), 1), 1)
47
+ >>> default_sort_key(S.One)
48
+ ((1, 0, 'Number'), (0, ()), (), 1)
49
+ >>> default_sort_key(2)
50
+ ((1, 0, 'Number'), (0, ()), (), 2)
51
+
52
+ While sort_key is a method only defined for SymPy objects,
53
+ default_sort_key will accept anything as an argument so it is
54
+ more robust as a sorting key. For the following, using key=
55
+ lambda i: i.sort_key() would fail because 2 does not have a sort_key
56
+ method; that's why default_sort_key is used. Note, that it also
57
+ handles sympification of non-string items likes ints:
58
+
59
+ >>> a = [2, I, -I]
60
+ >>> sorted(a, key=default_sort_key)
61
+ [2, -I, I]
62
+
63
+ The returned key can be used anywhere that a key can be specified for
64
+ a function, e.g. sort, min, max, etc...:
65
+
66
+ >>> a.sort(key=default_sort_key); a[0]
67
+ 2
68
+ >>> min(a, key=default_sort_key)
69
+ 2
70
+
71
+ Notes
72
+ =====
73
+
74
+ The key returned is useful for getting items into a canonical order
75
+ that will be the same across platforms. It is not directly useful for
76
+ sorting lists of expressions:
77
+
78
+ >>> a, b = x, 1/x
79
+
80
+ Since ``a`` has only 1 term, its value of sort_key is unaffected by
81
+ ``order``:
82
+
83
+ >>> a.sort_key() == a.sort_key('rev-lex')
84
+ True
85
+
86
+ If ``a`` and ``b`` are combined then the key will differ because there
87
+ are terms that can be ordered:
88
+
89
+ >>> eq = a + b
90
+ >>> eq.sort_key() == eq.sort_key('rev-lex')
91
+ False
92
+ >>> eq.as_ordered_terms()
93
+ [x, 1/x]
94
+ >>> eq.as_ordered_terms('rev-lex')
95
+ [1/x, x]
96
+
97
+ But since the keys for each of these terms are independent of ``order``'s
98
+ value, they do not sort differently when they appear separately in a list:
99
+
100
+ >>> sorted(eq.args, key=default_sort_key)
101
+ [1/x, x]
102
+ >>> sorted(eq.args, key=lambda i: default_sort_key(i, order='rev-lex'))
103
+ [1/x, x]
104
+
105
+ The order of terms obtained when using these keys is the order that would
106
+ be obtained if those terms were *factors* in a product.
107
+
108
+ Although it is useful for quickly putting expressions in canonical order,
109
+ it does not sort expressions based on their complexity defined by the
110
+ number of operations, power of variables and others:
111
+
112
+ >>> sorted([sin(x)*cos(x), sin(x)], key=default_sort_key)
113
+ [sin(x)*cos(x), sin(x)]
114
+ >>> sorted([x, x**2, sqrt(x), x**3], key=default_sort_key)
115
+ [sqrt(x), x, x**2, x**3]
116
+
117
+ See Also
118
+ ========
119
+
120
+ ordered, sympy.core.expr.Expr.as_ordered_factors, sympy.core.expr.Expr.as_ordered_terms
121
+
122
+ """
123
+ from .basic import Basic
124
+ from .singleton import S
125
+
126
+ if isinstance(item, Basic):
127
+ return item.sort_key(order=order)
128
+
129
+ if iterable(item, exclude=str):
130
+ if isinstance(item, dict):
131
+ args = item.items()
132
+ unordered = True
133
+ elif isinstance(item, set):
134
+ args = item
135
+ unordered = True
136
+ else:
137
+ # e.g. tuple, list
138
+ args = list(item)
139
+ unordered = False
140
+
141
+ args = [default_sort_key(arg, order=order) for arg in args]
142
+
143
+ if unordered:
144
+ # e.g. dict, set
145
+ args = sorted(args)
146
+
147
+ cls_index, args = 10, (len(args), tuple(args))
148
+ else:
149
+ if not isinstance(item, str):
150
+ try:
151
+ item = sympify(item, strict=True)
152
+ except SympifyError:
153
+ # e.g. lambda x: x
154
+ pass
155
+ else:
156
+ if isinstance(item, Basic):
157
+ # e.g int -> Integer
158
+ return default_sort_key(item)
159
+ # e.g. UndefinedFunction
160
+
161
+ # e.g. str
162
+ cls_index, args = 0, (1, (str(item),))
163
+
164
+ return (cls_index, 0, item.__class__.__name__
165
+ ), args, S.One.sort_key(), S.One
166
+
167
+
168
+ def _node_count(e):
169
+ # this not only counts nodes, it affirms that the
170
+ # args are Basic (i.e. have an args property). If
171
+ # some object has a non-Basic arg, it needs to be
172
+ # fixed since it is intended that all Basic args
173
+ # are of Basic type (though this is not easy to enforce).
174
+ if e.is_Float:
175
+ return 0.5
176
+ return 1 + sum(map(_node_count, e.args))
177
+
178
+
179
+ def _nodes(e):
180
+ """
181
+ A helper for ordered() which returns the node count of ``e`` which
182
+ for Basic objects is the number of Basic nodes in the expression tree
183
+ but for other objects is 1 (unless the object is an iterable or dict
184
+ for which the sum of nodes is returned).
185
+ """
186
+ from .basic import Basic
187
+ from .function import Derivative
188
+
189
+ if isinstance(e, Basic):
190
+ if isinstance(e, Derivative):
191
+ return _nodes(e.expr) + sum(i[1] if i[1].is_Number else
192
+ _nodes(i[1]) for i in e.variable_count)
193
+ return _node_count(e)
194
+ elif iterable(e):
195
+ return 1 + sum(_nodes(ei) for ei in e)
196
+ elif isinstance(e, dict):
197
+ return 1 + sum(_nodes(k) + _nodes(v) for k, v in e.items())
198
+ else:
199
+ return 1
200
+
201
+
202
+ def ordered(seq, keys=None, default=True, warn=False):
203
+ """Return an iterator of the seq where keys are used to break ties in
204
+ a conservative fashion: if, after applying a key, there are no ties
205
+ then no other keys will be computed.
206
+
207
+ Two default keys will be applied if 1) keys are not provided or 2) the
208
+ given keys do not resolve all ties (but only if ``default`` is True). The
209
+ two keys are ``_nodes`` (which places smaller expressions before large) and
210
+ ``default_sort_key`` which (if the ``sort_key`` for an object is defined
211
+ properly) should resolve any ties.
212
+
213
+ If ``warn`` is True then an error will be raised if there were no
214
+ keys remaining to break ties. This can be used if it was expected that
215
+ there should be no ties between items that are not identical.
216
+
217
+ Examples
218
+ ========
219
+
220
+ >>> from sympy import ordered, count_ops
221
+ >>> from sympy.abc import x, y
222
+
223
+ The count_ops is not sufficient to break ties in this list and the first
224
+ two items appear in their original order (i.e. the sorting is stable):
225
+
226
+ >>> list(ordered([y + 2, x + 2, x**2 + y + 3],
227
+ ... count_ops, default=False, warn=False))
228
+ ...
229
+ [y + 2, x + 2, x**2 + y + 3]
230
+
231
+ The default_sort_key allows the tie to be broken:
232
+
233
+ >>> list(ordered([y + 2, x + 2, x**2 + y + 3]))
234
+ ...
235
+ [x + 2, y + 2, x**2 + y + 3]
236
+
237
+ Here, sequences are sorted by length, then sum:
238
+
239
+ >>> seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], [
240
+ ... lambda x: len(x),
241
+ ... lambda x: sum(x)]]
242
+ ...
243
+ >>> list(ordered(seq, keys, default=False, warn=False))
244
+ [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]]
245
+
246
+ If ``warn`` is True, an error will be raised if there were not
247
+ enough keys to break ties:
248
+
249
+ >>> list(ordered(seq, keys, default=False, warn=True))
250
+ Traceback (most recent call last):
251
+ ...
252
+ ValueError: not enough keys to break ties
253
+
254
+
255
+ Notes
256
+ =====
257
+
258
+ The decorated sort is one of the fastest ways to sort a sequence for
259
+ which special item comparison is desired: the sequence is decorated,
260
+ sorted on the basis of the decoration (e.g. making all letters lower
261
+ case) and then undecorated. If one wants to break ties for items that
262
+ have the same decorated value, a second key can be used. But if the
263
+ second key is expensive to compute then it is inefficient to decorate
264
+ all items with both keys: only those items having identical first key
265
+ values need to be decorated. This function applies keys successively
266
+ only when needed to break ties. By yielding an iterator, use of the
267
+ tie-breaker is delayed as long as possible.
268
+
269
+ This function is best used in cases when use of the first key is
270
+ expected to be a good hashing function; if there are no unique hashes
271
+ from application of a key, then that key should not have been used. The
272
+ exception, however, is that even if there are many collisions, if the
273
+ first group is small and one does not need to process all items in the
274
+ list then time will not be wasted sorting what one was not interested
275
+ in. For example, if one were looking for the minimum in a list and
276
+ there were several criteria used to define the sort order, then this
277
+ function would be good at returning that quickly if the first group
278
+ of candidates is small relative to the number of items being processed.
279
+
280
+ """
281
+
282
+ d = defaultdict(list)
283
+ if keys:
284
+ if isinstance(keys, (list, tuple)):
285
+ keys = list(keys)
286
+ f = keys.pop(0)
287
+ else:
288
+ f = keys
289
+ keys = []
290
+ for a in seq:
291
+ d[f(a)].append(a)
292
+ else:
293
+ if not default:
294
+ raise ValueError('if default=False then keys must be provided')
295
+ d[None].extend(seq)
296
+
297
+ for k, value in sorted(d.items()):
298
+ if len(value) > 1:
299
+ if keys:
300
+ value = ordered(value, keys, default, warn)
301
+ elif default:
302
+ value = ordered(value, (_nodes, default_sort_key,),
303
+ default=False, warn=warn)
304
+ elif warn:
305
+ u = list(uniq(value))
306
+ if len(u) > 1:
307
+ raise ValueError(
308
+ 'not enough keys to break ties: %s' % u)
309
+ yield from value
venv/lib/python3.10/site-packages/sympy/core/trace.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.utilities.exceptions import sympy_deprecation_warning
2
+
3
+ sympy_deprecation_warning(
4
+ """
5
+ sympy.core.trace is deprecated. Use sympy.physics.quantum.trace
6
+ instead.
7
+ """,
8
+ deprecated_since_version="1.10",
9
+ active_deprecations_target="sympy-core-trace-deprecated",
10
+ )
11
+
12
+ from sympy.physics.quantum.trace import Tr # noqa:F401
venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.94 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/bivariate.cpython-310.pyc ADDED
Binary file (13.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/decompogen.cpython-310.pyc ADDED
Binary file (3.5 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/deutils.cpython-310.pyc ADDED
Binary file (8.06 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/inequalities.cpython-310.pyc ADDED
Binary file (23.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/pde.cpython-310.pyc ADDED
Binary file (29.8 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/polysys.cpython-310.pyc ADDED
Binary file (12.8 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/recurr.cpython-310.pyc ADDED
Binary file (22.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/solvers.cpython-310.pyc ADDED
Binary file (98.6 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/__pycache__/solveset.cpython-310.pyc ADDED
Binary file (105 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/benchmarks/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (192 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/benchmarks/__pycache__/bench_solvers.cpython-310.pyc ADDED
Binary file (732 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/benchmarks/bench_solvers.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import Symbol
2
+ from sympy.matrices.dense import (eye, zeros)
3
+ from sympy.solvers.solvers import solve_linear_system
4
+
5
+ N = 8
6
+ M = zeros(N, N + 1)
7
+ M[:, :N] = eye(N)
8
+ S = [Symbol('A%i' % i) for i in range(N)]
9
+
10
+
11
+ def timeit_linsolve_trivial():
12
+ solve_linear_system(M, *S)
venv/lib/python3.10/site-packages/sympy/solvers/diophantine/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .diophantine import diophantine, classify_diop, diop_solve
2
+
3
+ __all__ = [
4
+ 'diophantine', 'classify_diop', 'diop_solve'
5
+ ]
venv/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (291 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/diophantine.cpython-310.pyc ADDED
Binary file (103 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/diophantine/diophantine.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (199 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/test_diophantine.cpython-310.pyc ADDED
Binary file (46 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/test_diophantine.py ADDED
@@ -0,0 +1,1037 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.add import Add
2
+ from sympy.core.mul import Mul
3
+ from sympy.core.numbers import (Rational, oo, pi)
4
+ from sympy.core.relational import Eq
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import symbols
7
+ from sympy.matrices.dense import Matrix
8
+ from sympy.ntheory.factor_ import factorint
9
+ from sympy.simplify.powsimp import powsimp
10
+ from sympy.core.function import _mexpand
11
+ from sympy.core.sorting import default_sort_key, ordered
12
+ from sympy.functions.elementary.trigonometric import sin
13
+ from sympy.solvers.diophantine import diophantine
14
+ from sympy.solvers.diophantine.diophantine import (diop_DN,
15
+ diop_solve, diop_ternary_quadratic_normal,
16
+ diop_general_pythagorean, diop_ternary_quadratic, diop_linear,
17
+ diop_quadratic, diop_general_sum_of_squares, diop_general_sum_of_even_powers,
18
+ descent, diop_bf_DN, divisible, equivalent, find_DN, ldescent, length,
19
+ reconstruct, partition, power_representation,
20
+ prime_as_sum_of_two_squares, square_factor, sum_of_four_squares,
21
+ sum_of_three_squares, transformation_to_DN, transformation_to_normal,
22
+ classify_diop, base_solution_linear, cornacchia, sqf_normal, gaussian_reduce, holzer,
23
+ check_param, parametrize_ternary_quadratic, sum_of_powers, sum_of_squares,
24
+ _diop_ternary_quadratic_normal, _nint_or_floor,
25
+ _odd, _even, _remove_gcd, _can_do_sum_of_squares, DiophantineSolutionSet, GeneralPythagorean,
26
+ BinaryQuadratic)
27
+
28
+ from sympy.testing.pytest import slow, raises, XFAIL
29
+ from sympy.utilities.iterables import (
30
+ signed_permutations)
31
+
32
+ a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z = symbols(
33
+ "a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z", integer=True)
34
+ t_0, t_1, t_2, t_3, t_4, t_5, t_6 = symbols("t_:7", integer=True)
35
+ m1, m2, m3 = symbols('m1:4', integer=True)
36
+ n1 = symbols('n1', integer=True)
37
+
38
+
39
+ def diop_simplify(eq):
40
+ return _mexpand(powsimp(_mexpand(eq)))
41
+
42
+
43
+ def test_input_format():
44
+ raises(TypeError, lambda: diophantine(sin(x)))
45
+ raises(TypeError, lambda: diophantine(x/pi - 3))
46
+
47
+
48
+ def test_nosols():
49
+ # diophantine should sympify eq so that these are equivalent
50
+ assert diophantine(3) == set()
51
+ assert diophantine(S(3)) == set()
52
+
53
+
54
+ def test_univariate():
55
+ assert diop_solve((x - 1)*(x - 2)**2) == {(1,), (2,)}
56
+ assert diop_solve((x - 1)*(x - 2)) == {(1,), (2,)}
57
+
58
+
59
+ def test_classify_diop():
60
+ raises(TypeError, lambda: classify_diop(x**2/3 - 1))
61
+ raises(ValueError, lambda: classify_diop(1))
62
+ raises(NotImplementedError, lambda: classify_diop(w*x*y*z - 1))
63
+ raises(NotImplementedError, lambda: classify_diop(x**3 + y**3 + z**4 - 90))
64
+ assert classify_diop(14*x**2 + 15*x - 42) == (
65
+ [x], {1: -42, x: 15, x**2: 14}, 'univariate')
66
+ assert classify_diop(x*y + z) == (
67
+ [x, y, z], {x*y: 1, z: 1}, 'inhomogeneous_ternary_quadratic')
68
+ assert classify_diop(x*y + z + w + x**2) == (
69
+ [w, x, y, z], {x*y: 1, w: 1, x**2: 1, z: 1}, 'inhomogeneous_general_quadratic')
70
+ assert classify_diop(x*y + x*z + x**2 + 1) == (
71
+ [x, y, z], {x*y: 1, x*z: 1, x**2: 1, 1: 1}, 'inhomogeneous_general_quadratic')
72
+ assert classify_diop(x*y + z + w + 42) == (
73
+ [w, x, y, z], {x*y: 1, w: 1, 1: 42, z: 1}, 'inhomogeneous_general_quadratic')
74
+ assert classify_diop(x*y + z*w) == (
75
+ [w, x, y, z], {x*y: 1, w*z: 1}, 'homogeneous_general_quadratic')
76
+ assert classify_diop(x*y**2 + 1) == (
77
+ [x, y], {x*y**2: 1, 1: 1}, 'cubic_thue')
78
+ assert classify_diop(x**4 + y**4 + z**4 - (1 + 16 + 81)) == (
79
+ [x, y, z], {1: -98, x**4: 1, z**4: 1, y**4: 1}, 'general_sum_of_even_powers')
80
+ assert classify_diop(x**2 + y**2 + z**2) == (
81
+ [x, y, z], {x**2: 1, y**2: 1, z**2: 1}, 'homogeneous_ternary_quadratic_normal')
82
+
83
+
84
+ def test_linear():
85
+ assert diop_solve(x) == (0,)
86
+ assert diop_solve(1*x) == (0,)
87
+ assert diop_solve(3*x) == (0,)
88
+ assert diop_solve(x + 1) == (-1,)
89
+ assert diop_solve(2*x + 1) == (None,)
90
+ assert diop_solve(2*x + 4) == (-2,)
91
+ assert diop_solve(y + x) == (t_0, -t_0)
92
+ assert diop_solve(y + x + 0) == (t_0, -t_0)
93
+ assert diop_solve(y + x - 0) == (t_0, -t_0)
94
+ assert diop_solve(0*x - y - 5) == (-5,)
95
+ assert diop_solve(3*y + 2*x - 5) == (3*t_0 - 5, -2*t_0 + 5)
96
+ assert diop_solve(2*x - 3*y - 5) == (3*t_0 - 5, 2*t_0 - 5)
97
+ assert diop_solve(-2*x - 3*y - 5) == (3*t_0 + 5, -2*t_0 - 5)
98
+ assert diop_solve(7*x + 5*y) == (5*t_0, -7*t_0)
99
+ assert diop_solve(2*x + 4*y) == (2*t_0, -t_0)
100
+ assert diop_solve(4*x + 6*y - 4) == (3*t_0 - 2, -2*t_0 + 2)
101
+ assert diop_solve(4*x + 6*y - 3) == (None, None)
102
+ assert diop_solve(0*x + 3*y - 4*z + 5) == (4*t_0 + 5, 3*t_0 + 5)
103
+ assert diop_solve(4*x + 3*y - 4*z + 5) == (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5)
104
+ assert diop_solve(4*x + 3*y - 4*z + 5, None) == (0, 5, 5)
105
+ assert diop_solve(4*x + 2*y + 8*z - 5) == (None, None, None)
106
+ assert diop_solve(5*x + 7*y - 2*z - 6) == (t_0, -3*t_0 + 2*t_1 + 6, -8*t_0 + 7*t_1 + 18)
107
+ assert diop_solve(3*x - 6*y + 12*z - 9) == (2*t_0 + 3, t_0 + 2*t_1, t_1)
108
+ assert diop_solve(6*w + 9*x + 20*y - z) == (t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 20*t_2)
109
+
110
+ # to ignore constant factors, use diophantine
111
+ raises(TypeError, lambda: diop_solve(x/2))
112
+
113
+
114
+ def test_quadratic_simple_hyperbolic_case():
115
+ # Simple Hyperbolic case: A = C = 0 and B != 0
116
+ assert diop_solve(3*x*y + 34*x - 12*y + 1) == \
117
+ {(-133, -11), (5, -57)}
118
+ assert diop_solve(6*x*y + 2*x + 3*y + 1) == set()
119
+ assert diop_solve(-13*x*y + 2*x - 4*y - 54) == {(27, 0)}
120
+ assert diop_solve(-27*x*y - 30*x - 12*y - 54) == {(-14, -1)}
121
+ assert diop_solve(2*x*y + 5*x + 56*y + 7) == {(-161, -3), (-47, -6), (-35, -12),
122
+ (-29, -69), (-27, 64), (-21, 7),
123
+ (-9, 1), (105, -2)}
124
+ assert diop_solve(6*x*y + 9*x + 2*y + 3) == set()
125
+ assert diop_solve(x*y + x + y + 1) == {(-1, t), (t, -1)}
126
+ assert diophantine(48*x*y)
127
+
128
+
129
+ def test_quadratic_elliptical_case():
130
+ # Elliptical case: B**2 - 4AC < 0
131
+
132
+ assert diop_solve(42*x**2 + 8*x*y + 15*y**2 + 23*x + 17*y - 4915) == {(-11, -1)}
133
+ assert diop_solve(4*x**2 + 3*y**2 + 5*x - 11*y + 12) == set()
134
+ assert diop_solve(x**2 + y**2 + 2*x + 2*y + 2) == {(-1, -1)}
135
+ assert diop_solve(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950) == {(-15, 6)}
136
+ assert diop_solve(10*x**2 + 12*x*y + 12*y**2 - 34) == \
137
+ {(-1, -1), (-1, 2), (1, -2), (1, 1)}
138
+
139
+
140
+ def test_quadratic_parabolic_case():
141
+ # Parabolic case: B**2 - 4AC = 0
142
+ assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 5*x + 7*y + 16)
143
+ assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 6*x + 12*y - 6)
144
+ assert check_solutions(8*x**2 + 24*x*y + 18*y**2 + 4*x + 6*y - 7)
145
+ assert check_solutions(-4*x**2 + 4*x*y - y**2 + 2*x - 3)
146
+ assert check_solutions(x**2 + 2*x*y + y**2 + 2*x + 2*y + 1)
147
+ assert check_solutions(x**2 - 2*x*y + y**2 + 2*x + 2*y + 1)
148
+ assert check_solutions(y**2 - 41*x + 40)
149
+
150
+
151
+ def test_quadratic_perfect_square():
152
+ # B**2 - 4*A*C > 0
153
+ # B**2 - 4*A*C is a perfect square
154
+ assert check_solutions(48*x*y)
155
+ assert check_solutions(4*x**2 - 5*x*y + y**2 + 2)
156
+ assert check_solutions(-2*x**2 - 3*x*y + 2*y**2 -2*x - 17*y + 25)
157
+ assert check_solutions(12*x**2 + 13*x*y + 3*y**2 - 2*x + 3*y - 12)
158
+ assert check_solutions(8*x**2 + 10*x*y + 2*y**2 - 32*x - 13*y - 23)
159
+ assert check_solutions(4*x**2 - 4*x*y - 3*y- 8*x - 3)
160
+ assert check_solutions(- 4*x*y - 4*y**2 - 3*y- 5*x - 10)
161
+ assert check_solutions(x**2 - y**2 - 2*x - 2*y)
162
+ assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y)
163
+ assert check_solutions(4*x**2 - 9*y**2 - 4*x - 12*y - 3)
164
+
165
+
166
+ def test_quadratic_non_perfect_square():
167
+ # B**2 - 4*A*C is not a perfect square
168
+ # Used check_solutions() since the solutions are complex expressions involving
169
+ # square roots and exponents
170
+ assert check_solutions(x**2 - 2*x - 5*y**2)
171
+ assert check_solutions(3*x**2 - 2*y**2 - 2*x - 2*y)
172
+ assert check_solutions(x**2 - x*y - y**2 - 3*y)
173
+ assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y)
174
+ assert BinaryQuadratic(x**2 + y**2 + 2*x + 2*y + 2).solve() == {(-1, -1)}
175
+
176
+
177
+ def test_issue_9106():
178
+ eq = -48 - 2*x*(3*x - 1) + y*(3*y - 1)
179
+ v = (x, y)
180
+ for sol in diophantine(eq):
181
+ assert not diop_simplify(eq.xreplace(dict(zip(v, sol))))
182
+
183
+
184
+ def test_issue_18138():
185
+ eq = x**2 - x - y**2
186
+ v = (x, y)
187
+ for sol in diophantine(eq):
188
+ assert not diop_simplify(eq.xreplace(dict(zip(v, sol))))
189
+
190
+
191
+ @slow
192
+ def test_quadratic_non_perfect_slow():
193
+ assert check_solutions(8*x**2 + 10*x*y - 2*y**2 - 32*x - 13*y - 23)
194
+ # This leads to very large numbers.
195
+ # assert check_solutions(5*x**2 - 13*x*y + y**2 - 4*x - 4*y - 15)
196
+ assert check_solutions(-3*x**2 - 2*x*y + 7*y**2 - 5*x - 7)
197
+ assert check_solutions(-4 - x + 4*x**2 - y - 3*x*y - 4*y**2)
198
+ assert check_solutions(1 + 2*x + 2*x**2 + 2*y + x*y - 2*y**2)
199
+
200
+
201
+ def test_DN():
202
+ # Most of the test cases were adapted from,
203
+ # Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004.
204
+ # https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
205
+ # others are verified using Wolfram Alpha.
206
+
207
+ # Covers cases where D <= 0 or D > 0 and D is a square or N = 0
208
+ # Solutions are straightforward in these cases.
209
+ assert diop_DN(3, 0) == [(0, 0)]
210
+ assert diop_DN(-17, -5) == []
211
+ assert diop_DN(-19, 23) == [(2, 1)]
212
+ assert diop_DN(-13, 17) == [(2, 1)]
213
+ assert diop_DN(-15, 13) == []
214
+ assert diop_DN(0, 5) == []
215
+ assert diop_DN(0, 9) == [(3, t)]
216
+ assert diop_DN(9, 0) == [(3*t, t)]
217
+ assert diop_DN(16, 24) == []
218
+ assert diop_DN(9, 180) == [(18, 4)]
219
+ assert diop_DN(9, -180) == [(12, 6)]
220
+ assert diop_DN(7, 0) == [(0, 0)]
221
+
222
+ # When equation is x**2 + y**2 = N
223
+ # Solutions are interchangeable
224
+ assert diop_DN(-1, 5) == [(2, 1), (1, 2)]
225
+ assert diop_DN(-1, 169) == [(12, 5), (5, 12), (13, 0), (0, 13)]
226
+
227
+ # D > 0 and D is not a square
228
+
229
+ # N = 1
230
+ assert diop_DN(13, 1) == [(649, 180)]
231
+ assert diop_DN(980, 1) == [(51841, 1656)]
232
+ assert diop_DN(981, 1) == [(158070671986249, 5046808151700)]
233
+ assert diop_DN(986, 1) == [(49299, 1570)]
234
+ assert diop_DN(991, 1) == [(379516400906811930638014896080, 12055735790331359447442538767)]
235
+ assert diop_DN(17, 1) == [(33, 8)]
236
+ assert diop_DN(19, 1) == [(170, 39)]
237
+
238
+ # N = -1
239
+ assert diop_DN(13, -1) == [(18, 5)]
240
+ assert diop_DN(991, -1) == []
241
+ assert diop_DN(41, -1) == [(32, 5)]
242
+ assert diop_DN(290, -1) == [(17, 1)]
243
+ assert diop_DN(21257, -1) == [(13913102721304, 95427381109)]
244
+ assert diop_DN(32, -1) == []
245
+
246
+ # |N| > 1
247
+ # Some tests were created using calculator at
248
+ # http://www.numbertheory.org/php/patz.html
249
+
250
+ assert diop_DN(13, -4) == [(3, 1), (393, 109), (36, 10)]
251
+ # Source I referred returned (3, 1), (393, 109) and (-3, 1) as fundamental solutions
252
+ # So (-3, 1) and (393, 109) should be in the same equivalent class
253
+ assert equivalent(-3, 1, 393, 109, 13, -4) == True
254
+
255
+ assert diop_DN(13, 27) == [(220, 61), (40, 11), (768, 213), (12, 3)]
256
+ assert set(diop_DN(157, 12)) == {(13, 1), (10663, 851), (579160, 46222),
257
+ (483790960, 38610722), (26277068347, 2097138361),
258
+ (21950079635497, 1751807067011)}
259
+ assert diop_DN(13, 25) == [(3245, 900)]
260
+ assert diop_DN(192, 18) == []
261
+ assert diop_DN(23, 13) == [(-6, 1), (6, 1)]
262
+ assert diop_DN(167, 2) == [(13, 1)]
263
+ assert diop_DN(167, -2) == []
264
+
265
+ assert diop_DN(123, -2) == [(11, 1)]
266
+ # One calculator returned [(11, 1), (-11, 1)] but both of these are in
267
+ # the same equivalence class
268
+ assert equivalent(11, 1, -11, 1, 123, -2)
269
+
270
+ assert diop_DN(123, -23) == [(-10, 1), (10, 1)]
271
+
272
+ assert diop_DN(0, 0, t) == [(0, t)]
273
+ assert diop_DN(0, -1, t) == []
274
+
275
+
276
+ def test_bf_pell():
277
+ assert diop_bf_DN(13, -4) == [(3, 1), (-3, 1), (36, 10)]
278
+ assert diop_bf_DN(13, 27) == [(12, 3), (-12, 3), (40, 11), (-40, 11)]
279
+ assert diop_bf_DN(167, -2) == []
280
+ assert diop_bf_DN(1729, 1) == [(44611924489705, 1072885712316)]
281
+ assert diop_bf_DN(89, -8) == [(9, 1), (-9, 1)]
282
+ assert diop_bf_DN(21257, -1) == [(13913102721304, 95427381109)]
283
+ assert diop_bf_DN(340, -4) == [(756, 41)]
284
+ assert diop_bf_DN(-1, 0, t) == [(0, 0)]
285
+ assert diop_bf_DN(0, 0, t) == [(0, t)]
286
+ assert diop_bf_DN(4, 0, t) == [(2*t, t), (-2*t, t)]
287
+ assert diop_bf_DN(3, 0, t) == [(0, 0)]
288
+ assert diop_bf_DN(1, -2, t) == []
289
+
290
+
291
+ def test_length():
292
+ assert length(2, 1, 0) == 1
293
+ assert length(-2, 4, 5) == 3
294
+ assert length(-5, 4, 17) == 4
295
+ assert length(0, 4, 13) == 6
296
+ assert length(7, 13, 11) == 23
297
+ assert length(1, 6, 4) == 2
298
+
299
+
300
+ def is_pell_transformation_ok(eq):
301
+ """
302
+ Test whether X*Y, X, or Y terms are present in the equation
303
+ after transforming the equation using the transformation returned
304
+ by transformation_to_pell(). If they are not present we are good.
305
+ Moreover, coefficient of X**2 should be a divisor of coefficient of
306
+ Y**2 and the constant term.
307
+ """
308
+ A, B = transformation_to_DN(eq)
309
+ u = (A*Matrix([X, Y]) + B)[0]
310
+ v = (A*Matrix([X, Y]) + B)[1]
311
+ simplified = diop_simplify(eq.subs(zip((x, y), (u, v))))
312
+
313
+ coeff = dict([reversed(t.as_independent(*[X, Y])) for t in simplified.args])
314
+
315
+ for term in [X*Y, X, Y]:
316
+ if term in coeff.keys():
317
+ return False
318
+
319
+ for term in [X**2, Y**2, 1]:
320
+ if term not in coeff.keys():
321
+ coeff[term] = 0
322
+
323
+ if coeff[X**2] != 0:
324
+ return divisible(coeff[Y**2], coeff[X**2]) and \
325
+ divisible(coeff[1], coeff[X**2])
326
+
327
+ return True
328
+
329
+
330
+ def test_transformation_to_pell():
331
+ assert is_pell_transformation_ok(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y - 14)
332
+ assert is_pell_transformation_ok(-17*x**2 + 19*x*y - 7*y**2 - 5*x - 13*y - 23)
333
+ assert is_pell_transformation_ok(x**2 - y**2 + 17)
334
+ assert is_pell_transformation_ok(-x**2 + 7*y**2 - 23)
335
+ assert is_pell_transformation_ok(25*x**2 - 45*x*y + 5*y**2 - 5*x - 10*y + 5)
336
+ assert is_pell_transformation_ok(190*x**2 + 30*x*y + y**2 - 3*y - 170*x - 130)
337
+ assert is_pell_transformation_ok(x**2 - 2*x*y -190*y**2 - 7*y - 23*x - 89)
338
+ assert is_pell_transformation_ok(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950)
339
+
340
+
341
+ def test_find_DN():
342
+ assert find_DN(x**2 - 2*x - y**2) == (1, 1)
343
+ assert find_DN(x**2 - 3*y**2 - 5) == (3, 5)
344
+ assert find_DN(x**2 - 2*x*y - 4*y**2 - 7) == (5, 7)
345
+ assert find_DN(4*x**2 - 8*x*y - y**2 - 9) == (20, 36)
346
+ assert find_DN(7*x**2 - 2*x*y - y**2 - 12) == (8, 84)
347
+ assert find_DN(-3*x**2 + 4*x*y -y**2) == (1, 0)
348
+ assert find_DN(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y -14) == (101, -7825480)
349
+
350
+
351
+ def test_ldescent():
352
+ # Equations which have solutions
353
+ u = ([(13, 23), (3, -11), (41, -113), (4, -7), (-7, 4), (91, -3), (1, 1), (1, -1),
354
+ (4, 32), (17, 13), (123689, 1), (19, -570)])
355
+ for a, b in u:
356
+ w, x, y = ldescent(a, b)
357
+ assert a*x**2 + b*y**2 == w**2
358
+ assert ldescent(-1, -1) is None
359
+
360
+
361
+ def test_diop_ternary_quadratic_normal():
362
+ assert check_solutions(234*x**2 - 65601*y**2 - z**2)
363
+ assert check_solutions(23*x**2 + 616*y**2 - z**2)
364
+ assert check_solutions(5*x**2 + 4*y**2 - z**2)
365
+ assert check_solutions(3*x**2 + 6*y**2 - 3*z**2)
366
+ assert check_solutions(x**2 + 3*y**2 - z**2)
367
+ assert check_solutions(4*x**2 + 5*y**2 - z**2)
368
+ assert check_solutions(x**2 + y**2 - z**2)
369
+ assert check_solutions(16*x**2 + y**2 - 25*z**2)
370
+ assert check_solutions(6*x**2 - y**2 + 10*z**2)
371
+ assert check_solutions(213*x**2 + 12*y**2 - 9*z**2)
372
+ assert check_solutions(34*x**2 - 3*y**2 - 301*z**2)
373
+ assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
374
+
375
+
376
+ def is_normal_transformation_ok(eq):
377
+ A = transformation_to_normal(eq)
378
+ X, Y, Z = A*Matrix([x, y, z])
379
+ simplified = diop_simplify(eq.subs(zip((x, y, z), (X, Y, Z))))
380
+
381
+ coeff = dict([reversed(t.as_independent(*[X, Y, Z])) for t in simplified.args])
382
+ for term in [X*Y, Y*Z, X*Z]:
383
+ if term in coeff.keys():
384
+ return False
385
+
386
+ return True
387
+
388
+
389
+ def test_transformation_to_normal():
390
+ assert is_normal_transformation_ok(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z)
391
+ assert is_normal_transformation_ok(x**2 + 3*y**2 - 100*z**2)
392
+ assert is_normal_transformation_ok(x**2 + 23*y*z)
393
+ assert is_normal_transformation_ok(3*y**2 - 100*z**2 - 12*x*y)
394
+ assert is_normal_transformation_ok(x**2 + 23*x*y - 34*y*z + 12*x*z)
395
+ assert is_normal_transformation_ok(z**2 + 34*x*y - 23*y*z + x*z)
396
+ assert is_normal_transformation_ok(x**2 + y**2 + z**2 - x*y - y*z - x*z)
397
+ assert is_normal_transformation_ok(x**2 + 2*y*z + 3*z**2)
398
+ assert is_normal_transformation_ok(x*y + 2*x*z + 3*y*z)
399
+ assert is_normal_transformation_ok(2*x*z + 3*y*z)
400
+
401
+
402
+ def test_diop_ternary_quadratic():
403
+ assert check_solutions(2*x**2 + z**2 + y**2 - 4*x*y)
404
+ assert check_solutions(x**2 - y**2 - z**2 - x*y - y*z)
405
+ assert check_solutions(3*x**2 - x*y - y*z - x*z)
406
+ assert check_solutions(x**2 - y*z - x*z)
407
+ assert check_solutions(5*x**2 - 3*x*y - x*z)
408
+ assert check_solutions(4*x**2 - 5*y**2 - x*z)
409
+ assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
410
+ assert check_solutions(8*x**2 - 12*y*z)
411
+ assert check_solutions(45*x**2 - 7*y**2 - 8*x*y - z**2)
412
+ assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y)
413
+ assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z)
414
+ assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 17*y*z)
415
+ assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 16*y*z + 12*x*z)
416
+ assert check_solutions(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z)
417
+ assert check_solutions(x*y - 7*y*z + 13*x*z)
418
+
419
+ assert diop_ternary_quadratic_normal(x**2 + y**2 + z**2) == (None, None, None)
420
+ assert diop_ternary_quadratic_normal(x**2 + y**2) is None
421
+ raises(ValueError, lambda:
422
+ _diop_ternary_quadratic_normal((x, y, z),
423
+ {x*y: 1, x**2: 2, y**2: 3, z**2: 0}))
424
+ eq = -2*x*y - 6*x*z + 7*y**2 - 3*y*z + 4*z**2
425
+ assert diop_ternary_quadratic(eq) == (7, 2, 0)
426
+ assert diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2) == \
427
+ (1, 0, 2)
428
+ assert diop_ternary_quadratic(x*y + 2*y*z) == \
429
+ (-2, 0, n1)
430
+ eq = -5*x*y - 8*x*z - 3*y*z + 8*z**2
431
+ assert parametrize_ternary_quadratic(eq) == \
432
+ (8*p**2 - 3*p*q, -8*p*q + 8*q**2, 5*p*q)
433
+ # this cannot be tested with diophantine because it will
434
+ # factor into a product
435
+ assert diop_solve(x*y + 2*y*z) == (-2*p*q, -n1*p**2 + p**2, p*q)
436
+
437
+
438
+ def test_square_factor():
439
+ assert square_factor(1) == square_factor(-1) == 1
440
+ assert square_factor(0) == 1
441
+ assert square_factor(5) == square_factor(-5) == 1
442
+ assert square_factor(4) == square_factor(-4) == 2
443
+ assert square_factor(12) == square_factor(-12) == 2
444
+ assert square_factor(6) == 1
445
+ assert square_factor(18) == 3
446
+ assert square_factor(52) == 2
447
+ assert square_factor(49) == 7
448
+ assert square_factor(392) == 14
449
+ assert square_factor(factorint(-12)) == 2
450
+
451
+
452
+ def test_parametrize_ternary_quadratic():
453
+ assert check_solutions(x**2 + y**2 - z**2)
454
+ assert check_solutions(x**2 + 2*x*y + z**2)
455
+ assert check_solutions(234*x**2 - 65601*y**2 - z**2)
456
+ assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
457
+ assert check_solutions(x**2 - y**2 - z**2)
458
+ assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y - 8*x*y)
459
+ assert check_solutions(8*x*y + z**2)
460
+ assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
461
+ assert check_solutions(236*x**2 - 225*y**2 - 11*x*y - 13*y*z - 17*x*z)
462
+ assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z)
463
+ assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
464
+
465
+
466
+ def test_no_square_ternary_quadratic():
467
+ assert check_solutions(2*x*y + y*z - 3*x*z)
468
+ assert check_solutions(189*x*y - 345*y*z - 12*x*z)
469
+ assert check_solutions(23*x*y + 34*y*z)
470
+ assert check_solutions(x*y + y*z + z*x)
471
+ assert check_solutions(23*x*y + 23*y*z + 23*x*z)
472
+
473
+
474
+ def test_descent():
475
+
476
+ u = ([(13, 23), (3, -11), (41, -113), (91, -3), (1, 1), (1, -1), (17, 13), (123689, 1), (19, -570)])
477
+ for a, b in u:
478
+ w, x, y = descent(a, b)
479
+ assert a*x**2 + b*y**2 == w**2
480
+ # the docstring warns against bad input, so these are expected results
481
+ # - can't both be negative
482
+ raises(TypeError, lambda: descent(-1, -3))
483
+ # A can't be zero unless B != 1
484
+ raises(ZeroDivisionError, lambda: descent(0, 3))
485
+ # supposed to be square-free
486
+ raises(TypeError, lambda: descent(4, 3))
487
+
488
+
489
+ def test_diophantine():
490
+ assert check_solutions((x - y)*(y - z)*(z - x))
491
+ assert check_solutions((x - y)*(x**2 + y**2 - z**2))
492
+ assert check_solutions((x - 3*y + 7*z)*(x**2 + y**2 - z**2))
493
+ assert check_solutions(x**2 - 3*y**2 - 1)
494
+ assert check_solutions(y**2 + 7*x*y)
495
+ assert check_solutions(x**2 - 3*x*y + y**2)
496
+ assert check_solutions(z*(x**2 - y**2 - 15))
497
+ assert check_solutions(x*(2*y - 2*z + 5))
498
+ assert check_solutions((x**2 - 3*y**2 - 1)*(x**2 - y**2 - 15))
499
+ assert check_solutions((x**2 - 3*y**2 - 1)*(y - 7*z))
500
+ assert check_solutions((x**2 + y**2 - z**2)*(x - 7*y - 3*z + 4*w))
501
+ # Following test case caused problems in parametric representation
502
+ # But this can be solved by factoring out y.
503
+ # No need to use methods for ternary quadratic equations.
504
+ assert check_solutions(y**2 - 7*x*y + 4*y*z)
505
+ assert check_solutions(x**2 - 2*x + 1)
506
+
507
+ assert diophantine(x - y) == diophantine(Eq(x, y))
508
+ # 18196
509
+ eq = x**4 + y**4 - 97
510
+ assert diophantine(eq, permute=True) == diophantine(-eq, permute=True)
511
+ assert diophantine(3*x*pi - 2*y*pi) == {(2*t_0, 3*t_0)}
512
+ eq = x**2 + y**2 + z**2 - 14
513
+ base_sol = {(1, 2, 3)}
514
+ assert diophantine(eq) == base_sol
515
+ complete_soln = set(signed_permutations(base_sol.pop()))
516
+ assert diophantine(eq, permute=True) == complete_soln
517
+
518
+ assert diophantine(x**2 + x*Rational(15, 14) - 3) == set()
519
+ # test issue 11049
520
+ eq = 92*x**2 - 99*y**2 - z**2
521
+ coeff = eq.as_coefficients_dict()
522
+ assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
523
+ {(9, 7, 51)}
524
+ assert diophantine(eq) == {(
525
+ 891*p**2 + 9*q**2, -693*p**2 - 102*p*q + 7*q**2,
526
+ 5049*p**2 - 1386*p*q - 51*q**2)}
527
+ eq = 2*x**2 + 2*y**2 - z**2
528
+ coeff = eq.as_coefficients_dict()
529
+ assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
530
+ {(1, 1, 2)}
531
+ assert diophantine(eq) == {(
532
+ 2*p**2 - q**2, -2*p**2 + 4*p*q - q**2,
533
+ 4*p**2 - 4*p*q + 2*q**2)}
534
+ eq = 411*x**2+57*y**2-221*z**2
535
+ coeff = eq.as_coefficients_dict()
536
+ assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
537
+ {(2021, 2645, 3066)}
538
+ assert diophantine(eq) == \
539
+ {(115197*p**2 - 446641*q**2, -150765*p**2 + 1355172*p*q -
540
+ 584545*q**2, 174762*p**2 - 301530*p*q + 677586*q**2)}
541
+ eq = 573*x**2+267*y**2-984*z**2
542
+ coeff = eq.as_coefficients_dict()
543
+ assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
544
+ {(49, 233, 127)}
545
+ assert diophantine(eq) == \
546
+ {(4361*p**2 - 16072*q**2, -20737*p**2 + 83312*p*q - 76424*q**2,
547
+ 11303*p**2 - 41474*p*q + 41656*q**2)}
548
+ # this produces factors during reconstruction
549
+ eq = x**2 + 3*y**2 - 12*z**2
550
+ coeff = eq.as_coefficients_dict()
551
+ assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
552
+ {(0, 2, 1)}
553
+ assert diophantine(eq) == \
554
+ {(24*p*q, 2*p**2 - 24*q**2, p**2 + 12*q**2)}
555
+ # solvers have not been written for every type
556
+ raises(NotImplementedError, lambda: diophantine(x*y**2 + 1))
557
+
558
+ # rational expressions
559
+ assert diophantine(1/x) == set()
560
+ assert diophantine(1/x + 1/y - S.Half) == {(6, 3), (-2, 1), (4, 4), (1, -2), (3, 6)}
561
+ assert diophantine(x**2 + y**2 +3*x- 5, permute=True) == \
562
+ {(-1, 1), (-4, -1), (1, -1), (1, 1), (-4, 1), (-1, -1), (4, 1), (4, -1)}
563
+
564
+
565
+ #test issue 18186
566
+ assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(x, y), permute=True) == \
567
+ {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
568
+ assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(y, x), permute=True) == \
569
+ {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
570
+
571
+ # issue 18122
572
+ assert check_solutions(x**2-y)
573
+ assert check_solutions(y**2-x)
574
+ assert diophantine((x**2-y), t) == {(t, t**2)}
575
+ assert diophantine((y**2-x), t) == {(t**2, -t)}
576
+
577
+
578
+ def test_general_pythagorean():
579
+ from sympy.abc import a, b, c, d, e
580
+
581
+ assert check_solutions(a**2 + b**2 + c**2 - d**2)
582
+ assert check_solutions(a**2 + 4*b**2 + 4*c**2 - d**2)
583
+ assert check_solutions(9*a**2 + 4*b**2 + 4*c**2 - d**2)
584
+ assert check_solutions(9*a**2 + 4*b**2 - 25*d**2 + 4*c**2 )
585
+ assert check_solutions(9*a**2 - 16*d**2 + 4*b**2 + 4*c**2)
586
+ assert check_solutions(-e**2 + 9*a**2 + 4*b**2 + 4*c**2 + 25*d**2)
587
+ assert check_solutions(16*a**2 - b**2 + 9*c**2 + d**2 + 25*e**2)
588
+
589
+ assert GeneralPythagorean(a**2 + b**2 + c**2 - d**2).solve(parameters=[x, y, z]) == \
590
+ {(x**2 + y**2 - z**2, 2*x*z, 2*y*z, x**2 + y**2 + z**2)}
591
+
592
+
593
+ def test_diop_general_sum_of_squares_quick():
594
+ for i in range(3, 10):
595
+ assert check_solutions(sum(i**2 for i in symbols(':%i' % i)) - i)
596
+
597
+ assert diop_general_sum_of_squares(x**2 + y**2 - 2) is None
598
+ assert diop_general_sum_of_squares(x**2 + y**2 + z**2 + 2) == set()
599
+ eq = x**2 + y**2 + z**2 - (1 + 4 + 9)
600
+ assert diop_general_sum_of_squares(eq) == \
601
+ {(1, 2, 3)}
602
+ eq = u**2 + v**2 + x**2 + y**2 + z**2 - 1313
603
+ assert len(diop_general_sum_of_squares(eq, 3)) == 3
604
+ # issue 11016
605
+ var = symbols(':5') + (symbols('6', negative=True),)
606
+ eq = Add(*[i**2 for i in var]) - 112
607
+
608
+ base_soln = {(0, 1, 1, 5, 6, -7), (1, 1, 1, 3, 6, -8), (2, 3, 3, 4, 5, -7), (0, 1, 1, 1, 3, -10),
609
+ (0, 0, 4, 4, 4, -8), (1, 2, 3, 3, 5, -8), (0, 1, 2, 3, 7, -7), (2, 2, 4, 4, 6, -6),
610
+ (1, 1, 3, 4, 6, -7), (0, 2, 3, 3, 3, -9), (0, 0, 2, 2, 2, -10), (1, 1, 2, 3, 4, -9),
611
+ (0, 1, 1, 2, 5, -9), (0, 0, 2, 6, 6, -6), (1, 3, 4, 5, 5, -6), (0, 2, 2, 2, 6, -8),
612
+ (0, 3, 3, 3, 6, -7), (0, 2, 3, 5, 5, -7), (0, 1, 5, 5, 5, -6)}
613
+ assert diophantine(eq) == base_soln
614
+ assert len(diophantine(eq, permute=True)) == 196800
615
+
616
+ # handle negated squares with signsimp
617
+ assert diophantine(12 - x**2 - y**2 - z**2) == {(2, 2, 2)}
618
+ # diophantine handles simplification, so classify_diop should
619
+ # not have to look for additional patterns that are removed
620
+ # by diophantine
621
+ eq = a**2 + b**2 + c**2 + d**2 - 4
622
+ raises(NotImplementedError, lambda: classify_diop(-eq))
623
+
624
+
625
+ def test_issue_23807():
626
+ # fixes recursion error
627
+ eq = x**2 + y**2 + z**2 - 1000000
628
+ base_soln = {(0, 0, 1000), (0, 352, 936), (480, 600, 640), (24, 640, 768), (192, 640, 744),
629
+ (192, 480, 856), (168, 224, 960), (0, 600, 800), (280, 576, 768), (152, 480, 864),
630
+ (0, 280, 960), (352, 360, 864), (424, 480, 768), (360, 480, 800), (224, 600, 768),
631
+ (96, 360, 928), (168, 576, 800), (96, 480, 872)}
632
+
633
+ assert diophantine(eq) == base_soln
634
+
635
+
636
+ def test_diop_partition():
637
+ for n in [8, 10]:
638
+ for k in range(1, 8):
639
+ for p in partition(n, k):
640
+ assert len(p) == k
641
+ assert list(partition(3, 5)) == []
642
+ assert [list(p) for p in partition(3, 5, 1)] == [
643
+ [0, 0, 0, 0, 3], [0, 0, 0, 1, 2], [0, 0, 1, 1, 1]]
644
+ assert list(partition(0)) == [()]
645
+ assert list(partition(1, 0)) == [()]
646
+ assert [list(i) for i in partition(3)] == [[1, 1, 1], [1, 2], [3]]
647
+
648
+
649
+ def test_prime_as_sum_of_two_squares():
650
+ for i in [5, 13, 17, 29, 37, 41, 2341, 3557, 34841, 64601]:
651
+ a, b = prime_as_sum_of_two_squares(i)
652
+ assert a**2 + b**2 == i
653
+ assert prime_as_sum_of_two_squares(7) is None
654
+ ans = prime_as_sum_of_two_squares(800029)
655
+ assert ans == (450, 773) and type(ans[0]) is int
656
+
657
+
658
+ def test_sum_of_three_squares():
659
+ for i in [0, 1, 2, 34, 123, 34304595905, 34304595905394941, 343045959052344,
660
+ 800, 801, 802, 803, 804, 805, 806]:
661
+ a, b, c = sum_of_three_squares(i)
662
+ assert a**2 + b**2 + c**2 == i
663
+
664
+ assert sum_of_three_squares(7) is None
665
+ assert sum_of_three_squares((4**5)*15) is None
666
+ assert sum_of_three_squares(25) == (5, 0, 0)
667
+ assert sum_of_three_squares(4) == (0, 0, 2)
668
+
669
+
670
+ def test_sum_of_four_squares():
671
+ from sympy.core.random import randint
672
+
673
+ # this should never fail
674
+ n = randint(1, 100000000000000)
675
+ assert sum(i**2 for i in sum_of_four_squares(n)) == n
676
+
677
+ assert sum_of_four_squares(0) == (0, 0, 0, 0)
678
+ assert sum_of_four_squares(14) == (0, 1, 2, 3)
679
+ assert sum_of_four_squares(15) == (1, 1, 2, 3)
680
+ assert sum_of_four_squares(18) == (1, 2, 2, 3)
681
+ assert sum_of_four_squares(19) == (0, 1, 3, 3)
682
+ assert sum_of_four_squares(48) == (0, 4, 4, 4)
683
+
684
+
685
+ def test_power_representation():
686
+ tests = [(1729, 3, 2), (234, 2, 4), (2, 1, 2), (3, 1, 3), (5, 2, 2), (12352, 2, 4),
687
+ (32760, 2, 3)]
688
+
689
+ for test in tests:
690
+ n, p, k = test
691
+ f = power_representation(n, p, k)
692
+
693
+ while True:
694
+ try:
695
+ l = next(f)
696
+ assert len(l) == k
697
+
698
+ chk_sum = 0
699
+ for l_i in l:
700
+ chk_sum = chk_sum + l_i**p
701
+ assert chk_sum == n
702
+
703
+ except StopIteration:
704
+ break
705
+
706
+ assert list(power_representation(20, 2, 4, True)) == \
707
+ [(1, 1, 3, 3), (0, 0, 2, 4)]
708
+ raises(ValueError, lambda: list(power_representation(1.2, 2, 2)))
709
+ raises(ValueError, lambda: list(power_representation(2, 0, 2)))
710
+ raises(ValueError, lambda: list(power_representation(2, 2, 0)))
711
+ assert list(power_representation(-1, 2, 2)) == []
712
+ assert list(power_representation(1, 1, 1)) == [(1,)]
713
+ assert list(power_representation(3, 2, 1)) == []
714
+ assert list(power_representation(4, 2, 1)) == [(2,)]
715
+ assert list(power_representation(3**4, 4, 6, zeros=True)) == \
716
+ [(1, 2, 2, 2, 2, 2), (0, 0, 0, 0, 0, 3)]
717
+ assert list(power_representation(3**4, 4, 5, zeros=False)) == []
718
+ assert list(power_representation(-2, 3, 2)) == [(-1, -1)]
719
+ assert list(power_representation(-2, 4, 2)) == []
720
+ assert list(power_representation(0, 3, 2, True)) == [(0, 0)]
721
+ assert list(power_representation(0, 3, 2, False)) == []
722
+ # when we are dealing with squares, do feasibility checks
723
+ assert len(list(power_representation(4**10*(8*10 + 7), 2, 3))) == 0
724
+ # there will be a recursion error if these aren't recognized
725
+ big = 2**30
726
+ for i in [13, 10, 7, 5, 4, 2, 1]:
727
+ assert list(sum_of_powers(big, 2, big - i)) == []
728
+
729
+
730
+ def test_assumptions():
731
+ """
732
+ Test whether diophantine respects the assumptions.
733
+ """
734
+ #Test case taken from the below so question regarding assumptions in diophantine module
735
+ #https://stackoverflow.com/questions/23301941/how-can-i-declare-natural-symbols-with-sympy
736
+ m, n = symbols('m n', integer=True, positive=True)
737
+ diof = diophantine(n**2 + m*n - 500)
738
+ assert diof == {(5, 20), (40, 10), (95, 5), (121, 4), (248, 2), (499, 1)}
739
+
740
+ a, b = symbols('a b', integer=True, positive=False)
741
+ diof = diophantine(a*b + 2*a + 3*b - 6)
742
+ assert diof == {(-15, -3), (-9, -4), (-7, -5), (-6, -6), (-5, -8), (-4, -14)}
743
+
744
+
745
+ def check_solutions(eq):
746
+ """
747
+ Determines whether solutions returned by diophantine() satisfy the original
748
+ equation. Hope to generalize this so we can remove functions like check_ternay_quadratic,
749
+ check_solutions_normal, check_solutions()
750
+ """
751
+ s = diophantine(eq)
752
+
753
+ factors = Mul.make_args(eq)
754
+
755
+ var = list(eq.free_symbols)
756
+ var.sort(key=default_sort_key)
757
+
758
+ while s:
759
+ solution = s.pop()
760
+ for f in factors:
761
+ if diop_simplify(f.subs(zip(var, solution))) == 0:
762
+ break
763
+ else:
764
+ return False
765
+ return True
766
+
767
+
768
+ def test_diopcoverage():
769
+ eq = (2*x + y + 1)**2
770
+ assert diop_solve(eq) == {(t_0, -2*t_0 - 1)}
771
+ eq = 2*x**2 + 6*x*y + 12*x + 4*y**2 + 18*y + 18
772
+ assert diop_solve(eq) == {(t, -t - 3), (2*t - 3, -t)}
773
+ assert diop_quadratic(x + y**2 - 3) == {(-t**2 + 3, -t)}
774
+
775
+ assert diop_linear(x + y - 3) == (t_0, 3 - t_0)
776
+
777
+ assert base_solution_linear(0, 1, 2, t=None) == (0, 0)
778
+ ans = (3*t - 1, -2*t + 1)
779
+ assert base_solution_linear(4, 8, 12, t) == ans
780
+ assert base_solution_linear(4, 8, 12, t=None) == tuple(_.subs(t, 0) for _ in ans)
781
+
782
+ assert cornacchia(1, 1, 20) is None
783
+ assert cornacchia(1, 1, 5) == {(2, 1)}
784
+ assert cornacchia(1, 2, 17) == {(3, 2)}
785
+
786
+ raises(ValueError, lambda: reconstruct(4, 20, 1))
787
+
788
+ assert gaussian_reduce(4, 1, 3) == (1, 1)
789
+ eq = -w**2 - x**2 - y**2 + z**2
790
+
791
+ assert diop_general_pythagorean(eq) == \
792
+ diop_general_pythagorean(-eq) == \
793
+ (m1**2 + m2**2 - m3**2, 2*m1*m3,
794
+ 2*m2*m3, m1**2 + m2**2 + m3**2)
795
+
796
+ assert len(check_param(S(3) + x/3, S(4) + x/2, S(2), [x])) == 0
797
+ assert len(check_param(Rational(3, 2), S(4) + x, S(2), [x])) == 0
798
+ assert len(check_param(S(4) + x, Rational(3, 2), S(2), [x])) == 0
799
+
800
+ assert _nint_or_floor(16, 10) == 2
801
+ assert _odd(1) == (not _even(1)) == True
802
+ assert _odd(0) == (not _even(0)) == False
803
+ assert _remove_gcd(2, 4, 6) == (1, 2, 3)
804
+ raises(TypeError, lambda: _remove_gcd((2, 4, 6)))
805
+ assert sqf_normal(2*3**2*5, 2*5*11, 2*7**2*11) == \
806
+ (11, 1, 5)
807
+
808
+ # it's ok if these pass some day when the solvers are implemented
809
+ raises(NotImplementedError, lambda: diophantine(x**2 + y**2 + x*y + 2*y*z - 12))
810
+ raises(NotImplementedError, lambda: diophantine(x**3 + y**2))
811
+ assert diop_quadratic(x**2 + y**2 - 1**2 - 3**4) == \
812
+ {(-9, -1), (-9, 1), (-1, -9), (-1, 9), (1, -9), (1, 9), (9, -1), (9, 1)}
813
+
814
+
815
+ def test_holzer():
816
+ # if the input is good, don't let it diverge in holzer()
817
+ # (but see test_fail_holzer below)
818
+ assert holzer(2, 7, 13, 4, 79, 23) == (2, 7, 13)
819
+
820
+ # None in uv condition met; solution is not Holzer reduced
821
+ # so this will hopefully change but is here for coverage
822
+ assert holzer(2, 6, 2, 1, 1, 10) == (2, 6, 2)
823
+
824
+ raises(ValueError, lambda: holzer(2, 7, 14, 4, 79, 23))
825
+
826
+
827
+ @XFAIL
828
+ def test_fail_holzer():
829
+ eq = lambda x, y, z: a*x**2 + b*y**2 - c*z**2
830
+ a, b, c = 4, 79, 23
831
+ x, y, z = xyz = 26, 1, 11
832
+ X, Y, Z = ans = 2, 7, 13
833
+ assert eq(*xyz) == 0
834
+ assert eq(*ans) == 0
835
+ assert max(a*x**2, b*y**2, c*z**2) <= a*b*c
836
+ assert max(a*X**2, b*Y**2, c*Z**2) <= a*b*c
837
+ h = holzer(x, y, z, a, b, c)
838
+ assert h == ans # it would be nice to get the smaller soln
839
+
840
+
841
+ def test_issue_9539():
842
+ assert diophantine(6*w + 9*y + 20*x - z) == \
843
+ {(t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 9*t_2)}
844
+
845
+
846
+ def test_issue_8943():
847
+ assert diophantine(
848
+ 3*(x**2 + y**2 + z**2) - 14*(x*y + y*z + z*x)) == \
849
+ {(0, 0, 0)}
850
+
851
+
852
+ def test_diop_sum_of_even_powers():
853
+ eq = x**4 + y**4 + z**4 - 2673
854
+ assert diop_solve(eq) == {(3, 6, 6), (2, 4, 7)}
855
+ assert diop_general_sum_of_even_powers(eq, 2) == {(3, 6, 6), (2, 4, 7)}
856
+ raises(NotImplementedError, lambda: diop_general_sum_of_even_powers(-eq, 2))
857
+ neg = symbols('neg', negative=True)
858
+ eq = x**4 + y**4 + neg**4 - 2673
859
+ assert diop_general_sum_of_even_powers(eq) == {(-3, 6, 6)}
860
+ assert diophantine(x**4 + y**4 + 2) == set()
861
+ assert diop_general_sum_of_even_powers(x**4 + y**4 - 2, limit=0) == set()
862
+
863
+
864
+ def test_sum_of_squares_powers():
865
+ tru = {(0, 0, 1, 1, 11), (0, 0, 5, 7, 7), (0, 1, 3, 7, 8), (0, 1, 4, 5, 9), (0, 3, 4, 7, 7), (0, 3, 5, 5, 8),
866
+ (1, 1, 2, 6, 9), (1, 1, 6, 6, 7), (1, 2, 3, 3, 10), (1, 3, 4, 4, 9), (1, 5, 5, 6, 6), (2, 2, 3, 5, 9),
867
+ (2, 3, 5, 6, 7), (3, 3, 4, 5, 8)}
868
+ eq = u**2 + v**2 + x**2 + y**2 + z**2 - 123
869
+ ans = diop_general_sum_of_squares(eq, oo) # allow oo to be used
870
+ assert len(ans) == 14
871
+ assert ans == tru
872
+
873
+ raises(ValueError, lambda: list(sum_of_squares(10, -1)))
874
+ assert list(sum_of_squares(-10, 2)) == []
875
+ assert list(sum_of_squares(2, 3)) == []
876
+ assert list(sum_of_squares(0, 3, True)) == [(0, 0, 0)]
877
+ assert list(sum_of_squares(0, 3)) == []
878
+ assert list(sum_of_squares(4, 1)) == [(2,)]
879
+ assert list(sum_of_squares(5, 1)) == []
880
+ assert list(sum_of_squares(50, 2)) == [(5, 5), (1, 7)]
881
+ assert list(sum_of_squares(11, 5, True)) == [
882
+ (1, 1, 1, 2, 2), (0, 0, 1, 1, 3)]
883
+ assert list(sum_of_squares(8, 8)) == [(1, 1, 1, 1, 1, 1, 1, 1)]
884
+
885
+ assert [len(list(sum_of_squares(i, 5, True))) for i in range(30)] == [
886
+ 1, 1, 1, 1, 2,
887
+ 2, 1, 1, 2, 2,
888
+ 2, 2, 2, 3, 2,
889
+ 1, 3, 3, 3, 3,
890
+ 4, 3, 3, 2, 2,
891
+ 4, 4, 4, 4, 5]
892
+ assert [len(list(sum_of_squares(i, 5))) for i in range(30)] == [
893
+ 0, 0, 0, 0, 0,
894
+ 1, 0, 0, 1, 0,
895
+ 0, 1, 0, 1, 1,
896
+ 0, 1, 1, 0, 1,
897
+ 2, 1, 1, 1, 1,
898
+ 1, 1, 1, 1, 3]
899
+ for i in range(30):
900
+ s1 = set(sum_of_squares(i, 5, True))
901
+ assert not s1 or all(sum(j**2 for j in t) == i for t in s1)
902
+ s2 = set(sum_of_squares(i, 5))
903
+ assert all(sum(j**2 for j in t) == i for t in s2)
904
+
905
+ raises(ValueError, lambda: list(sum_of_powers(2, -1, 1)))
906
+ raises(ValueError, lambda: list(sum_of_powers(2, 1, -1)))
907
+ assert list(sum_of_powers(-2, 3, 2)) == [(-1, -1)]
908
+ assert list(sum_of_powers(-2, 4, 2)) == []
909
+ assert list(sum_of_powers(2, 1, 1)) == [(2,)]
910
+ assert list(sum_of_powers(2, 1, 3, True)) == [(0, 0, 2), (0, 1, 1)]
911
+ assert list(sum_of_powers(5, 1, 2, True)) == [(0, 5), (1, 4), (2, 3)]
912
+ assert list(sum_of_powers(6, 2, 2)) == []
913
+ assert list(sum_of_powers(3**5, 3, 1)) == []
914
+ assert list(sum_of_powers(3**6, 3, 1)) == [(9,)] and (9**3 == 3**6)
915
+ assert list(sum_of_powers(2**1000, 5, 2)) == []
916
+
917
+
918
+ def test__can_do_sum_of_squares():
919
+ assert _can_do_sum_of_squares(3, -1) is False
920
+ assert _can_do_sum_of_squares(-3, 1) is False
921
+ assert _can_do_sum_of_squares(0, 1)
922
+ assert _can_do_sum_of_squares(4, 1)
923
+ assert _can_do_sum_of_squares(1, 2)
924
+ assert _can_do_sum_of_squares(2, 2)
925
+ assert _can_do_sum_of_squares(3, 2) is False
926
+
927
+
928
+ def test_diophantine_permute_sign():
929
+ from sympy.abc import a, b, c, d, e
930
+ eq = a**4 + b**4 - (2**4 + 3**4)
931
+ base_sol = {(2, 3)}
932
+ assert diophantine(eq) == base_sol
933
+ complete_soln = set(signed_permutations(base_sol.pop()))
934
+ assert diophantine(eq, permute=True) == complete_soln
935
+
936
+ eq = a**2 + b**2 + c**2 + d**2 + e**2 - 234
937
+ assert len(diophantine(eq)) == 35
938
+ assert len(diophantine(eq, permute=True)) == 62000
939
+ soln = {(-1, -1), (-1, 2), (1, -2), (1, 1)}
940
+ assert diophantine(10*x**2 + 12*x*y + 12*y**2 - 34, permute=True) == soln
941
+
942
+
943
+ @XFAIL
944
+ def test_not_implemented():
945
+ eq = x**2 + y**4 - 1**2 - 3**4
946
+ assert diophantine(eq, syms=[x, y]) == {(9, 1), (1, 3)}
947
+
948
+
949
+ def test_issue_9538():
950
+ eq = x - 3*y + 2
951
+ assert diophantine(eq, syms=[y,x]) == {(t_0, 3*t_0 - 2)}
952
+ raises(TypeError, lambda: diophantine(eq, syms={y, x}))
953
+
954
+
955
+ def test_ternary_quadratic():
956
+ # solution with 3 parameters
957
+ s = diophantine(2*x**2 + y**2 - 2*z**2)
958
+ p, q, r = ordered(S(s).free_symbols)
959
+ assert s == {(
960
+ p**2 - 2*q**2,
961
+ -2*p**2 + 4*p*q - 4*p*r - 4*q**2,
962
+ p**2 - 4*p*q + 2*q**2 - 4*q*r)}
963
+ # solution with Mul in solution
964
+ s = diophantine(x**2 + 2*y**2 - 2*z**2)
965
+ assert s == {(4*p*q, p**2 - 2*q**2, p**2 + 2*q**2)}
966
+ # solution with no Mul in solution
967
+ s = diophantine(2*x**2 + 2*y**2 - z**2)
968
+ assert s == {(2*p**2 - q**2, -2*p**2 + 4*p*q - q**2,
969
+ 4*p**2 - 4*p*q + 2*q**2)}
970
+ # reduced form when parametrized
971
+ s = diophantine(3*x**2 + 72*y**2 - 27*z**2)
972
+ assert s == {(24*p**2 - 9*q**2, 6*p*q, 8*p**2 + 3*q**2)}
973
+ assert parametrize_ternary_quadratic(
974
+ 3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) == (
975
+ 2*p**2 - 2*p*q - q**2, 2*p**2 + 2*p*q - q**2, 2*p**2 -
976
+ 2*p*q + 3*q**2)
977
+ assert parametrize_ternary_quadratic(
978
+ 124*x**2 - 30*y**2 - 7729*z**2) == (
979
+ -1410*p**2 - 363263*q**2, 2700*p**2 + 30916*p*q -
980
+ 695610*q**2, -60*p**2 + 5400*p*q + 15458*q**2)
981
+
982
+
983
+ def test_diophantine_solution_set():
984
+ s1 = DiophantineSolutionSet([], [])
985
+ assert set(s1) == set()
986
+ assert s1.symbols == ()
987
+ assert s1.parameters == ()
988
+ raises(ValueError, lambda: s1.add((x,)))
989
+ assert list(s1.dict_iterator()) == []
990
+
991
+ s2 = DiophantineSolutionSet([x, y], [t, u])
992
+ assert s2.symbols == (x, y)
993
+ assert s2.parameters == (t, u)
994
+ raises(ValueError, lambda: s2.add((1,)))
995
+ s2.add((3, 4))
996
+ assert set(s2) == {(3, 4)}
997
+ s2.update((3, 4), (-1, u))
998
+ assert set(s2) == {(3, 4), (-1, u)}
999
+ raises(ValueError, lambda: s1.update(s2))
1000
+ assert list(s2.dict_iterator()) == [{x: -1, y: u}, {x: 3, y: 4}]
1001
+
1002
+ s3 = DiophantineSolutionSet([x, y, z], [t, u])
1003
+ assert len(s3.parameters) == 2
1004
+ s3.add((t**2 + u, t - u, 1))
1005
+ assert set(s3) == {(t**2 + u, t - u, 1)}
1006
+ assert s3.subs(t, 2) == {(u + 4, 2 - u, 1)}
1007
+ assert s3(2) == {(u + 4, 2 - u, 1)}
1008
+ assert s3.subs({t: 7, u: 8}) == {(57, -1, 1)}
1009
+ assert s3(7, 8) == {(57, -1, 1)}
1010
+ assert s3.subs({t: 5}) == {(u + 25, 5 - u, 1)}
1011
+ assert s3(5) == {(u + 25, 5 - u, 1)}
1012
+ assert s3.subs(u, -3) == {(t**2 - 3, t + 3, 1)}
1013
+ assert s3(None, -3) == {(t**2 - 3, t + 3, 1)}
1014
+ assert s3.subs({t: 2, u: 8}) == {(12, -6, 1)}
1015
+ assert s3(2, 8) == {(12, -6, 1)}
1016
+ assert s3.subs({t: 5, u: -3}) == {(22, 8, 1)}
1017
+ assert s3(5, -3) == {(22, 8, 1)}
1018
+ raises(ValueError, lambda: s3.subs(x=1))
1019
+ raises(ValueError, lambda: s3.subs(1, 2, 3))
1020
+ raises(ValueError, lambda: s3.add(()))
1021
+ raises(ValueError, lambda: s3.add((1, 2, 3, 4)))
1022
+ raises(ValueError, lambda: s3.add((1, 2)))
1023
+ raises(ValueError, lambda: s3(1, 2, 3))
1024
+ raises(TypeError, lambda: s3(t=1))
1025
+
1026
+ s4 = DiophantineSolutionSet([x, y], [t, u])
1027
+ s4.add((t, 11*t))
1028
+ s4.add((-t, 22*t))
1029
+ assert s4(0, 0) == {(0, 0)}
1030
+
1031
+
1032
+ def test_quadratic_parameter_passing():
1033
+ eq = -33*x*y + 3*y**2
1034
+ solution = BinaryQuadratic(eq).solve(parameters=[t, u])
1035
+ # test that parameters are passed all the way to the final solution
1036
+ assert solution == {(t, 11*t), (-t, 22*t)}
1037
+ assert solution(0, 0) == {(0, 0)}
venv/lib/python3.10/site-packages/sympy/solvers/ode/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .ode import (allhints, checkinfsol, classify_ode,
2
+ constantsimp, dsolve, homogeneous_order)
3
+
4
+ from .lie_group import infinitesimals
5
+
6
+ from .subscheck import checkodesol
7
+
8
+ from .systems import (canonical_odes, linear_ode_to_matrix,
9
+ linodesolve)
10
+
11
+
12
+ __all__ = [
13
+ 'allhints', 'checkinfsol', 'checkodesol', 'classify_ode', 'constantsimp',
14
+ 'dsolve', 'homogeneous_order', 'infinitesimals', 'canonical_odes', 'linear_ode_to_matrix',
15
+ 'linodesolve'
16
+ ]
venv/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (602 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/hypergeometric.cpython-310.pyc ADDED
Binary file (7.07 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/lie_group.cpython-310.pyc ADDED
Binary file (30.8 kB). View file
 
venv/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/nonhomogeneous.cpython-310.pyc ADDED
Binary file (14.8 kB). View file