applied-ai-018 commited on
Commit
f1a7d0b
·
verified ·
1 Parent(s): 72e4051

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. env-llmeval/lib/python3.10/site-packages/sympy/core/__init__.py +100 -0
  2. env-llmeval/lib/python3.10/site-packages/sympy/core/assumptions.py +692 -0
  3. env-llmeval/lib/python3.10/site-packages/sympy/core/backend.py +84 -0
  4. env-llmeval/lib/python3.10/site-packages/sympy/core/basic.py +2233 -0
  5. env-llmeval/lib/python3.10/site-packages/sympy/core/cache.py +210 -0
  6. env-llmeval/lib/python3.10/site-packages/sympy/core/compatibility.py +35 -0
  7. env-llmeval/lib/python3.10/site-packages/sympy/core/containers.py +410 -0
  8. env-llmeval/lib/python3.10/site-packages/sympy/core/core.py +63 -0
  9. env-llmeval/lib/python3.10/site-packages/sympy/core/coreerrors.py +9 -0
  10. env-llmeval/lib/python3.10/site-packages/sympy/core/evalf.py +1801 -0
  11. env-llmeval/lib/python3.10/site-packages/sympy/core/exprtools.py +1569 -0
  12. env-llmeval/lib/python3.10/site-packages/sympy/core/facts.py +634 -0
  13. env-llmeval/lib/python3.10/site-packages/sympy/core/kind.py +388 -0
  14. env-llmeval/lib/python3.10/site-packages/sympy/core/logic.py +427 -0
  15. env-llmeval/lib/python3.10/site-packages/sympy/core/mul.py +2195 -0
  16. env-llmeval/lib/python3.10/site-packages/sympy/core/numbers.py +0 -0
  17. env-llmeval/lib/python3.10/site-packages/sympy/core/operations.py +722 -0
  18. env-llmeval/lib/python3.10/site-packages/sympy/core/parameters.py +161 -0
  19. env-llmeval/lib/python3.10/site-packages/sympy/core/random.py +227 -0
  20. env-llmeval/lib/python3.10/site-packages/sympy/core/relational.py +1587 -0
  21. env-llmeval/lib/python3.10/site-packages/sympy/core/singleton.py +174 -0
  22. env-llmeval/lib/python3.10/site-packages/sympy/core/sorting.py +309 -0
  23. env-llmeval/lib/python3.10/site-packages/sympy/core/sympify.py +634 -0
  24. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/__init__.py +0 -0
  25. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_args.py +0 -0
  26. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_arit.py +2463 -0
  27. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_assumptions.py +1335 -0
  28. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_basic.py +319 -0
  29. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_cache.py +91 -0
  30. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_compatibility.py +6 -0
  31. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_complex.py +226 -0
  32. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_constructor_postprocessor.py +87 -0
  33. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_containers.py +217 -0
  34. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_count_ops.py +155 -0
  35. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_diff.py +160 -0
  36. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_equal.py +89 -0
  37. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_eval.py +95 -0
  38. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_evalf.py +732 -0
  39. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_expr.py +2261 -0
  40. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_exprtools.py +493 -0
  41. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_facts.py +312 -0
  42. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_function.py +1455 -0
  43. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_kind.py +57 -0
  44. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_logic.py +198 -0
  45. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_match.py +766 -0
  46. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_multidimensional.py +24 -0
  47. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_noncommutative.py +140 -0
  48. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_numbers.py +2266 -0
  49. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_operations.py +110 -0
  50. env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_parameters.py +90 -0
env-llmeval/lib/python3.10/site-packages/sympy/core/__init__.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core module. Provides the basic operations needed in sympy.
2
+ """
3
+
4
+ from .sympify import sympify, SympifyError
5
+ from .cache import cacheit
6
+ from .assumptions import assumptions, check_assumptions, failing_assumptions, common_assumptions
7
+ from .basic import Basic, Atom
8
+ from .singleton import S
9
+ from .expr import Expr, AtomicExpr, UnevaluatedExpr
10
+ from .symbol import Symbol, Wild, Dummy, symbols, var
11
+ from .numbers import Number, Float, Rational, Integer, NumberSymbol, \
12
+ RealNumber, igcd, ilcm, seterr, E, I, nan, oo, pi, zoo, \
13
+ AlgebraicNumber, comp, mod_inverse
14
+ from .power import Pow, integer_nthroot, integer_log
15
+ from .mul import Mul, prod
16
+ from .add import Add
17
+ from .mod import Mod
18
+ from .relational import ( Rel, Eq, Ne, Lt, Le, Gt, Ge,
19
+ Equality, GreaterThan, LessThan, Unequality, StrictGreaterThan,
20
+ StrictLessThan )
21
+ from .multidimensional import vectorize
22
+ from .function import Lambda, WildFunction, Derivative, diff, FunctionClass, \
23
+ Function, Subs, expand, PoleError, count_ops, \
24
+ expand_mul, expand_log, expand_func, \
25
+ expand_trig, expand_complex, expand_multinomial, nfloat, \
26
+ expand_power_base, expand_power_exp, arity
27
+ from .evalf import PrecisionExhausted, N
28
+ from .containers import Tuple, Dict
29
+ from .exprtools import gcd_terms, factor_terms, factor_nc
30
+ from .parameters import evaluate
31
+ from .kind import UndefinedKind, NumberKind, BooleanKind
32
+ from .traversal import preorder_traversal, bottom_up, use, postorder_traversal
33
+ from .sorting import default_sort_key, ordered
34
+
35
+ # expose singletons
36
+ Catalan = S.Catalan
37
+ EulerGamma = S.EulerGamma
38
+ GoldenRatio = S.GoldenRatio
39
+ TribonacciConstant = S.TribonacciConstant
40
+
41
+ __all__ = [
42
+ 'sympify', 'SympifyError',
43
+
44
+ 'cacheit',
45
+
46
+ 'assumptions', 'check_assumptions', 'failing_assumptions',
47
+ 'common_assumptions',
48
+
49
+ 'Basic', 'Atom',
50
+
51
+ 'S',
52
+
53
+ 'Expr', 'AtomicExpr', 'UnevaluatedExpr',
54
+
55
+ 'Symbol', 'Wild', 'Dummy', 'symbols', 'var',
56
+
57
+ 'Number', 'Float', 'Rational', 'Integer', 'NumberSymbol', 'RealNumber',
58
+ 'igcd', 'ilcm', 'seterr', 'E', 'I', 'nan', 'oo', 'pi', 'zoo',
59
+ 'AlgebraicNumber', 'comp', 'mod_inverse',
60
+
61
+ 'Pow', 'integer_nthroot', 'integer_log',
62
+
63
+ 'Mul', 'prod',
64
+
65
+ 'Add',
66
+
67
+ 'Mod',
68
+
69
+ 'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge', 'Equality', 'GreaterThan',
70
+ 'LessThan', 'Unequality', 'StrictGreaterThan', 'StrictLessThan',
71
+
72
+ 'vectorize',
73
+
74
+ 'Lambda', 'WildFunction', 'Derivative', 'diff', 'FunctionClass',
75
+ 'Function', 'Subs', 'expand', 'PoleError', 'count_ops', 'expand_mul',
76
+ 'expand_log', 'expand_func', 'expand_trig', 'expand_complex',
77
+ 'expand_multinomial', 'nfloat', 'expand_power_base', 'expand_power_exp',
78
+ 'arity',
79
+
80
+ 'PrecisionExhausted', 'N',
81
+
82
+ 'evalf', # The module?
83
+
84
+ 'Tuple', 'Dict',
85
+
86
+ 'gcd_terms', 'factor_terms', 'factor_nc',
87
+
88
+ 'evaluate',
89
+
90
+ 'Catalan',
91
+ 'EulerGamma',
92
+ 'GoldenRatio',
93
+ 'TribonacciConstant',
94
+
95
+ 'UndefinedKind', 'NumberKind', 'BooleanKind',
96
+
97
+ 'preorder_traversal', 'bottom_up', 'use', 'postorder_traversal',
98
+
99
+ 'default_sort_key', 'ordered',
100
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/core/assumptions.py ADDED
@@ -0,0 +1,692 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module contains the machinery handling assumptions.
3
+ Do also consider the guide :ref:`assumptions-guide`.
4
+
5
+ All symbolic objects have assumption attributes that can be accessed via
6
+ ``.is_<assumption name>`` attribute.
7
+
8
+ Assumptions determine certain properties of symbolic objects and can
9
+ have 3 possible values: ``True``, ``False``, ``None``. ``True`` is returned if the
10
+ object has the property and ``False`` is returned if it does not or cannot
11
+ (i.e. does not make sense):
12
+
13
+ >>> from sympy import I
14
+ >>> I.is_algebraic
15
+ True
16
+ >>> I.is_real
17
+ False
18
+ >>> I.is_prime
19
+ False
20
+
21
+ When the property cannot be determined (or when a method is not
22
+ implemented) ``None`` will be returned. For example, a generic symbol, ``x``,
23
+ may or may not be positive so a value of ``None`` is returned for ``x.is_positive``.
24
+
25
+ By default, all symbolic values are in the largest set in the given context
26
+ without specifying the property. For example, a symbol that has a property
27
+ being integer, is also real, complex, etc.
28
+
29
+ Here follows a list of possible assumption names:
30
+
31
+ .. glossary::
32
+
33
+ commutative
34
+ object commutes with any other object with
35
+ respect to multiplication operation. See [12]_.
36
+
37
+ complex
38
+ object can have only values from the set
39
+ of complex numbers. See [13]_.
40
+
41
+ imaginary
42
+ object value is a number that can be written as a real
43
+ number multiplied by the imaginary unit ``I``. See
44
+ [3]_. Please note that ``0`` is not considered to be an
45
+ imaginary number, see
46
+ `issue #7649 <https://github.com/sympy/sympy/issues/7649>`_.
47
+
48
+ real
49
+ object can have only values from the set
50
+ of real numbers.
51
+
52
+ extended_real
53
+ object can have only values from the set
54
+ of real numbers, ``oo`` and ``-oo``.
55
+
56
+ integer
57
+ object can have only values from the set
58
+ of integers.
59
+
60
+ odd
61
+ even
62
+ object can have only values from the set of
63
+ odd (even) integers [2]_.
64
+
65
+ prime
66
+ object is a natural number greater than 1 that has
67
+ no positive divisors other than 1 and itself. See [6]_.
68
+
69
+ composite
70
+ object is a positive integer that has at least one positive
71
+ divisor other than 1 or the number itself. See [4]_.
72
+
73
+ zero
74
+ object has the value of 0.
75
+
76
+ nonzero
77
+ object is a real number that is not zero.
78
+
79
+ rational
80
+ object can have only values from the set
81
+ of rationals.
82
+
83
+ algebraic
84
+ object can have only values from the set
85
+ of algebraic numbers [11]_.
86
+
87
+ transcendental
88
+ object can have only values from the set
89
+ of transcendental numbers [10]_.
90
+
91
+ irrational
92
+ object value cannot be represented exactly by :class:`~.Rational`, see [5]_.
93
+
94
+ finite
95
+ infinite
96
+ object absolute value is bounded (arbitrarily large).
97
+ See [7]_, [8]_, [9]_.
98
+
99
+ negative
100
+ nonnegative
101
+ object can have only negative (nonnegative)
102
+ values [1]_.
103
+
104
+ positive
105
+ nonpositive
106
+ object can have only positive (nonpositive) values.
107
+
108
+ extended_negative
109
+ extended_nonnegative
110
+ extended_positive
111
+ extended_nonpositive
112
+ extended_nonzero
113
+ as without the extended part, but also including infinity with
114
+ corresponding sign, e.g., extended_positive includes ``oo``
115
+
116
+ hermitian
117
+ antihermitian
118
+ object belongs to the field of Hermitian
119
+ (antihermitian) operators.
120
+
121
+ Examples
122
+ ========
123
+
124
+ >>> from sympy import Symbol
125
+ >>> x = Symbol('x', real=True); x
126
+ x
127
+ >>> x.is_real
128
+ True
129
+ >>> x.is_complex
130
+ True
131
+
132
+ See Also
133
+ ========
134
+
135
+ .. seealso::
136
+
137
+ :py:class:`sympy.core.numbers.ImaginaryUnit`
138
+ :py:class:`sympy.core.numbers.Zero`
139
+ :py:class:`sympy.core.numbers.One`
140
+ :py:class:`sympy.core.numbers.Infinity`
141
+ :py:class:`sympy.core.numbers.NegativeInfinity`
142
+ :py:class:`sympy.core.numbers.ComplexInfinity`
143
+
144
+ Notes
145
+ =====
146
+
147
+ The fully-resolved assumptions for any SymPy expression
148
+ can be obtained as follows:
149
+
150
+ >>> from sympy.core.assumptions import assumptions
151
+ >>> x = Symbol('x',positive=True)
152
+ >>> assumptions(x + I)
153
+ {'commutative': True, 'complex': True, 'composite': False, 'even':
154
+ False, 'extended_negative': False, 'extended_nonnegative': False,
155
+ 'extended_nonpositive': False, 'extended_nonzero': False,
156
+ 'extended_positive': False, 'extended_real': False, 'finite': True,
157
+ 'imaginary': False, 'infinite': False, 'integer': False, 'irrational':
158
+ False, 'negative': False, 'noninteger': False, 'nonnegative': False,
159
+ 'nonpositive': False, 'nonzero': False, 'odd': False, 'positive':
160
+ False, 'prime': False, 'rational': False, 'real': False, 'zero':
161
+ False}
162
+
163
+ Developers Notes
164
+ ================
165
+
166
+ The current (and possibly incomplete) values are stored
167
+ in the ``obj._assumptions dictionary``; queries to getter methods
168
+ (with property decorators) or attributes of objects/classes
169
+ will return values and update the dictionary.
170
+
171
+ >>> eq = x**2 + I
172
+ >>> eq._assumptions
173
+ {}
174
+ >>> eq.is_finite
175
+ True
176
+ >>> eq._assumptions
177
+ {'finite': True, 'infinite': False}
178
+
179
+ For a :class:`~.Symbol`, there are two locations for assumptions that may
180
+ be of interest. The ``assumptions0`` attribute gives the full set of
181
+ assumptions derived from a given set of initial assumptions. The
182
+ latter assumptions are stored as ``Symbol._assumptions_orig``
183
+
184
+ >>> Symbol('x', prime=True, even=True)._assumptions_orig
185
+ {'even': True, 'prime': True}
186
+
187
+ The ``_assumptions_orig`` are not necessarily canonical nor are they filtered
188
+ in any way: they records the assumptions used to instantiate a Symbol and (for
189
+ storage purposes) represent a more compact representation of the assumptions
190
+ needed to recreate the full set in ``Symbol.assumptions0``.
191
+
192
+
193
+ References
194
+ ==========
195
+
196
+ .. [1] https://en.wikipedia.org/wiki/Negative_number
197
+ .. [2] https://en.wikipedia.org/wiki/Parity_%28mathematics%29
198
+ .. [3] https://en.wikipedia.org/wiki/Imaginary_number
199
+ .. [4] https://en.wikipedia.org/wiki/Composite_number
200
+ .. [5] https://en.wikipedia.org/wiki/Irrational_number
201
+ .. [6] https://en.wikipedia.org/wiki/Prime_number
202
+ .. [7] https://en.wikipedia.org/wiki/Finite
203
+ .. [8] https://docs.python.org/3/library/math.html#math.isfinite
204
+ .. [9] https://numpy.org/doc/stable/reference/generated/numpy.isfinite.html
205
+ .. [10] https://en.wikipedia.org/wiki/Transcendental_number
206
+ .. [11] https://en.wikipedia.org/wiki/Algebraic_number
207
+ .. [12] https://en.wikipedia.org/wiki/Commutative_property
208
+ .. [13] https://en.wikipedia.org/wiki/Complex_number
209
+
210
+ """
211
+
212
+ from sympy.utilities.exceptions import sympy_deprecation_warning
213
+
214
+ from .facts import FactRules, FactKB
215
+ from .sympify import sympify
216
+
217
+ from sympy.core.random import _assumptions_shuffle as shuffle
218
+ from sympy.core.assumptions_generated import generated_assumptions as _assumptions
219
+
220
+ def _load_pre_generated_assumption_rules():
221
+ """ Load the assumption rules from pre-generated data
222
+
223
+ To update the pre-generated data, see :method::`_generate_assumption_rules`
224
+ """
225
+ _assume_rules=FactRules._from_python(_assumptions)
226
+ return _assume_rules
227
+
228
+ def _generate_assumption_rules():
229
+ """ Generate the default assumption rules
230
+
231
+ This method should only be called to update the pre-generated
232
+ assumption rules.
233
+
234
+ To update the pre-generated assumptions run: bin/ask_update.py
235
+
236
+ """
237
+ _assume_rules = FactRules([
238
+
239
+ 'integer -> rational',
240
+ 'rational -> real',
241
+ 'rational -> algebraic',
242
+ 'algebraic -> complex',
243
+ 'transcendental == complex & !algebraic',
244
+ 'real -> hermitian',
245
+ 'imaginary -> complex',
246
+ 'imaginary -> antihermitian',
247
+ 'extended_real -> commutative',
248
+ 'complex -> commutative',
249
+ 'complex -> finite',
250
+
251
+ 'odd == integer & !even',
252
+ 'even == integer & !odd',
253
+
254
+ 'real -> complex',
255
+ 'extended_real -> real | infinite',
256
+ 'real == extended_real & finite',
257
+
258
+ 'extended_real == extended_negative | zero | extended_positive',
259
+ 'extended_negative == extended_nonpositive & extended_nonzero',
260
+ 'extended_positive == extended_nonnegative & extended_nonzero',
261
+
262
+ 'extended_nonpositive == extended_real & !extended_positive',
263
+ 'extended_nonnegative == extended_real & !extended_negative',
264
+
265
+ 'real == negative | zero | positive',
266
+ 'negative == nonpositive & nonzero',
267
+ 'positive == nonnegative & nonzero',
268
+
269
+ 'nonpositive == real & !positive',
270
+ 'nonnegative == real & !negative',
271
+
272
+ 'positive == extended_positive & finite',
273
+ 'negative == extended_negative & finite',
274
+ 'nonpositive == extended_nonpositive & finite',
275
+ 'nonnegative == extended_nonnegative & finite',
276
+ 'nonzero == extended_nonzero & finite',
277
+
278
+ 'zero -> even & finite',
279
+ 'zero == extended_nonnegative & extended_nonpositive',
280
+ 'zero == nonnegative & nonpositive',
281
+ 'nonzero -> real',
282
+
283
+ 'prime -> integer & positive',
284
+ 'composite -> integer & positive & !prime',
285
+ '!composite -> !positive | !even | prime',
286
+
287
+ 'irrational == real & !rational',
288
+
289
+ 'imaginary -> !extended_real',
290
+
291
+ 'infinite == !finite',
292
+ 'noninteger == extended_real & !integer',
293
+ 'extended_nonzero == extended_real & !zero',
294
+ ])
295
+ return _assume_rules
296
+
297
+
298
+ _assume_rules = _load_pre_generated_assumption_rules()
299
+ _assume_defined = _assume_rules.defined_facts.copy()
300
+ _assume_defined.add('polar')
301
+ _assume_defined = frozenset(_assume_defined)
302
+
303
+
304
+ def assumptions(expr, _check=None):
305
+ """return the T/F assumptions of ``expr``"""
306
+ n = sympify(expr)
307
+ if n.is_Symbol:
308
+ rv = n.assumptions0 # are any important ones missing?
309
+ if _check is not None:
310
+ rv = {k: rv[k] for k in set(rv) & set(_check)}
311
+ return rv
312
+ rv = {}
313
+ for k in _assume_defined if _check is None else _check:
314
+ v = getattr(n, 'is_{}'.format(k))
315
+ if v is not None:
316
+ rv[k] = v
317
+ return rv
318
+
319
+
320
+ def common_assumptions(exprs, check=None):
321
+ """return those assumptions which have the same True or False
322
+ value for all the given expressions.
323
+
324
+ Examples
325
+ ========
326
+
327
+ >>> from sympy.core import common_assumptions
328
+ >>> from sympy import oo, pi, sqrt
329
+ >>> common_assumptions([-4, 0, sqrt(2), 2, pi, oo])
330
+ {'commutative': True, 'composite': False,
331
+ 'extended_real': True, 'imaginary': False, 'odd': False}
332
+
333
+ By default, all assumptions are tested; pass an iterable of the
334
+ assumptions to limit those that are reported:
335
+
336
+ >>> common_assumptions([0, 1, 2], ['positive', 'integer'])
337
+ {'integer': True}
338
+ """
339
+ check = _assume_defined if check is None else set(check)
340
+ if not check or not exprs:
341
+ return {}
342
+
343
+ # get all assumptions for each
344
+ assume = [assumptions(i, _check=check) for i in sympify(exprs)]
345
+ # focus on those of interest that are True
346
+ for i, e in enumerate(assume):
347
+ assume[i] = {k: e[k] for k in set(e) & check}
348
+ # what assumptions are in common?
349
+ common = set.intersection(*[set(i) for i in assume])
350
+ # which ones hold the same value
351
+ a = assume[0]
352
+ return {k: a[k] for k in common if all(a[k] == b[k]
353
+ for b in assume)}
354
+
355
+
356
+ def failing_assumptions(expr, **assumptions):
357
+ """
358
+ Return a dictionary containing assumptions with values not
359
+ matching those of the passed assumptions.
360
+
361
+ Examples
362
+ ========
363
+
364
+ >>> from sympy import failing_assumptions, Symbol
365
+
366
+ >>> x = Symbol('x', positive=True)
367
+ >>> y = Symbol('y')
368
+ >>> failing_assumptions(6*x + y, positive=True)
369
+ {'positive': None}
370
+
371
+ >>> failing_assumptions(x**2 - 1, positive=True)
372
+ {'positive': None}
373
+
374
+ If *expr* satisfies all of the assumptions, an empty dictionary is returned.
375
+
376
+ >>> failing_assumptions(x**2, positive=True)
377
+ {}
378
+
379
+ """
380
+ expr = sympify(expr)
381
+ failed = {}
382
+ for k in assumptions:
383
+ test = getattr(expr, 'is_%s' % k, None)
384
+ if test is not assumptions[k]:
385
+ failed[k] = test
386
+ return failed # {} or {assumption: value != desired}
387
+
388
+
389
+ def check_assumptions(expr, against=None, **assume):
390
+ """
391
+ Checks whether assumptions of ``expr`` match the T/F assumptions
392
+ given (or possessed by ``against``). True is returned if all
393
+ assumptions match; False is returned if there is a mismatch and
394
+ the assumption in ``expr`` is not None; else None is returned.
395
+
396
+ Explanation
397
+ ===========
398
+
399
+ *assume* is a dict of assumptions with True or False values
400
+
401
+ Examples
402
+ ========
403
+
404
+ >>> from sympy import Symbol, pi, I, exp, check_assumptions
405
+ >>> check_assumptions(-5, integer=True)
406
+ True
407
+ >>> check_assumptions(pi, real=True, integer=False)
408
+ True
409
+ >>> check_assumptions(pi, negative=True)
410
+ False
411
+ >>> check_assumptions(exp(I*pi/7), real=False)
412
+ True
413
+ >>> x = Symbol('x', positive=True)
414
+ >>> check_assumptions(2*x + 1, positive=True)
415
+ True
416
+ >>> check_assumptions(-2*x - 5, positive=True)
417
+ False
418
+
419
+ To check assumptions of *expr* against another variable or expression,
420
+ pass the expression or variable as ``against``.
421
+
422
+ >>> check_assumptions(2*x + 1, x)
423
+ True
424
+
425
+ To see if a number matches the assumptions of an expression, pass
426
+ the number as the first argument, else its specific assumptions
427
+ may not have a non-None value in the expression:
428
+
429
+ >>> check_assumptions(x, 3)
430
+ >>> check_assumptions(3, x)
431
+ True
432
+
433
+ ``None`` is returned if ``check_assumptions()`` could not conclude.
434
+
435
+ >>> check_assumptions(2*x - 1, x)
436
+
437
+ >>> z = Symbol('z')
438
+ >>> check_assumptions(z, real=True)
439
+
440
+ See Also
441
+ ========
442
+
443
+ failing_assumptions
444
+
445
+ """
446
+ expr = sympify(expr)
447
+ if against is not None:
448
+ if assume:
449
+ raise ValueError(
450
+ 'Expecting `against` or `assume`, not both.')
451
+ assume = assumptions(against)
452
+ known = True
453
+ for k, v in assume.items():
454
+ if v is None:
455
+ continue
456
+ e = getattr(expr, 'is_' + k, None)
457
+ if e is None:
458
+ known = None
459
+ elif v != e:
460
+ return False
461
+ return known
462
+
463
+
464
+ class StdFactKB(FactKB):
465
+ """A FactKB specialized for the built-in rules
466
+
467
+ This is the only kind of FactKB that Basic objects should use.
468
+ """
469
+ def __init__(self, facts=None):
470
+ super().__init__(_assume_rules)
471
+ # save a copy of the facts dict
472
+ if not facts:
473
+ self._generator = {}
474
+ elif not isinstance(facts, FactKB):
475
+ self._generator = facts.copy()
476
+ else:
477
+ self._generator = facts.generator
478
+ if facts:
479
+ self.deduce_all_facts(facts)
480
+
481
+ def copy(self):
482
+ return self.__class__(self)
483
+
484
+ @property
485
+ def generator(self):
486
+ return self._generator.copy()
487
+
488
+
489
+ def as_property(fact):
490
+ """Convert a fact name to the name of the corresponding property"""
491
+ return 'is_%s' % fact
492
+
493
+
494
+ def make_property(fact):
495
+ """Create the automagic property corresponding to a fact."""
496
+
497
+ def getit(self):
498
+ try:
499
+ return self._assumptions[fact]
500
+ except KeyError:
501
+ if self._assumptions is self.default_assumptions:
502
+ self._assumptions = self.default_assumptions.copy()
503
+ return _ask(fact, self)
504
+
505
+ getit.func_name = as_property(fact)
506
+ return property(getit)
507
+
508
+
509
+ def _ask(fact, obj):
510
+ """
511
+ Find the truth value for a property of an object.
512
+
513
+ This function is called when a request is made to see what a fact
514
+ value is.
515
+
516
+ For this we use several techniques:
517
+
518
+ First, the fact-evaluation function is tried, if it exists (for
519
+ example _eval_is_integer). Then we try related facts. For example
520
+
521
+ rational --> integer
522
+
523
+ another example is joined rule:
524
+
525
+ integer & !odd --> even
526
+
527
+ so in the latter case if we are looking at what 'even' value is,
528
+ 'integer' and 'odd' facts will be asked.
529
+
530
+ In all cases, when we settle on some fact value, its implications are
531
+ deduced, and the result is cached in ._assumptions.
532
+ """
533
+ # FactKB which is dict-like and maps facts to their known values:
534
+ assumptions = obj._assumptions
535
+
536
+ # A dict that maps facts to their handlers:
537
+ handler_map = obj._prop_handler
538
+
539
+ # This is our queue of facts to check:
540
+ facts_to_check = [fact]
541
+ facts_queued = {fact}
542
+
543
+ # Loop over the queue as it extends
544
+ for fact_i in facts_to_check:
545
+
546
+ # If fact_i has already been determined then we don't need to rerun the
547
+ # handler. There is a potential race condition for multithreaded code
548
+ # though because it's possible that fact_i was checked in another
549
+ # thread. The main logic of the loop below would potentially skip
550
+ # checking assumptions[fact] in this case so we check it once after the
551
+ # loop to be sure.
552
+ if fact_i in assumptions:
553
+ continue
554
+
555
+ # Now we call the associated handler for fact_i if it exists.
556
+ fact_i_value = None
557
+ handler_i = handler_map.get(fact_i)
558
+ if handler_i is not None:
559
+ fact_i_value = handler_i(obj)
560
+
561
+ # If we get a new value for fact_i then we should update our knowledge
562
+ # of fact_i as well as any related facts that can be inferred using the
563
+ # inference rules connecting the fact_i and any other fact values that
564
+ # are already known.
565
+ if fact_i_value is not None:
566
+ assumptions.deduce_all_facts(((fact_i, fact_i_value),))
567
+
568
+ # Usually if assumptions[fact] is now not None then that is because of
569
+ # the call to deduce_all_facts above. The handler for fact_i returned
570
+ # True or False and knowing fact_i (which is equal to fact in the first
571
+ # iteration) implies knowing a value for fact. It is also possible
572
+ # though that independent code e.g. called indirectly by the handler or
573
+ # called in another thread in a multithreaded context might have
574
+ # resulted in assumptions[fact] being set. Either way we return it.
575
+ fact_value = assumptions.get(fact)
576
+ if fact_value is not None:
577
+ return fact_value
578
+
579
+ # Extend the queue with other facts that might determine fact_i. Here
580
+ # we randomise the order of the facts that are checked. This should not
581
+ # lead to any non-determinism if all handlers are logically consistent
582
+ # with the inference rules for the facts. Non-deterministic assumptions
583
+ # queries can result from bugs in the handlers that are exposed by this
584
+ # call to shuffle. These are pushed to the back of the queue meaning
585
+ # that the inference graph is traversed in breadth-first order.
586
+ new_facts_to_check = list(_assume_rules.prereq[fact_i] - facts_queued)
587
+ shuffle(new_facts_to_check)
588
+ facts_to_check.extend(new_facts_to_check)
589
+ facts_queued.update(new_facts_to_check)
590
+
591
+ # The above loop should be able to handle everything fine in a
592
+ # single-threaded context but in multithreaded code it is possible that
593
+ # this thread skipped computing a particular fact that was computed in
594
+ # another thread (due to the continue). In that case it is possible that
595
+ # fact was inferred and is now stored in the assumptions dict but it wasn't
596
+ # checked for in the body of the loop. This is an obscure case but to make
597
+ # sure we catch it we check once here at the end of the loop.
598
+ if fact in assumptions:
599
+ return assumptions[fact]
600
+
601
+ # This query can not be answered. It's possible that e.g. another thread
602
+ # has already stored None for fact but assumptions._tell does not mind if
603
+ # we call _tell twice setting the same value. If this raises
604
+ # InconsistentAssumptions then it probably means that another thread
605
+ # attempted to compute this and got a value of True or False rather than
606
+ # None. In that case there must be a bug in at least one of the handlers.
607
+ # If the handlers are all deterministic and are consistent with the
608
+ # inference rules then the same value should be computed for fact in all
609
+ # threads.
610
+ assumptions._tell(fact, None)
611
+ return None
612
+
613
+
614
+ def _prepare_class_assumptions(cls):
615
+ """Precompute class level assumptions and generate handlers.
616
+
617
+ This is called by Basic.__init_subclass__ each time a Basic subclass is
618
+ defined.
619
+ """
620
+
621
+ local_defs = {}
622
+ for k in _assume_defined:
623
+ attrname = as_property(k)
624
+ v = cls.__dict__.get(attrname, '')
625
+ if isinstance(v, (bool, int, type(None))):
626
+ if v is not None:
627
+ v = bool(v)
628
+ local_defs[k] = v
629
+
630
+ defs = {}
631
+ for base in reversed(cls.__bases__):
632
+ assumptions = getattr(base, '_explicit_class_assumptions', None)
633
+ if assumptions is not None:
634
+ defs.update(assumptions)
635
+ defs.update(local_defs)
636
+
637
+ cls._explicit_class_assumptions = defs
638
+ cls.default_assumptions = StdFactKB(defs)
639
+
640
+ cls._prop_handler = {}
641
+ for k in _assume_defined:
642
+ eval_is_meth = getattr(cls, '_eval_is_%s' % k, None)
643
+ if eval_is_meth is not None:
644
+ cls._prop_handler[k] = eval_is_meth
645
+
646
+ # Put definite results directly into the class dict, for speed
647
+ for k, v in cls.default_assumptions.items():
648
+ setattr(cls, as_property(k), v)
649
+
650
+ # protection e.g. for Integer.is_even=F <- (Rational.is_integer=F)
651
+ derived_from_bases = set()
652
+ for base in cls.__bases__:
653
+ default_assumptions = getattr(base, 'default_assumptions', None)
654
+ # is an assumption-aware class
655
+ if default_assumptions is not None:
656
+ derived_from_bases.update(default_assumptions)
657
+
658
+ for fact in derived_from_bases - set(cls.default_assumptions):
659
+ pname = as_property(fact)
660
+ if pname not in cls.__dict__:
661
+ setattr(cls, pname, make_property(fact))
662
+
663
+ # Finally, add any missing automagic property (e.g. for Basic)
664
+ for fact in _assume_defined:
665
+ pname = as_property(fact)
666
+ if not hasattr(cls, pname):
667
+ setattr(cls, pname, make_property(fact))
668
+
669
+
670
+ # XXX: ManagedProperties used to be the metaclass for Basic but now Basic does
671
+ # not use a metaclass. We leave this here for backwards compatibility for now
672
+ # in case someone has been using the ManagedProperties class in downstream
673
+ # code. The reason that it might have been used is that when subclassing a
674
+ # class and wanting to use a metaclass the metaclass must be a subclass of the
675
+ # metaclass for the class that is being subclassed. Anyone wanting to subclass
676
+ # Basic and use a metaclass in their subclass would have needed to subclass
677
+ # ManagedProperties. Here ManagedProperties is not the metaclass for Basic any
678
+ # more but it should still be usable as a metaclass for Basic subclasses since
679
+ # it is a subclass of type which is now the metaclass for Basic.
680
+ class ManagedProperties(type):
681
+ def __init__(cls, *args, **kwargs):
682
+ msg = ("The ManagedProperties metaclass. "
683
+ "Basic does not use metaclasses any more")
684
+ sympy_deprecation_warning(msg,
685
+ deprecated_since_version="1.12",
686
+ active_deprecations_target='managedproperties')
687
+
688
+ # Here we still call this function in case someone is using
689
+ # ManagedProperties for something that is not a Basic subclass. For
690
+ # Basic subclasses this function is now called by __init_subclass__ and
691
+ # so this metaclass is not needed any more.
692
+ _prepare_class_assumptions(cls)
env-llmeval/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
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/core/basic.py ADDED
@@ -0,0 +1,2233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for all the objects in SymPy"""
2
+ from __future__ import annotations
3
+
4
+ from collections import defaultdict
5
+ from collections.abc import Mapping
6
+ from itertools import chain, zip_longest
7
+
8
+ from .assumptions import _prepare_class_assumptions
9
+ from .cache import cacheit
10
+ from .core import ordering_of_classes
11
+ from .sympify import _sympify, sympify, SympifyError, _external_converter
12
+ from .sorting import ordered
13
+ from .kind import Kind, UndefinedKind
14
+ from ._print_helpers import Printable
15
+
16
+ from sympy.utilities.decorator import deprecated
17
+ from sympy.utilities.exceptions import sympy_deprecation_warning
18
+ from sympy.utilities.iterables import iterable, numbered_symbols
19
+ from sympy.utilities.misc import filldedent, func_name
20
+
21
+ from inspect import getmro
22
+
23
+
24
+ def as_Basic(expr):
25
+ """Return expr as a Basic instance using strict sympify
26
+ or raise a TypeError; this is just a wrapper to _sympify,
27
+ raising a TypeError instead of a SympifyError."""
28
+ try:
29
+ return _sympify(expr)
30
+ except SympifyError:
31
+ raise TypeError(
32
+ 'Argument must be a Basic object, not `%s`' % func_name(
33
+ expr))
34
+
35
+
36
+ def _old_compare(x: type, y: type) -> int:
37
+ # If the other object is not a Basic subclass, then we are not equal to it.
38
+ if not issubclass(y, Basic):
39
+ return -1
40
+
41
+ n1 = x.__name__
42
+ n2 = y.__name__
43
+ if n1 == n2:
44
+ return 0
45
+
46
+ UNKNOWN = len(ordering_of_classes) + 1
47
+ try:
48
+ i1 = ordering_of_classes.index(n1)
49
+ except ValueError:
50
+ i1 = UNKNOWN
51
+ try:
52
+ i2 = ordering_of_classes.index(n2)
53
+ except ValueError:
54
+ i2 = UNKNOWN
55
+ if i1 == UNKNOWN and i2 == UNKNOWN:
56
+ return (n1 > n2) - (n1 < n2)
57
+ return (i1 > i2) - (i1 < i2)
58
+
59
+
60
+ class Basic(Printable):
61
+ """
62
+ Base class for all SymPy objects.
63
+
64
+ Notes and conventions
65
+ =====================
66
+
67
+ 1) Always use ``.args``, when accessing parameters of some instance:
68
+
69
+ >>> from sympy import cot
70
+ >>> from sympy.abc import x, y
71
+
72
+ >>> cot(x).args
73
+ (x,)
74
+
75
+ >>> cot(x).args[0]
76
+ x
77
+
78
+ >>> (x*y).args
79
+ (x, y)
80
+
81
+ >>> (x*y).args[1]
82
+ y
83
+
84
+
85
+ 2) Never use internal methods or variables (the ones prefixed with ``_``):
86
+
87
+ >>> cot(x)._args # do not use this, use cot(x).args instead
88
+ (x,)
89
+
90
+
91
+ 3) By "SymPy object" we mean something that can be returned by
92
+ ``sympify``. But not all objects one encounters using SymPy are
93
+ subclasses of Basic. For example, mutable objects are not:
94
+
95
+ >>> from sympy import Basic, Matrix, sympify
96
+ >>> A = Matrix([[1, 2], [3, 4]]).as_mutable()
97
+ >>> isinstance(A, Basic)
98
+ False
99
+
100
+ >>> B = sympify(A)
101
+ >>> isinstance(B, Basic)
102
+ True
103
+ """
104
+ __slots__ = ('_mhash', # hash value
105
+ '_args', # arguments
106
+ '_assumptions'
107
+ )
108
+
109
+ _args: tuple[Basic, ...]
110
+ _mhash: int | None
111
+
112
+ @property
113
+ def __sympy__(self):
114
+ return True
115
+
116
+ def __init_subclass__(cls):
117
+ # Initialize the default_assumptions FactKB and also any assumptions
118
+ # property methods. This method will only be called for subclasses of
119
+ # Basic but not for Basic itself so we call
120
+ # _prepare_class_assumptions(Basic) below the class definition.
121
+ _prepare_class_assumptions(cls)
122
+
123
+ # To be overridden with True in the appropriate subclasses
124
+ is_number = False
125
+ is_Atom = False
126
+ is_Symbol = False
127
+ is_symbol = False
128
+ is_Indexed = False
129
+ is_Dummy = False
130
+ is_Wild = False
131
+ is_Function = False
132
+ is_Add = False
133
+ is_Mul = False
134
+ is_Pow = False
135
+ is_Number = False
136
+ is_Float = False
137
+ is_Rational = False
138
+ is_Integer = False
139
+ is_NumberSymbol = False
140
+ is_Order = False
141
+ is_Derivative = False
142
+ is_Piecewise = False
143
+ is_Poly = False
144
+ is_AlgebraicNumber = False
145
+ is_Relational = False
146
+ is_Equality = False
147
+ is_Boolean = False
148
+ is_Not = False
149
+ is_Matrix = False
150
+ is_Vector = False
151
+ is_Point = False
152
+ is_MatAdd = False
153
+ is_MatMul = False
154
+ is_real: bool | None
155
+ is_extended_real: bool | None
156
+ is_zero: bool | None
157
+ is_negative: bool | None
158
+ is_commutative: bool | None
159
+
160
+ kind: Kind = UndefinedKind
161
+
162
+ def __new__(cls, *args):
163
+ obj = object.__new__(cls)
164
+ obj._assumptions = cls.default_assumptions
165
+ obj._mhash = None # will be set by __hash__ method.
166
+
167
+ obj._args = args # all items in args must be Basic objects
168
+ return obj
169
+
170
+ def copy(self):
171
+ return self.func(*self.args)
172
+
173
+ def __getnewargs__(self):
174
+ return self.args
175
+
176
+ def __getstate__(self):
177
+ return None
178
+
179
+ def __setstate__(self, state):
180
+ for name, value in state.items():
181
+ setattr(self, name, value)
182
+
183
+ def __reduce_ex__(self, protocol):
184
+ if protocol < 2:
185
+ msg = "Only pickle protocol 2 or higher is supported by SymPy"
186
+ raise NotImplementedError(msg)
187
+ return super().__reduce_ex__(protocol)
188
+
189
+ def __hash__(self) -> int:
190
+ # hash cannot be cached using cache_it because infinite recurrence
191
+ # occurs as hash is needed for setting cache dictionary keys
192
+ h = self._mhash
193
+ if h is None:
194
+ h = hash((type(self).__name__,) + self._hashable_content())
195
+ self._mhash = h
196
+ return h
197
+
198
+ def _hashable_content(self):
199
+ """Return a tuple of information about self that can be used to
200
+ compute the hash. If a class defines additional attributes,
201
+ like ``name`` in Symbol, then this method should be updated
202
+ accordingly to return such relevant attributes.
203
+
204
+ Defining more than _hashable_content is necessary if __eq__ has
205
+ been defined by a class. See note about this in Basic.__eq__."""
206
+ return self._args
207
+
208
+ @property
209
+ def assumptions0(self):
210
+ """
211
+ Return object `type` assumptions.
212
+
213
+ For example:
214
+
215
+ Symbol('x', real=True)
216
+ Symbol('x', integer=True)
217
+
218
+ are different objects. In other words, besides Python type (Symbol in
219
+ this case), the initial assumptions are also forming their typeinfo.
220
+
221
+ Examples
222
+ ========
223
+
224
+ >>> from sympy import Symbol
225
+ >>> from sympy.abc import x
226
+ >>> x.assumptions0
227
+ {'commutative': True}
228
+ >>> x = Symbol("x", positive=True)
229
+ >>> x.assumptions0
230
+ {'commutative': True, 'complex': True, 'extended_negative': False,
231
+ 'extended_nonnegative': True, 'extended_nonpositive': False,
232
+ 'extended_nonzero': True, 'extended_positive': True, 'extended_real':
233
+ True, 'finite': True, 'hermitian': True, 'imaginary': False,
234
+ 'infinite': False, 'negative': False, 'nonnegative': True,
235
+ 'nonpositive': False, 'nonzero': True, 'positive': True, 'real':
236
+ True, 'zero': False}
237
+ """
238
+ return {}
239
+
240
+ def compare(self, other):
241
+ """
242
+ Return -1, 0, 1 if the object is smaller, equal, or greater than other.
243
+
244
+ Not in the mathematical sense. If the object is of a different type
245
+ from the "other" then their classes are ordered according to
246
+ the sorted_classes list.
247
+
248
+ Examples
249
+ ========
250
+
251
+ >>> from sympy.abc import x, y
252
+ >>> x.compare(y)
253
+ -1
254
+ >>> x.compare(x)
255
+ 0
256
+ >>> y.compare(x)
257
+ 1
258
+
259
+ """
260
+ # all redefinitions of __cmp__ method should start with the
261
+ # following lines:
262
+ if self is other:
263
+ return 0
264
+ n1 = self.__class__
265
+ n2 = other.__class__
266
+ c = _old_compare(n1, n2)
267
+ if c:
268
+ return c
269
+ #
270
+ st = self._hashable_content()
271
+ ot = other._hashable_content()
272
+ c = (len(st) > len(ot)) - (len(st) < len(ot))
273
+ if c:
274
+ return c
275
+ for l, r in zip(st, ot):
276
+ l = Basic(*l) if isinstance(l, frozenset) else l
277
+ r = Basic(*r) if isinstance(r, frozenset) else r
278
+ if isinstance(l, Basic):
279
+ c = l.compare(r)
280
+ else:
281
+ c = (l > r) - (l < r)
282
+ if c:
283
+ return c
284
+ return 0
285
+
286
+ @staticmethod
287
+ def _compare_pretty(a, b):
288
+ from sympy.series.order import Order
289
+ if isinstance(a, Order) and not isinstance(b, Order):
290
+ return 1
291
+ if not isinstance(a, Order) and isinstance(b, Order):
292
+ return -1
293
+
294
+ if a.is_Rational and b.is_Rational:
295
+ l = a.p * b.q
296
+ r = b.p * a.q
297
+ return (l > r) - (l < r)
298
+ else:
299
+ from .symbol import Wild
300
+ p1, p2, p3 = Wild("p1"), Wild("p2"), Wild("p3")
301
+ r_a = a.match(p1 * p2**p3)
302
+ if r_a and p3 in r_a:
303
+ a3 = r_a[p3]
304
+ r_b = b.match(p1 * p2**p3)
305
+ if r_b and p3 in r_b:
306
+ b3 = r_b[p3]
307
+ c = Basic.compare(a3, b3)
308
+ if c != 0:
309
+ return c
310
+
311
+ return Basic.compare(a, b)
312
+
313
+ @classmethod
314
+ def fromiter(cls, args, **assumptions):
315
+ """
316
+ Create a new object from an iterable.
317
+
318
+ This is a convenience function that allows one to create objects from
319
+ any iterable, without having to convert to a list or tuple first.
320
+
321
+ Examples
322
+ ========
323
+
324
+ >>> from sympy import Tuple
325
+ >>> Tuple.fromiter(i for i in range(5))
326
+ (0, 1, 2, 3, 4)
327
+
328
+ """
329
+ return cls(*tuple(args), **assumptions)
330
+
331
+ @classmethod
332
+ def class_key(cls):
333
+ """Nice order of classes."""
334
+ return 5, 0, cls.__name__
335
+
336
+ @cacheit
337
+ def sort_key(self, order=None):
338
+ """
339
+ Return a sort key.
340
+
341
+ Examples
342
+ ========
343
+
344
+ >>> from sympy import S, I
345
+
346
+ >>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
347
+ [1/2, -I, I]
348
+
349
+ >>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
350
+ [x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
351
+ >>> sorted(_, key=lambda x: x.sort_key())
352
+ [x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
353
+
354
+ """
355
+
356
+ # XXX: remove this when issue 5169 is fixed
357
+ def inner_key(arg):
358
+ if isinstance(arg, Basic):
359
+ return arg.sort_key(order)
360
+ else:
361
+ return arg
362
+
363
+ args = self._sorted_args
364
+ args = len(args), tuple([inner_key(arg) for arg in args])
365
+ return self.class_key(), args, S.One.sort_key(), S.One
366
+
367
+ def _do_eq_sympify(self, other):
368
+ """Returns a boolean indicating whether a == b when either a
369
+ or b is not a Basic. This is only done for types that were either
370
+ added to `converter` by a 3rd party or when the object has `_sympy_`
371
+ defined. This essentially reuses the code in `_sympify` that is
372
+ specific for this use case. Non-user defined types that are meant
373
+ to work with SymPy should be handled directly in the __eq__ methods
374
+ of the `Basic` classes it could equate to and not be converted. Note
375
+ that after conversion, `==` is used again since it is not
376
+ necessarily clear whether `self` or `other`'s __eq__ method needs
377
+ to be used."""
378
+ for superclass in type(other).__mro__:
379
+ conv = _external_converter.get(superclass)
380
+ if conv is not None:
381
+ return self == conv(other)
382
+ if hasattr(other, '_sympy_'):
383
+ return self == other._sympy_()
384
+ return NotImplemented
385
+
386
+ def __eq__(self, other):
387
+ """Return a boolean indicating whether a == b on the basis of
388
+ their symbolic trees.
389
+
390
+ This is the same as a.compare(b) == 0 but faster.
391
+
392
+ Notes
393
+ =====
394
+
395
+ If a class that overrides __eq__() needs to retain the
396
+ implementation of __hash__() from a parent class, the
397
+ interpreter must be told this explicitly by setting
398
+ __hash__ : Callable[[object], int] = <ParentClass>.__hash__.
399
+ Otherwise the inheritance of __hash__() will be blocked,
400
+ just as if __hash__ had been explicitly set to None.
401
+
402
+ References
403
+ ==========
404
+
405
+ from https://docs.python.org/dev/reference/datamodel.html#object.__hash__
406
+ """
407
+ if self is other:
408
+ return True
409
+
410
+ if not isinstance(other, Basic):
411
+ return self._do_eq_sympify(other)
412
+
413
+ # check for pure number expr
414
+ if not (self.is_Number and other.is_Number) and (
415
+ type(self) != type(other)):
416
+ return False
417
+ a, b = self._hashable_content(), other._hashable_content()
418
+ if a != b:
419
+ return False
420
+ # check number *in* an expression
421
+ for a, b in zip(a, b):
422
+ if not isinstance(a, Basic):
423
+ continue
424
+ if a.is_Number and type(a) != type(b):
425
+ return False
426
+ return True
427
+
428
+ def __ne__(self, other):
429
+ """``a != b`` -> Compare two symbolic trees and see whether they are different
430
+
431
+ this is the same as:
432
+
433
+ ``a.compare(b) != 0``
434
+
435
+ but faster
436
+ """
437
+ return not self == other
438
+
439
+ def dummy_eq(self, other, symbol=None):
440
+ """
441
+ Compare two expressions and handle dummy symbols.
442
+
443
+ Examples
444
+ ========
445
+
446
+ >>> from sympy import Dummy
447
+ >>> from sympy.abc import x, y
448
+
449
+ >>> u = Dummy('u')
450
+
451
+ >>> (u**2 + 1).dummy_eq(x**2 + 1)
452
+ True
453
+ >>> (u**2 + 1) == (x**2 + 1)
454
+ False
455
+
456
+ >>> (u**2 + y).dummy_eq(x**2 + y, x)
457
+ True
458
+ >>> (u**2 + y).dummy_eq(x**2 + y, y)
459
+ False
460
+
461
+ """
462
+ s = self.as_dummy()
463
+ o = _sympify(other)
464
+ o = o.as_dummy()
465
+
466
+ dummy_symbols = [i for i in s.free_symbols if i.is_Dummy]
467
+
468
+ if len(dummy_symbols) == 1:
469
+ dummy = dummy_symbols.pop()
470
+ else:
471
+ return s == o
472
+
473
+ if symbol is None:
474
+ symbols = o.free_symbols
475
+
476
+ if len(symbols) == 1:
477
+ symbol = symbols.pop()
478
+ else:
479
+ return s == o
480
+
481
+ tmp = dummy.__class__()
482
+
483
+ return s.xreplace({dummy: tmp}) == o.xreplace({symbol: tmp})
484
+
485
+ def atoms(self, *types):
486
+ """Returns the atoms that form the current object.
487
+
488
+ By default, only objects that are truly atomic and cannot
489
+ be divided into smaller pieces are returned: symbols, numbers,
490
+ and number symbols like I and pi. It is possible to request
491
+ atoms of any type, however, as demonstrated below.
492
+
493
+ Examples
494
+ ========
495
+
496
+ >>> from sympy import I, pi, sin
497
+ >>> from sympy.abc import x, y
498
+ >>> (1 + x + 2*sin(y + I*pi)).atoms()
499
+ {1, 2, I, pi, x, y}
500
+
501
+ If one or more types are given, the results will contain only
502
+ those types of atoms.
503
+
504
+ >>> from sympy import Number, NumberSymbol, Symbol
505
+ >>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol)
506
+ {x, y}
507
+
508
+ >>> (1 + x + 2*sin(y + I*pi)).atoms(Number)
509
+ {1, 2}
510
+
511
+ >>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol)
512
+ {1, 2, pi}
513
+
514
+ >>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I)
515
+ {1, 2, I, pi}
516
+
517
+ Note that I (imaginary unit) and zoo (complex infinity) are special
518
+ types of number symbols and are not part of the NumberSymbol class.
519
+
520
+ The type can be given implicitly, too:
521
+
522
+ >>> (1 + x + 2*sin(y + I*pi)).atoms(x) # x is a Symbol
523
+ {x, y}
524
+
525
+ Be careful to check your assumptions when using the implicit option
526
+ since ``S(1).is_Integer = True`` but ``type(S(1))`` is ``One``, a special type
527
+ of SymPy atom, while ``type(S(2))`` is type ``Integer`` and will find all
528
+ integers in an expression:
529
+
530
+ >>> from sympy import S
531
+ >>> (1 + x + 2*sin(y + I*pi)).atoms(S(1))
532
+ {1}
533
+
534
+ >>> (1 + x + 2*sin(y + I*pi)).atoms(S(2))
535
+ {1, 2}
536
+
537
+ Finally, arguments to atoms() can select more than atomic atoms: any
538
+ SymPy type (loaded in core/__init__.py) can be listed as an argument
539
+ and those types of "atoms" as found in scanning the arguments of the
540
+ expression recursively:
541
+
542
+ >>> from sympy import Function, Mul
543
+ >>> from sympy.core.function import AppliedUndef
544
+ >>> f = Function('f')
545
+ >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(Function)
546
+ {f(x), sin(y + I*pi)}
547
+ >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef)
548
+ {f(x)}
549
+
550
+ >>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
551
+ {I*pi, 2*sin(y + I*pi)}
552
+
553
+ """
554
+ if types:
555
+ types = tuple(
556
+ [t if isinstance(t, type) else type(t) for t in types])
557
+ nodes = _preorder_traversal(self)
558
+ if types:
559
+ result = {node for node in nodes if isinstance(node, types)}
560
+ else:
561
+ result = {node for node in nodes if not node.args}
562
+ return result
563
+
564
+ @property
565
+ def free_symbols(self) -> set[Basic]:
566
+ """Return from the atoms of self those which are free symbols.
567
+
568
+ Not all free symbols are ``Symbol``. Eg: IndexedBase('I')[0].free_symbols
569
+
570
+ For most expressions, all symbols are free symbols. For some classes
571
+ this is not true. e.g. Integrals use Symbols for the dummy variables
572
+ which are bound variables, so Integral has a method to return all
573
+ symbols except those. Derivative keeps track of symbols with respect
574
+ to which it will perform a derivative; those are
575
+ bound variables, too, so it has its own free_symbols method.
576
+
577
+ Any other method that uses bound variables should implement a
578
+ free_symbols method."""
579
+ empty: set[Basic] = set()
580
+ return empty.union(*(a.free_symbols for a in self.args))
581
+
582
+ @property
583
+ def expr_free_symbols(self):
584
+ sympy_deprecation_warning("""
585
+ The expr_free_symbols property is deprecated. Use free_symbols to get
586
+ the free symbols of an expression.
587
+ """,
588
+ deprecated_since_version="1.9",
589
+ active_deprecations_target="deprecated-expr-free-symbols")
590
+ return set()
591
+
592
+ def as_dummy(self):
593
+ """Return the expression with any objects having structurally
594
+ bound symbols replaced with unique, canonical symbols within
595
+ the object in which they appear and having only the default
596
+ assumption for commutativity being True. When applied to a
597
+ symbol a new symbol having only the same commutativity will be
598
+ returned.
599
+
600
+ Examples
601
+ ========
602
+
603
+ >>> from sympy import Integral, Symbol
604
+ >>> from sympy.abc import x
605
+ >>> r = Symbol('r', real=True)
606
+ >>> Integral(r, (r, x)).as_dummy()
607
+ Integral(_0, (_0, x))
608
+ >>> _.variables[0].is_real is None
609
+ True
610
+ >>> r.as_dummy()
611
+ _r
612
+
613
+ Notes
614
+ =====
615
+
616
+ Any object that has structurally bound variables should have
617
+ a property, `bound_symbols` that returns those symbols
618
+ appearing in the object.
619
+ """
620
+ from .symbol import Dummy, Symbol
621
+ def can(x):
622
+ # mask free that shadow bound
623
+ free = x.free_symbols
624
+ bound = set(x.bound_symbols)
625
+ d = {i: Dummy() for i in bound & free}
626
+ x = x.subs(d)
627
+ # replace bound with canonical names
628
+ x = x.xreplace(x.canonical_variables)
629
+ # return after undoing masking
630
+ return x.xreplace({v: k for k, v in d.items()})
631
+ if not self.has(Symbol):
632
+ return self
633
+ return self.replace(
634
+ lambda x: hasattr(x, 'bound_symbols'),
635
+ can,
636
+ simultaneous=False)
637
+
638
+ @property
639
+ def canonical_variables(self):
640
+ """Return a dictionary mapping any variable defined in
641
+ ``self.bound_symbols`` to Symbols that do not clash
642
+ with any free symbols in the expression.
643
+
644
+ Examples
645
+ ========
646
+
647
+ >>> from sympy import Lambda
648
+ >>> from sympy.abc import x
649
+ >>> Lambda(x, 2*x).canonical_variables
650
+ {x: _0}
651
+ """
652
+ if not hasattr(self, 'bound_symbols'):
653
+ return {}
654
+ dums = numbered_symbols('_')
655
+ reps = {}
656
+ # watch out for free symbol that are not in bound symbols;
657
+ # those that are in bound symbols are about to get changed
658
+ bound = self.bound_symbols
659
+ names = {i.name for i in self.free_symbols - set(bound)}
660
+ for b in bound:
661
+ d = next(dums)
662
+ if b.is_Symbol:
663
+ while d.name in names:
664
+ d = next(dums)
665
+ reps[b] = d
666
+ return reps
667
+
668
+ def rcall(self, *args):
669
+ """Apply on the argument recursively through the expression tree.
670
+
671
+ This method is used to simulate a common abuse of notation for
672
+ operators. For instance, in SymPy the following will not work:
673
+
674
+ ``(x+Lambda(y, 2*y))(z) == x+2*z``,
675
+
676
+ however, you can use:
677
+
678
+ >>> from sympy import Lambda
679
+ >>> from sympy.abc import x, y, z
680
+ >>> (x + Lambda(y, 2*y)).rcall(z)
681
+ x + 2*z
682
+ """
683
+ return Basic._recursive_call(self, args)
684
+
685
+ @staticmethod
686
+ def _recursive_call(expr_to_call, on_args):
687
+ """Helper for rcall method."""
688
+ from .symbol import Symbol
689
+ def the_call_method_is_overridden(expr):
690
+ for cls in getmro(type(expr)):
691
+ if '__call__' in cls.__dict__:
692
+ return cls != Basic
693
+
694
+ if callable(expr_to_call) and the_call_method_is_overridden(expr_to_call):
695
+ if isinstance(expr_to_call, Symbol): # XXX When you call a Symbol it is
696
+ return expr_to_call # transformed into an UndefFunction
697
+ else:
698
+ return expr_to_call(*on_args)
699
+ elif expr_to_call.args:
700
+ args = [Basic._recursive_call(
701
+ sub, on_args) for sub in expr_to_call.args]
702
+ return type(expr_to_call)(*args)
703
+ else:
704
+ return expr_to_call
705
+
706
+ def is_hypergeometric(self, k):
707
+ from sympy.simplify.simplify import hypersimp
708
+ from sympy.functions.elementary.piecewise import Piecewise
709
+ if self.has(Piecewise):
710
+ return None
711
+ return hypersimp(self, k) is not None
712
+
713
+ @property
714
+ def is_comparable(self):
715
+ """Return True if self can be computed to a real number
716
+ (or already is a real number) with precision, else False.
717
+
718
+ Examples
719
+ ========
720
+
721
+ >>> from sympy import exp_polar, pi, I
722
+ >>> (I*exp_polar(I*pi/2)).is_comparable
723
+ True
724
+ >>> (I*exp_polar(I*pi*2)).is_comparable
725
+ False
726
+
727
+ A False result does not mean that `self` cannot be rewritten
728
+ into a form that would be comparable. For example, the
729
+ difference computed below is zero but without simplification
730
+ it does not evaluate to a zero with precision:
731
+
732
+ >>> e = 2**pi*(1 + 2**pi)
733
+ >>> dif = e - e.expand()
734
+ >>> dif.is_comparable
735
+ False
736
+ >>> dif.n(2)._prec
737
+ 1
738
+
739
+ """
740
+ is_extended_real = self.is_extended_real
741
+ if is_extended_real is False:
742
+ return False
743
+ if not self.is_number:
744
+ return False
745
+ # don't re-eval numbers that are already evaluated since
746
+ # this will create spurious precision
747
+ n, i = [p.evalf(2) if not p.is_Number else p
748
+ for p in self.as_real_imag()]
749
+ if not (i.is_Number and n.is_Number):
750
+ return False
751
+ if i:
752
+ # if _prec = 1 we can't decide and if not,
753
+ # the answer is False because numbers with
754
+ # imaginary parts can't be compared
755
+ # so return False
756
+ return False
757
+ else:
758
+ return n._prec != 1
759
+
760
+ @property
761
+ def func(self):
762
+ """
763
+ The top-level function in an expression.
764
+
765
+ The following should hold for all objects::
766
+
767
+ >> x == x.func(*x.args)
768
+
769
+ Examples
770
+ ========
771
+
772
+ >>> from sympy.abc import x
773
+ >>> a = 2*x
774
+ >>> a.func
775
+ <class 'sympy.core.mul.Mul'>
776
+ >>> a.args
777
+ (2, x)
778
+ >>> a.func(*a.args)
779
+ 2*x
780
+ >>> a == a.func(*a.args)
781
+ True
782
+
783
+ """
784
+ return self.__class__
785
+
786
+ @property
787
+ def args(self) -> tuple[Basic, ...]:
788
+ """Returns a tuple of arguments of 'self'.
789
+
790
+ Examples
791
+ ========
792
+
793
+ >>> from sympy import cot
794
+ >>> from sympy.abc import x, y
795
+
796
+ >>> cot(x).args
797
+ (x,)
798
+
799
+ >>> cot(x).args[0]
800
+ x
801
+
802
+ >>> (x*y).args
803
+ (x, y)
804
+
805
+ >>> (x*y).args[1]
806
+ y
807
+
808
+ Notes
809
+ =====
810
+
811
+ Never use self._args, always use self.args.
812
+ Only use _args in __new__ when creating a new function.
813
+ Do not override .args() from Basic (so that it is easy to
814
+ change the interface in the future if needed).
815
+ """
816
+ return self._args
817
+
818
+ @property
819
+ def _sorted_args(self):
820
+ """
821
+ The same as ``args``. Derived classes which do not fix an
822
+ order on their arguments should override this method to
823
+ produce the sorted representation.
824
+ """
825
+ return self.args
826
+
827
+ def as_content_primitive(self, radical=False, clear=True):
828
+ """A stub to allow Basic args (like Tuple) to be skipped when computing
829
+ the content and primitive components of an expression.
830
+
831
+ See Also
832
+ ========
833
+
834
+ sympy.core.expr.Expr.as_content_primitive
835
+ """
836
+ return S.One, self
837
+
838
+ def subs(self, *args, **kwargs):
839
+ """
840
+ Substitutes old for new in an expression after sympifying args.
841
+
842
+ `args` is either:
843
+ - two arguments, e.g. foo.subs(old, new)
844
+ - one iterable argument, e.g. foo.subs(iterable). The iterable may be
845
+ o an iterable container with (old, new) pairs. In this case the
846
+ replacements are processed in the order given with successive
847
+ patterns possibly affecting replacements already made.
848
+ o a dict or set whose key/value items correspond to old/new pairs.
849
+ In this case the old/new pairs will be sorted by op count and in
850
+ case of a tie, by number of args and the default_sort_key. The
851
+ resulting sorted list is then processed as an iterable container
852
+ (see previous).
853
+
854
+ If the keyword ``simultaneous`` is True, the subexpressions will not be
855
+ evaluated until all the substitutions have been made.
856
+
857
+ Examples
858
+ ========
859
+
860
+ >>> from sympy import pi, exp, limit, oo
861
+ >>> from sympy.abc import x, y
862
+ >>> (1 + x*y).subs(x, pi)
863
+ pi*y + 1
864
+ >>> (1 + x*y).subs({x:pi, y:2})
865
+ 1 + 2*pi
866
+ >>> (1 + x*y).subs([(x, pi), (y, 2)])
867
+ 1 + 2*pi
868
+ >>> reps = [(y, x**2), (x, 2)]
869
+ >>> (x + y).subs(reps)
870
+ 6
871
+ >>> (x + y).subs(reversed(reps))
872
+ x**2 + 2
873
+
874
+ >>> (x**2 + x**4).subs(x**2, y)
875
+ y**2 + y
876
+
877
+ To replace only the x**2 but not the x**4, use xreplace:
878
+
879
+ >>> (x**2 + x**4).xreplace({x**2: y})
880
+ x**4 + y
881
+
882
+ To delay evaluation until all substitutions have been made,
883
+ set the keyword ``simultaneous`` to True:
884
+
885
+ >>> (x/y).subs([(x, 0), (y, 0)])
886
+ 0
887
+ >>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True)
888
+ nan
889
+
890
+ This has the added feature of not allowing subsequent substitutions
891
+ to affect those already made:
892
+
893
+ >>> ((x + y)/y).subs({x + y: y, y: x + y})
894
+ 1
895
+ >>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True)
896
+ y/(x + y)
897
+
898
+ In order to obtain a canonical result, unordered iterables are
899
+ sorted by count_op length, number of arguments and by the
900
+ default_sort_key to break any ties. All other iterables are left
901
+ unsorted.
902
+
903
+ >>> from sympy import sqrt, sin, cos
904
+ >>> from sympy.abc import a, b, c, d, e
905
+
906
+ >>> A = (sqrt(sin(2*x)), a)
907
+ >>> B = (sin(2*x), b)
908
+ >>> C = (cos(2*x), c)
909
+ >>> D = (x, d)
910
+ >>> E = (exp(x), e)
911
+
912
+ >>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)
913
+
914
+ >>> expr.subs(dict([A, B, C, D, E]))
915
+ a*c*sin(d*e) + b
916
+
917
+ The resulting expression represents a literal replacement of the
918
+ old arguments with the new arguments. This may not reflect the
919
+ limiting behavior of the expression:
920
+
921
+ >>> (x**3 - 3*x).subs({x: oo})
922
+ nan
923
+
924
+ >>> limit(x**3 - 3*x, x, oo)
925
+ oo
926
+
927
+ If the substitution will be followed by numerical
928
+ evaluation, it is better to pass the substitution to
929
+ evalf as
930
+
931
+ >>> (1/x).evalf(subs={x: 3.0}, n=21)
932
+ 0.333333333333333333333
933
+
934
+ rather than
935
+
936
+ >>> (1/x).subs({x: 3.0}).evalf(21)
937
+ 0.333333333333333314830
938
+
939
+ as the former will ensure that the desired level of precision is
940
+ obtained.
941
+
942
+ See Also
943
+ ========
944
+ replace: replacement capable of doing wildcard-like matching,
945
+ parsing of match, and conditional replacements
946
+ xreplace: exact node replacement in expr tree; also capable of
947
+ using matching rules
948
+ sympy.core.evalf.EvalfMixin.evalf: calculates the given formula to a desired level of precision
949
+
950
+ """
951
+ from .containers import Dict
952
+ from .symbol import Dummy, Symbol
953
+ from .numbers import _illegal
954
+
955
+ unordered = False
956
+ if len(args) == 1:
957
+
958
+ sequence = args[0]
959
+ if isinstance(sequence, set):
960
+ unordered = True
961
+ elif isinstance(sequence, (Dict, Mapping)):
962
+ unordered = True
963
+ sequence = sequence.items()
964
+ elif not iterable(sequence):
965
+ raise ValueError(filldedent("""
966
+ When a single argument is passed to subs
967
+ it should be a dictionary of old: new pairs or an iterable
968
+ of (old, new) tuples."""))
969
+ elif len(args) == 2:
970
+ sequence = [args]
971
+ else:
972
+ raise ValueError("subs accepts either 1 or 2 arguments")
973
+
974
+ def sympify_old(old):
975
+ if isinstance(old, str):
976
+ # Use Symbol rather than parse_expr for old
977
+ return Symbol(old)
978
+ elif isinstance(old, type):
979
+ # Allow a type e.g. Function('f') or sin
980
+ return sympify(old, strict=False)
981
+ else:
982
+ return sympify(old, strict=True)
983
+
984
+ def sympify_new(new):
985
+ if isinstance(new, (str, type)):
986
+ # Allow a type or parse a string input
987
+ return sympify(new, strict=False)
988
+ else:
989
+ return sympify(new, strict=True)
990
+
991
+ sequence = [(sympify_old(s1), sympify_new(s2)) for s1, s2 in sequence]
992
+
993
+ # skip if there is no change
994
+ sequence = [(s1, s2) for s1, s2 in sequence if not _aresame(s1, s2)]
995
+
996
+ simultaneous = kwargs.pop('simultaneous', False)
997
+
998
+ if unordered:
999
+ from .sorting import _nodes, default_sort_key
1000
+ sequence = dict(sequence)
1001
+ # order so more complex items are first and items
1002
+ # of identical complexity are ordered so
1003
+ # f(x) < f(y) < x < y
1004
+ # \___ 2 __/ \_1_/ <- number of nodes
1005
+ #
1006
+ # For more complex ordering use an unordered sequence.
1007
+ k = list(ordered(sequence, default=False, keys=(
1008
+ lambda x: -_nodes(x),
1009
+ default_sort_key,
1010
+ )))
1011
+ sequence = [(k, sequence[k]) for k in k]
1012
+ # do infinities first
1013
+ if not simultaneous:
1014
+ redo = [i for i, seq in enumerate(sequence) if seq[1] in _illegal]
1015
+ for i in reversed(redo):
1016
+ sequence.insert(0, sequence.pop(i))
1017
+
1018
+ if simultaneous: # XXX should this be the default for dict subs?
1019
+ reps = {}
1020
+ rv = self
1021
+ kwargs['hack2'] = True
1022
+ m = Dummy('subs_m')
1023
+ for old, new in sequence:
1024
+ com = new.is_commutative
1025
+ if com is None:
1026
+ com = True
1027
+ d = Dummy('subs_d', commutative=com)
1028
+ # using d*m so Subs will be used on dummy variables
1029
+ # in things like Derivative(f(x, y), x) in which x
1030
+ # is both free and bound
1031
+ rv = rv._subs(old, d*m, **kwargs)
1032
+ if not isinstance(rv, Basic):
1033
+ break
1034
+ reps[d] = new
1035
+ reps[m] = S.One # get rid of m
1036
+ return rv.xreplace(reps)
1037
+ else:
1038
+ rv = self
1039
+ for old, new in sequence:
1040
+ rv = rv._subs(old, new, **kwargs)
1041
+ if not isinstance(rv, Basic):
1042
+ break
1043
+ return rv
1044
+
1045
+ @cacheit
1046
+ def _subs(self, old, new, **hints):
1047
+ """Substitutes an expression old -> new.
1048
+
1049
+ If self is not equal to old then _eval_subs is called.
1050
+ If _eval_subs does not want to make any special replacement
1051
+ then a None is received which indicates that the fallback
1052
+ should be applied wherein a search for replacements is made
1053
+ amongst the arguments of self.
1054
+
1055
+ >>> from sympy import Add
1056
+ >>> from sympy.abc import x, y, z
1057
+
1058
+ Examples
1059
+ ========
1060
+
1061
+ Add's _eval_subs knows how to target x + y in the following
1062
+ so it makes the change:
1063
+
1064
+ >>> (x + y + z).subs(x + y, 1)
1065
+ z + 1
1066
+
1067
+ Add's _eval_subs does not need to know how to find x + y in
1068
+ the following:
1069
+
1070
+ >>> Add._eval_subs(z*(x + y) + 3, x + y, 1) is None
1071
+ True
1072
+
1073
+ The returned None will cause the fallback routine to traverse the args and
1074
+ pass the z*(x + y) arg to Mul where the change will take place and the
1075
+ substitution will succeed:
1076
+
1077
+ >>> (z*(x + y) + 3).subs(x + y, 1)
1078
+ z + 3
1079
+
1080
+ ** Developers Notes **
1081
+
1082
+ An _eval_subs routine for a class should be written if:
1083
+
1084
+ 1) any arguments are not instances of Basic (e.g. bool, tuple);
1085
+
1086
+ 2) some arguments should not be targeted (as in integration
1087
+ variables);
1088
+
1089
+ 3) if there is something other than a literal replacement
1090
+ that should be attempted (as in Piecewise where the condition
1091
+ may be updated without doing a replacement).
1092
+
1093
+ If it is overridden, here are some special cases that might arise:
1094
+
1095
+ 1) If it turns out that no special change was made and all
1096
+ the original sub-arguments should be checked for
1097
+ replacements then None should be returned.
1098
+
1099
+ 2) If it is necessary to do substitutions on a portion of
1100
+ the expression then _subs should be called. _subs will
1101
+ handle the case of any sub-expression being equal to old
1102
+ (which usually would not be the case) while its fallback
1103
+ will handle the recursion into the sub-arguments. For
1104
+ example, after Add's _eval_subs removes some matching terms
1105
+ it must process the remaining terms so it calls _subs
1106
+ on each of the un-matched terms and then adds them
1107
+ onto the terms previously obtained.
1108
+
1109
+ 3) If the initial expression should remain unchanged then
1110
+ the original expression should be returned. (Whenever an
1111
+ expression is returned, modified or not, no further
1112
+ substitution of old -> new is attempted.) Sum's _eval_subs
1113
+ routine uses this strategy when a substitution is attempted
1114
+ on any of its summation variables.
1115
+ """
1116
+
1117
+ def fallback(self, old, new):
1118
+ """
1119
+ Try to replace old with new in any of self's arguments.
1120
+ """
1121
+ hit = False
1122
+ args = list(self.args)
1123
+ for i, arg in enumerate(args):
1124
+ if not hasattr(arg, '_eval_subs'):
1125
+ continue
1126
+ arg = arg._subs(old, new, **hints)
1127
+ if not _aresame(arg, args[i]):
1128
+ hit = True
1129
+ args[i] = arg
1130
+ if hit:
1131
+ rv = self.func(*args)
1132
+ hack2 = hints.get('hack2', False)
1133
+ if hack2 and self.is_Mul and not rv.is_Mul: # 2-arg hack
1134
+ coeff = S.One
1135
+ nonnumber = []
1136
+ for i in args:
1137
+ if i.is_Number:
1138
+ coeff *= i
1139
+ else:
1140
+ nonnumber.append(i)
1141
+ nonnumber = self.func(*nonnumber)
1142
+ if coeff is S.One:
1143
+ return nonnumber
1144
+ else:
1145
+ return self.func(coeff, nonnumber, evaluate=False)
1146
+ return rv
1147
+ return self
1148
+
1149
+ if _aresame(self, old):
1150
+ return new
1151
+
1152
+ rv = self._eval_subs(old, new)
1153
+ if rv is None:
1154
+ rv = fallback(self, old, new)
1155
+ return rv
1156
+
1157
+ def _eval_subs(self, old, new):
1158
+ """Override this stub if you want to do anything more than
1159
+ attempt a replacement of old with new in the arguments of self.
1160
+
1161
+ See also
1162
+ ========
1163
+
1164
+ _subs
1165
+ """
1166
+ return None
1167
+
1168
+ def xreplace(self, rule):
1169
+ """
1170
+ Replace occurrences of objects within the expression.
1171
+
1172
+ Parameters
1173
+ ==========
1174
+
1175
+ rule : dict-like
1176
+ Expresses a replacement rule
1177
+
1178
+ Returns
1179
+ =======
1180
+
1181
+ xreplace : the result of the replacement
1182
+
1183
+ Examples
1184
+ ========
1185
+
1186
+ >>> from sympy import symbols, pi, exp
1187
+ >>> x, y, z = symbols('x y z')
1188
+ >>> (1 + x*y).xreplace({x: pi})
1189
+ pi*y + 1
1190
+ >>> (1 + x*y).xreplace({x: pi, y: 2})
1191
+ 1 + 2*pi
1192
+
1193
+ Replacements occur only if an entire node in the expression tree is
1194
+ matched:
1195
+
1196
+ >>> (x*y + z).xreplace({x*y: pi})
1197
+ z + pi
1198
+ >>> (x*y*z).xreplace({x*y: pi})
1199
+ x*y*z
1200
+ >>> (2*x).xreplace({2*x: y, x: z})
1201
+ y
1202
+ >>> (2*2*x).xreplace({2*x: y, x: z})
1203
+ 4*z
1204
+ >>> (x + y + 2).xreplace({x + y: 2})
1205
+ x + y + 2
1206
+ >>> (x + 2 + exp(x + 2)).xreplace({x + 2: y})
1207
+ x + exp(y) + 2
1208
+
1209
+ xreplace does not differentiate between free and bound symbols. In the
1210
+ following, subs(x, y) would not change x since it is a bound symbol,
1211
+ but xreplace does:
1212
+
1213
+ >>> from sympy import Integral
1214
+ >>> Integral(x, (x, 1, 2*x)).xreplace({x: y})
1215
+ Integral(y, (y, 1, 2*y))
1216
+
1217
+ Trying to replace x with an expression raises an error:
1218
+
1219
+ >>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) # doctest: +SKIP
1220
+ ValueError: Invalid limits given: ((2*y, 1, 4*y),)
1221
+
1222
+ See Also
1223
+ ========
1224
+ replace: replacement capable of doing wildcard-like matching,
1225
+ parsing of match, and conditional replacements
1226
+ subs: substitution of subexpressions as defined by the objects
1227
+ themselves.
1228
+
1229
+ """
1230
+ value, _ = self._xreplace(rule)
1231
+ return value
1232
+
1233
+ def _xreplace(self, rule):
1234
+ """
1235
+ Helper for xreplace. Tracks whether a replacement actually occurred.
1236
+ """
1237
+ if self in rule:
1238
+ return rule[self], True
1239
+ elif rule:
1240
+ args = []
1241
+ changed = False
1242
+ for a in self.args:
1243
+ _xreplace = getattr(a, '_xreplace', None)
1244
+ if _xreplace is not None:
1245
+ a_xr = _xreplace(rule)
1246
+ args.append(a_xr[0])
1247
+ changed |= a_xr[1]
1248
+ else:
1249
+ args.append(a)
1250
+ args = tuple(args)
1251
+ if changed:
1252
+ return self.func(*args), True
1253
+ return self, False
1254
+
1255
+ @cacheit
1256
+ def has(self, *patterns):
1257
+ """
1258
+ Test whether any subexpression matches any of the patterns.
1259
+
1260
+ Examples
1261
+ ========
1262
+
1263
+ >>> from sympy import sin
1264
+ >>> from sympy.abc import x, y, z
1265
+ >>> (x**2 + sin(x*y)).has(z)
1266
+ False
1267
+ >>> (x**2 + sin(x*y)).has(x, y, z)
1268
+ True
1269
+ >>> x.has(x)
1270
+ True
1271
+
1272
+ Note ``has`` is a structural algorithm with no knowledge of
1273
+ mathematics. Consider the following half-open interval:
1274
+
1275
+ >>> from sympy import Interval
1276
+ >>> i = Interval.Lopen(0, 5); i
1277
+ Interval.Lopen(0, 5)
1278
+ >>> i.args
1279
+ (0, 5, True, False)
1280
+ >>> i.has(4) # there is no "4" in the arguments
1281
+ False
1282
+ >>> i.has(0) # there *is* a "0" in the arguments
1283
+ True
1284
+
1285
+ Instead, use ``contains`` to determine whether a number is in the
1286
+ interval or not:
1287
+
1288
+ >>> i.contains(4)
1289
+ True
1290
+ >>> i.contains(0)
1291
+ False
1292
+
1293
+
1294
+ Note that ``expr.has(*patterns)`` is exactly equivalent to
1295
+ ``any(expr.has(p) for p in patterns)``. In particular, ``False`` is
1296
+ returned when the list of patterns is empty.
1297
+
1298
+ >>> x.has()
1299
+ False
1300
+
1301
+ """
1302
+ return self._has(iterargs, *patterns)
1303
+
1304
+ def has_xfree(self, s: set[Basic]):
1305
+ """Return True if self has any of the patterns in s as a
1306
+ free argument, else False. This is like `Basic.has_free`
1307
+ but this will only report exact argument matches.
1308
+
1309
+ Examples
1310
+ ========
1311
+
1312
+ >>> from sympy import Function
1313
+ >>> from sympy.abc import x, y
1314
+ >>> f = Function('f')
1315
+ >>> f(x).has_xfree({f})
1316
+ False
1317
+ >>> f(x).has_xfree({f(x)})
1318
+ True
1319
+ >>> f(x + 1).has_xfree({x})
1320
+ True
1321
+ >>> f(x + 1).has_xfree({x + 1})
1322
+ True
1323
+ >>> f(x + y + 1).has_xfree({x + 1})
1324
+ False
1325
+ """
1326
+ # protect O(1) containment check by requiring:
1327
+ if type(s) is not set:
1328
+ raise TypeError('expecting set argument')
1329
+ return any(a in s for a in iterfreeargs(self))
1330
+
1331
+ @cacheit
1332
+ def has_free(self, *patterns):
1333
+ """Return True if self has object(s) ``x`` as a free expression
1334
+ else False.
1335
+
1336
+ Examples
1337
+ ========
1338
+
1339
+ >>> from sympy import Integral, Function
1340
+ >>> from sympy.abc import x, y
1341
+ >>> f = Function('f')
1342
+ >>> g = Function('g')
1343
+ >>> expr = Integral(f(x), (f(x), 1, g(y)))
1344
+ >>> expr.free_symbols
1345
+ {y}
1346
+ >>> expr.has_free(g(y))
1347
+ True
1348
+ >>> expr.has_free(*(x, f(x)))
1349
+ False
1350
+
1351
+ This works for subexpressions and types, too:
1352
+
1353
+ >>> expr.has_free(g)
1354
+ True
1355
+ >>> (x + y + 1).has_free(y + 1)
1356
+ True
1357
+ """
1358
+ if not patterns:
1359
+ return False
1360
+ p0 = patterns[0]
1361
+ if len(patterns) == 1 and iterable(p0) and not isinstance(p0, Basic):
1362
+ # Basic can contain iterables (though not non-Basic, ideally)
1363
+ # but don't encourage mixed passing patterns
1364
+ raise TypeError(filldedent('''
1365
+ Expecting 1 or more Basic args, not a single
1366
+ non-Basic iterable. Don't forget to unpack
1367
+ iterables: `eq.has_free(*patterns)`'''))
1368
+ # try quick test first
1369
+ s = set(patterns)
1370
+ rv = self.has_xfree(s)
1371
+ if rv:
1372
+ return rv
1373
+ # now try matching through slower _has
1374
+ return self._has(iterfreeargs, *patterns)
1375
+
1376
+ def _has(self, iterargs, *patterns):
1377
+ # separate out types and unhashable objects
1378
+ type_set = set() # only types
1379
+ p_set = set() # hashable non-types
1380
+ for p in patterns:
1381
+ if isinstance(p, type) and issubclass(p, Basic):
1382
+ type_set.add(p)
1383
+ continue
1384
+ if not isinstance(p, Basic):
1385
+ try:
1386
+ p = _sympify(p)
1387
+ except SympifyError:
1388
+ continue # Basic won't have this in it
1389
+ p_set.add(p) # fails if object defines __eq__ but
1390
+ # doesn't define __hash__
1391
+ types = tuple(type_set) #
1392
+ for i in iterargs(self): #
1393
+ if i in p_set: # <--- here, too
1394
+ return True
1395
+ if isinstance(i, types):
1396
+ return True
1397
+
1398
+ # use matcher if defined, e.g. operations defines
1399
+ # matcher that checks for exact subset containment,
1400
+ # (x + y + 1).has(x + 1) -> True
1401
+ for i in p_set - type_set: # types don't have matchers
1402
+ if not hasattr(i, '_has_matcher'):
1403
+ continue
1404
+ match = i._has_matcher()
1405
+ if any(match(arg) for arg in iterargs(self)):
1406
+ return True
1407
+
1408
+ # no success
1409
+ return False
1410
+
1411
+ def replace(self, query, value, map=False, simultaneous=True, exact=None):
1412
+ """
1413
+ Replace matching subexpressions of ``self`` with ``value``.
1414
+
1415
+ If ``map = True`` then also return the mapping {old: new} where ``old``
1416
+ was a sub-expression found with query and ``new`` is the replacement
1417
+ value for it. If the expression itself does not match the query, then
1418
+ the returned value will be ``self.xreplace(map)`` otherwise it should
1419
+ be ``self.subs(ordered(map.items()))``.
1420
+
1421
+ Traverses an expression tree and performs replacement of matching
1422
+ subexpressions from the bottom to the top of the tree. The default
1423
+ approach is to do the replacement in a simultaneous fashion so
1424
+ changes made are targeted only once. If this is not desired or causes
1425
+ problems, ``simultaneous`` can be set to False.
1426
+
1427
+ In addition, if an expression containing more than one Wild symbol
1428
+ is being used to match subexpressions and the ``exact`` flag is None
1429
+ it will be set to True so the match will only succeed if all non-zero
1430
+ values are received for each Wild that appears in the match pattern.
1431
+ Setting this to False accepts a match of 0; while setting it True
1432
+ accepts all matches that have a 0 in them. See example below for
1433
+ cautions.
1434
+
1435
+ The list of possible combinations of queries and replacement values
1436
+ is listed below:
1437
+
1438
+ Examples
1439
+ ========
1440
+
1441
+ Initial setup
1442
+
1443
+ >>> from sympy import log, sin, cos, tan, Wild, Mul, Add
1444
+ >>> from sympy.abc import x, y
1445
+ >>> f = log(sin(x)) + tan(sin(x**2))
1446
+
1447
+ 1.1. type -> type
1448
+ obj.replace(type, newtype)
1449
+
1450
+ When object of type ``type`` is found, replace it with the
1451
+ result of passing its argument(s) to ``newtype``.
1452
+
1453
+ >>> f.replace(sin, cos)
1454
+ log(cos(x)) + tan(cos(x**2))
1455
+ >>> sin(x).replace(sin, cos, map=True)
1456
+ (cos(x), {sin(x): cos(x)})
1457
+ >>> (x*y).replace(Mul, Add)
1458
+ x + y
1459
+
1460
+ 1.2. type -> func
1461
+ obj.replace(type, func)
1462
+
1463
+ When object of type ``type`` is found, apply ``func`` to its
1464
+ argument(s). ``func`` must be written to handle the number
1465
+ of arguments of ``type``.
1466
+
1467
+ >>> f.replace(sin, lambda arg: sin(2*arg))
1468
+ log(sin(2*x)) + tan(sin(2*x**2))
1469
+ >>> (x*y).replace(Mul, lambda *args: sin(2*Mul(*args)))
1470
+ sin(2*x*y)
1471
+
1472
+ 2.1. pattern -> expr
1473
+ obj.replace(pattern(wild), expr(wild))
1474
+
1475
+ Replace subexpressions matching ``pattern`` with the expression
1476
+ written in terms of the Wild symbols in ``pattern``.
1477
+
1478
+ >>> a, b = map(Wild, 'ab')
1479
+ >>> f.replace(sin(a), tan(a))
1480
+ log(tan(x)) + tan(tan(x**2))
1481
+ >>> f.replace(sin(a), tan(a/2))
1482
+ log(tan(x/2)) + tan(tan(x**2/2))
1483
+ >>> f.replace(sin(a), a)
1484
+ log(x) + tan(x**2)
1485
+ >>> (x*y).replace(a*x, a)
1486
+ y
1487
+
1488
+ Matching is exact by default when more than one Wild symbol
1489
+ is used: matching fails unless the match gives non-zero
1490
+ values for all Wild symbols:
1491
+
1492
+ >>> (2*x + y).replace(a*x + b, b - a)
1493
+ y - 2
1494
+ >>> (2*x).replace(a*x + b, b - a)
1495
+ 2*x
1496
+
1497
+ When set to False, the results may be non-intuitive:
1498
+
1499
+ >>> (2*x).replace(a*x + b, b - a, exact=False)
1500
+ 2/x
1501
+
1502
+ 2.2. pattern -> func
1503
+ obj.replace(pattern(wild), lambda wild: expr(wild))
1504
+
1505
+ All behavior is the same as in 2.1 but now a function in terms of
1506
+ pattern variables is used rather than an expression:
1507
+
1508
+ >>> f.replace(sin(a), lambda a: sin(2*a))
1509
+ log(sin(2*x)) + tan(sin(2*x**2))
1510
+
1511
+ 3.1. func -> func
1512
+ obj.replace(filter, func)
1513
+
1514
+ Replace subexpression ``e`` with ``func(e)`` if ``filter(e)``
1515
+ is True.
1516
+
1517
+ >>> g = 2*sin(x**3)
1518
+ >>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
1519
+ 4*sin(x**9)
1520
+
1521
+ The expression itself is also targeted by the query but is done in
1522
+ such a fashion that changes are not made twice.
1523
+
1524
+ >>> e = x*(x*y + 1)
1525
+ >>> e.replace(lambda x: x.is_Mul, lambda x: 2*x)
1526
+ 2*x*(2*x*y + 1)
1527
+
1528
+ When matching a single symbol, `exact` will default to True, but
1529
+ this may or may not be the behavior that is desired:
1530
+
1531
+ Here, we want `exact=False`:
1532
+
1533
+ >>> from sympy import Function
1534
+ >>> f = Function('f')
1535
+ >>> e = f(1) + f(0)
1536
+ >>> q = f(a), lambda a: f(a + 1)
1537
+ >>> e.replace(*q, exact=False)
1538
+ f(1) + f(2)
1539
+ >>> e.replace(*q, exact=True)
1540
+ f(0) + f(2)
1541
+
1542
+ But here, the nature of matching makes selecting
1543
+ the right setting tricky:
1544
+
1545
+ >>> e = x**(1 + y)
1546
+ >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=False)
1547
+ x
1548
+ >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=True)
1549
+ x**(-x - y + 1)
1550
+ >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=False)
1551
+ x
1552
+ >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=True)
1553
+ x**(1 - y)
1554
+
1555
+ It is probably better to use a different form of the query
1556
+ that describes the target expression more precisely:
1557
+
1558
+ >>> (1 + x**(1 + y)).replace(
1559
+ ... lambda x: x.is_Pow and x.exp.is_Add and x.exp.args[0] == 1,
1560
+ ... lambda x: x.base**(1 - (x.exp - 1)))
1561
+ ...
1562
+ x**(1 - y) + 1
1563
+
1564
+ See Also
1565
+ ========
1566
+
1567
+ subs: substitution of subexpressions as defined by the objects
1568
+ themselves.
1569
+ xreplace: exact node replacement in expr tree; also capable of
1570
+ using matching rules
1571
+
1572
+ """
1573
+
1574
+ try:
1575
+ query = _sympify(query)
1576
+ except SympifyError:
1577
+ pass
1578
+ try:
1579
+ value = _sympify(value)
1580
+ except SympifyError:
1581
+ pass
1582
+ if isinstance(query, type):
1583
+ _query = lambda expr: isinstance(expr, query)
1584
+
1585
+ if isinstance(value, type):
1586
+ _value = lambda expr, result: value(*expr.args)
1587
+ elif callable(value):
1588
+ _value = lambda expr, result: value(*expr.args)
1589
+ else:
1590
+ raise TypeError(
1591
+ "given a type, replace() expects another "
1592
+ "type or a callable")
1593
+ elif isinstance(query, Basic):
1594
+ _query = lambda expr: expr.match(query)
1595
+ if exact is None:
1596
+ from .symbol import Wild
1597
+ exact = (len(query.atoms(Wild)) > 1)
1598
+
1599
+ if isinstance(value, Basic):
1600
+ if exact:
1601
+ _value = lambda expr, result: (value.subs(result)
1602
+ if all(result.values()) else expr)
1603
+ else:
1604
+ _value = lambda expr, result: value.subs(result)
1605
+ elif callable(value):
1606
+ # match dictionary keys get the trailing underscore stripped
1607
+ # from them and are then passed as keywords to the callable;
1608
+ # if ``exact`` is True, only accept match if there are no null
1609
+ # values amongst those matched.
1610
+ if exact:
1611
+ _value = lambda expr, result: (value(**
1612
+ {str(k)[:-1]: v for k, v in result.items()})
1613
+ if all(val for val in result.values()) else expr)
1614
+ else:
1615
+ _value = lambda expr, result: value(**
1616
+ {str(k)[:-1]: v for k, v in result.items()})
1617
+ else:
1618
+ raise TypeError(
1619
+ "given an expression, replace() expects "
1620
+ "another expression or a callable")
1621
+ elif callable(query):
1622
+ _query = query
1623
+
1624
+ if callable(value):
1625
+ _value = lambda expr, result: value(expr)
1626
+ else:
1627
+ raise TypeError(
1628
+ "given a callable, replace() expects "
1629
+ "another callable")
1630
+ else:
1631
+ raise TypeError(
1632
+ "first argument to replace() must be a "
1633
+ "type, an expression or a callable")
1634
+
1635
+ def walk(rv, F):
1636
+ """Apply ``F`` to args and then to result.
1637
+ """
1638
+ args = getattr(rv, 'args', None)
1639
+ if args is not None:
1640
+ if args:
1641
+ newargs = tuple([walk(a, F) for a in args])
1642
+ if args != newargs:
1643
+ rv = rv.func(*newargs)
1644
+ if simultaneous:
1645
+ # if rv is something that was already
1646
+ # matched (that was changed) then skip
1647
+ # applying F again
1648
+ for i, e in enumerate(args):
1649
+ if rv == e and e != newargs[i]:
1650
+ return rv
1651
+ rv = F(rv)
1652
+ return rv
1653
+
1654
+ mapping = {} # changes that took place
1655
+
1656
+ def rec_replace(expr):
1657
+ result = _query(expr)
1658
+ if result or result == {}:
1659
+ v = _value(expr, result)
1660
+ if v is not None and v != expr:
1661
+ if map:
1662
+ mapping[expr] = v
1663
+ expr = v
1664
+ return expr
1665
+
1666
+ rv = walk(self, rec_replace)
1667
+ return (rv, mapping) if map else rv
1668
+
1669
+ def find(self, query, group=False):
1670
+ """Find all subexpressions matching a query."""
1671
+ query = _make_find_query(query)
1672
+ results = list(filter(query, _preorder_traversal(self)))
1673
+
1674
+ if not group:
1675
+ return set(results)
1676
+ else:
1677
+ groups = {}
1678
+
1679
+ for result in results:
1680
+ if result in groups:
1681
+ groups[result] += 1
1682
+ else:
1683
+ groups[result] = 1
1684
+
1685
+ return groups
1686
+
1687
+ def count(self, query):
1688
+ """Count the number of matching subexpressions."""
1689
+ query = _make_find_query(query)
1690
+ return sum(bool(query(sub)) for sub in _preorder_traversal(self))
1691
+
1692
+ def matches(self, expr, repl_dict=None, old=False):
1693
+ """
1694
+ Helper method for match() that looks for a match between Wild symbols
1695
+ in self and expressions in expr.
1696
+
1697
+ Examples
1698
+ ========
1699
+
1700
+ >>> from sympy import symbols, Wild, Basic
1701
+ >>> a, b, c = symbols('a b c')
1702
+ >>> x = Wild('x')
1703
+ >>> Basic(a + x, x).matches(Basic(a + b, c)) is None
1704
+ True
1705
+ >>> Basic(a + x, x).matches(Basic(a + b + c, b + c))
1706
+ {x_: b + c}
1707
+ """
1708
+ expr = sympify(expr)
1709
+ if not isinstance(expr, self.__class__):
1710
+ return None
1711
+
1712
+ if repl_dict is None:
1713
+ repl_dict = {}
1714
+ else:
1715
+ repl_dict = repl_dict.copy()
1716
+
1717
+ if self == expr:
1718
+ return repl_dict
1719
+
1720
+ if len(self.args) != len(expr.args):
1721
+ return None
1722
+
1723
+ d = repl_dict # already a copy
1724
+ for arg, other_arg in zip(self.args, expr.args):
1725
+ if arg == other_arg:
1726
+ continue
1727
+ if arg.is_Relational:
1728
+ try:
1729
+ d = arg.xreplace(d).matches(other_arg, d, old=old)
1730
+ except TypeError: # Should be InvalidComparisonError when introduced
1731
+ d = None
1732
+ else:
1733
+ d = arg.xreplace(d).matches(other_arg, d, old=old)
1734
+ if d is None:
1735
+ return None
1736
+ return d
1737
+
1738
+ def match(self, pattern, old=False):
1739
+ """
1740
+ Pattern matching.
1741
+
1742
+ Wild symbols match all.
1743
+
1744
+ Return ``None`` when expression (self) does not match
1745
+ with pattern. Otherwise return a dictionary such that::
1746
+
1747
+ pattern.xreplace(self.match(pattern)) == self
1748
+
1749
+ Examples
1750
+ ========
1751
+
1752
+ >>> from sympy import Wild, Sum
1753
+ >>> from sympy.abc import x, y
1754
+ >>> p = Wild("p")
1755
+ >>> q = Wild("q")
1756
+ >>> r = Wild("r")
1757
+ >>> e = (x+y)**(x+y)
1758
+ >>> e.match(p**p)
1759
+ {p_: x + y}
1760
+ >>> e.match(p**q)
1761
+ {p_: x + y, q_: x + y}
1762
+ >>> e = (2*x)**2
1763
+ >>> e.match(p*q**r)
1764
+ {p_: 4, q_: x, r_: 2}
1765
+ >>> (p*q**r).xreplace(e.match(p*q**r))
1766
+ 4*x**2
1767
+
1768
+ Structurally bound symbols are ignored during matching:
1769
+
1770
+ >>> Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, p)))
1771
+ {p_: 2}
1772
+
1773
+ But they can be identified if desired:
1774
+
1775
+ >>> Sum(x, (x, 1, 2)).match(Sum(q, (q, 1, p)))
1776
+ {p_: 2, q_: x}
1777
+
1778
+ The ``old`` flag will give the old-style pattern matching where
1779
+ expressions and patterns are essentially solved to give the
1780
+ match. Both of the following give None unless ``old=True``:
1781
+
1782
+ >>> (x - 2).match(p - x, old=True)
1783
+ {p_: 2*x - 2}
1784
+ >>> (2/x).match(p*x, old=True)
1785
+ {p_: 2/x**2}
1786
+
1787
+ """
1788
+ pattern = sympify(pattern)
1789
+ # match non-bound symbols
1790
+ canonical = lambda x: x if x.is_Symbol else x.as_dummy()
1791
+ m = canonical(pattern).matches(canonical(self), old=old)
1792
+ if m is None:
1793
+ return m
1794
+ from .symbol import Wild
1795
+ from .function import WildFunction
1796
+ from ..tensor.tensor import WildTensor, WildTensorIndex, WildTensorHead
1797
+ wild = pattern.atoms(Wild, WildFunction, WildTensor, WildTensorIndex, WildTensorHead)
1798
+ # sanity check
1799
+ if set(m) - wild:
1800
+ raise ValueError(filldedent('''
1801
+ Some `matches` routine did not use a copy of repl_dict
1802
+ and injected unexpected symbols. Report this as an
1803
+ error at https://github.com/sympy/sympy/issues'''))
1804
+ # now see if bound symbols were requested
1805
+ bwild = wild - set(m)
1806
+ if not bwild:
1807
+ return m
1808
+ # replace free-Wild symbols in pattern with match result
1809
+ # so they will match but not be in the next match
1810
+ wpat = pattern.xreplace(m)
1811
+ # identify remaining bound wild
1812
+ w = wpat.matches(self, old=old)
1813
+ # add them to m
1814
+ if w:
1815
+ m.update(w)
1816
+ # done
1817
+ return m
1818
+
1819
+ def count_ops(self, visual=None):
1820
+ """Wrapper for count_ops that returns the operation count."""
1821
+ from .function import count_ops
1822
+ return count_ops(self, visual)
1823
+
1824
+ def doit(self, **hints):
1825
+ """Evaluate objects that are not evaluated by default like limits,
1826
+ integrals, sums and products. All objects of this kind will be
1827
+ evaluated recursively, unless some species were excluded via 'hints'
1828
+ or unless the 'deep' hint was set to 'False'.
1829
+
1830
+ >>> from sympy import Integral
1831
+ >>> from sympy.abc import x
1832
+
1833
+ >>> 2*Integral(x, x)
1834
+ 2*Integral(x, x)
1835
+
1836
+ >>> (2*Integral(x, x)).doit()
1837
+ x**2
1838
+
1839
+ >>> (2*Integral(x, x)).doit(deep=False)
1840
+ 2*Integral(x, x)
1841
+
1842
+ """
1843
+ if hints.get('deep', True):
1844
+ terms = [term.doit(**hints) if isinstance(term, Basic) else term
1845
+ for term in self.args]
1846
+ return self.func(*terms)
1847
+ else:
1848
+ return self
1849
+
1850
+ def simplify(self, **kwargs):
1851
+ """See the simplify function in sympy.simplify"""
1852
+ from sympy.simplify.simplify import simplify
1853
+ return simplify(self, **kwargs)
1854
+
1855
+ def refine(self, assumption=True):
1856
+ """See the refine function in sympy.assumptions"""
1857
+ from sympy.assumptions.refine import refine
1858
+ return refine(self, assumption)
1859
+
1860
+ def _eval_derivative_n_times(self, s, n):
1861
+ # This is the default evaluator for derivatives (as called by `diff`
1862
+ # and `Derivative`), it will attempt a loop to derive the expression
1863
+ # `n` times by calling the corresponding `_eval_derivative` method,
1864
+ # while leaving the derivative unevaluated if `n` is symbolic. This
1865
+ # method should be overridden if the object has a closed form for its
1866
+ # symbolic n-th derivative.
1867
+ from .numbers import Integer
1868
+ if isinstance(n, (int, Integer)):
1869
+ obj = self
1870
+ for i in range(n):
1871
+ obj2 = obj._eval_derivative(s)
1872
+ if obj == obj2 or obj2 is None:
1873
+ break
1874
+ obj = obj2
1875
+ return obj2
1876
+ else:
1877
+ return None
1878
+
1879
+ def rewrite(self, *args, deep=True, **hints):
1880
+ """
1881
+ Rewrite *self* using a defined rule.
1882
+
1883
+ Rewriting transforms an expression to another, which is mathematically
1884
+ equivalent but structurally different. For example you can rewrite
1885
+ trigonometric functions as complex exponentials or combinatorial
1886
+ functions as gamma function.
1887
+
1888
+ This method takes a *pattern* and a *rule* as positional arguments.
1889
+ *pattern* is optional parameter which defines the types of expressions
1890
+ that will be transformed. If it is not passed, all possible expressions
1891
+ will be rewritten. *rule* defines how the expression will be rewritten.
1892
+
1893
+ Parameters
1894
+ ==========
1895
+
1896
+ args : Expr
1897
+ A *rule*, or *pattern* and *rule*.
1898
+ - *pattern* is a type or an iterable of types.
1899
+ - *rule* can be any object.
1900
+
1901
+ deep : bool, optional
1902
+ If ``True``, subexpressions are recursively transformed. Default is
1903
+ ``True``.
1904
+
1905
+ Examples
1906
+ ========
1907
+
1908
+ If *pattern* is unspecified, all possible expressions are transformed.
1909
+
1910
+ >>> from sympy import cos, sin, exp, I
1911
+ >>> from sympy.abc import x
1912
+ >>> expr = cos(x) + I*sin(x)
1913
+ >>> expr.rewrite(exp)
1914
+ exp(I*x)
1915
+
1916
+ Pattern can be a type or an iterable of types.
1917
+
1918
+ >>> expr.rewrite(sin, exp)
1919
+ exp(I*x)/2 + cos(x) - exp(-I*x)/2
1920
+ >>> expr.rewrite([cos,], exp)
1921
+ exp(I*x)/2 + I*sin(x) + exp(-I*x)/2
1922
+ >>> expr.rewrite([cos, sin], exp)
1923
+ exp(I*x)
1924
+
1925
+ Rewriting behavior can be implemented by defining ``_eval_rewrite()``
1926
+ method.
1927
+
1928
+ >>> from sympy import Expr, sqrt, pi
1929
+ >>> class MySin(Expr):
1930
+ ... def _eval_rewrite(self, rule, args, **hints):
1931
+ ... x, = args
1932
+ ... if rule == cos:
1933
+ ... return cos(pi/2 - x, evaluate=False)
1934
+ ... if rule == sqrt:
1935
+ ... return sqrt(1 - cos(x)**2)
1936
+ >>> MySin(MySin(x)).rewrite(cos)
1937
+ cos(-cos(-x + pi/2) + pi/2)
1938
+ >>> MySin(x).rewrite(sqrt)
1939
+ sqrt(1 - cos(x)**2)
1940
+
1941
+ Defining ``_eval_rewrite_as_[...]()`` method is supported for backwards
1942
+ compatibility reason. This may be removed in the future and using it is
1943
+ discouraged.
1944
+
1945
+ >>> class MySin(Expr):
1946
+ ... def _eval_rewrite_as_cos(self, *args, **hints):
1947
+ ... x, = args
1948
+ ... return cos(pi/2 - x, evaluate=False)
1949
+ >>> MySin(x).rewrite(cos)
1950
+ cos(-x + pi/2)
1951
+
1952
+ """
1953
+ if not args:
1954
+ return self
1955
+
1956
+ hints.update(deep=deep)
1957
+
1958
+ pattern = args[:-1]
1959
+ rule = args[-1]
1960
+
1961
+ # support old design by _eval_rewrite_as_[...] method
1962
+ if isinstance(rule, str):
1963
+ method = "_eval_rewrite_as_%s" % rule
1964
+ elif hasattr(rule, "__name__"):
1965
+ # rule is class or function
1966
+ clsname = rule.__name__
1967
+ method = "_eval_rewrite_as_%s" % clsname
1968
+ else:
1969
+ # rule is instance
1970
+ clsname = rule.__class__.__name__
1971
+ method = "_eval_rewrite_as_%s" % clsname
1972
+
1973
+ if pattern:
1974
+ if iterable(pattern[0]):
1975
+ pattern = pattern[0]
1976
+ pattern = tuple(p for p in pattern if self.has(p))
1977
+ if not pattern:
1978
+ return self
1979
+ # hereafter, empty pattern is interpreted as all pattern.
1980
+
1981
+ return self._rewrite(pattern, rule, method, **hints)
1982
+
1983
+ def _rewrite(self, pattern, rule, method, **hints):
1984
+ deep = hints.pop('deep', True)
1985
+ if deep:
1986
+ args = [a._rewrite(pattern, rule, method, **hints)
1987
+ for a in self.args]
1988
+ else:
1989
+ args = self.args
1990
+ if not pattern or any(isinstance(self, p) for p in pattern):
1991
+ meth = getattr(self, method, None)
1992
+ if meth is not None:
1993
+ rewritten = meth(*args, **hints)
1994
+ else:
1995
+ rewritten = self._eval_rewrite(rule, args, **hints)
1996
+ if rewritten is not None:
1997
+ return rewritten
1998
+ if not args:
1999
+ return self
2000
+ return self.func(*args)
2001
+
2002
+ def _eval_rewrite(self, rule, args, **hints):
2003
+ return None
2004
+
2005
+ _constructor_postprocessor_mapping = {} # type: ignore
2006
+
2007
+ @classmethod
2008
+ def _exec_constructor_postprocessors(cls, obj):
2009
+ # WARNING: This API is experimental.
2010
+
2011
+ # This is an experimental API that introduces constructor
2012
+ # postprosessors for SymPy Core elements. If an argument of a SymPy
2013
+ # expression has a `_constructor_postprocessor_mapping` attribute, it will
2014
+ # be interpreted as a dictionary containing lists of postprocessing
2015
+ # functions for matching expression node names.
2016
+
2017
+ clsname = obj.__class__.__name__
2018
+ postprocessors = defaultdict(list)
2019
+ for i in obj.args:
2020
+ try:
2021
+ postprocessor_mappings = (
2022
+ Basic._constructor_postprocessor_mapping[cls].items()
2023
+ for cls in type(i).mro()
2024
+ if cls in Basic._constructor_postprocessor_mapping
2025
+ )
2026
+ for k, v in chain.from_iterable(postprocessor_mappings):
2027
+ postprocessors[k].extend([j for j in v if j not in postprocessors[k]])
2028
+ except TypeError:
2029
+ pass
2030
+
2031
+ for f in postprocessors.get(clsname, []):
2032
+ obj = f(obj)
2033
+
2034
+ return obj
2035
+
2036
+ def _sage_(self):
2037
+ """
2038
+ Convert *self* to a symbolic expression of SageMath.
2039
+
2040
+ This version of the method is merely a placeholder.
2041
+ """
2042
+ old_method = self._sage_
2043
+ from sage.interfaces.sympy import sympy_init
2044
+ sympy_init() # may monkey-patch _sage_ method into self's class or superclasses
2045
+ if old_method == self._sage_:
2046
+ raise NotImplementedError('conversion to SageMath is not implemented')
2047
+ else:
2048
+ # call the freshly monkey-patched method
2049
+ return self._sage_()
2050
+
2051
+ def could_extract_minus_sign(self):
2052
+ return False # see Expr.could_extract_minus_sign
2053
+
2054
+
2055
+ # For all Basic subclasses _prepare_class_assumptions is called by
2056
+ # Basic.__init_subclass__ but that method is not called for Basic itself so we
2057
+ # call the function here instead.
2058
+ _prepare_class_assumptions(Basic)
2059
+
2060
+
2061
+ class Atom(Basic):
2062
+ """
2063
+ A parent class for atomic things. An atom is an expression with no subexpressions.
2064
+
2065
+ Examples
2066
+ ========
2067
+
2068
+ Symbol, Number, Rational, Integer, ...
2069
+ But not: Add, Mul, Pow, ...
2070
+ """
2071
+
2072
+ is_Atom = True
2073
+
2074
+ __slots__ = ()
2075
+
2076
+ def matches(self, expr, repl_dict=None, old=False):
2077
+ if self == expr:
2078
+ if repl_dict is None:
2079
+ return {}
2080
+ return repl_dict.copy()
2081
+
2082
+ def xreplace(self, rule, hack2=False):
2083
+ return rule.get(self, self)
2084
+
2085
+ def doit(self, **hints):
2086
+ return self
2087
+
2088
+ @classmethod
2089
+ def class_key(cls):
2090
+ return 2, 0, cls.__name__
2091
+
2092
+ @cacheit
2093
+ def sort_key(self, order=None):
2094
+ return self.class_key(), (1, (str(self),)), S.One.sort_key(), S.One
2095
+
2096
+ def _eval_simplify(self, **kwargs):
2097
+ return self
2098
+
2099
+ @property
2100
+ def _sorted_args(self):
2101
+ # this is here as a safeguard against accidentally using _sorted_args
2102
+ # on Atoms -- they cannot be rebuilt as atom.func(*atom._sorted_args)
2103
+ # since there are no args. So the calling routine should be checking
2104
+ # to see that this property is not called for Atoms.
2105
+ raise AttributeError('Atoms have no args. It might be necessary'
2106
+ ' to make a check for Atoms in the calling code.')
2107
+
2108
+
2109
+ def _aresame(a, b):
2110
+ """Return True if a and b are structurally the same, else False.
2111
+
2112
+ Examples
2113
+ ========
2114
+
2115
+ In SymPy (as in Python) two numbers compare the same if they
2116
+ have the same underlying base-2 representation even though
2117
+ they may not be the same type:
2118
+
2119
+ >>> from sympy import S
2120
+ >>> 2.0 == S(2)
2121
+ True
2122
+ >>> 0.5 == S.Half
2123
+ True
2124
+
2125
+ This routine was written to provide a query for such cases that
2126
+ would give false when the types do not match:
2127
+
2128
+ >>> from sympy.core.basic import _aresame
2129
+ >>> _aresame(S(2.0), S(2))
2130
+ False
2131
+
2132
+ """
2133
+ from .numbers import Number
2134
+ from .function import AppliedUndef, UndefinedFunction as UndefFunc
2135
+ if isinstance(a, Number) and isinstance(b, Number):
2136
+ return a == b and a.__class__ == b.__class__
2137
+ for i, j in zip_longest(_preorder_traversal(a), _preorder_traversal(b)):
2138
+ if i != j or type(i) != type(j):
2139
+ if ((isinstance(i, UndefFunc) and isinstance(j, UndefFunc)) or
2140
+ (isinstance(i, AppliedUndef) and isinstance(j, AppliedUndef))):
2141
+ if i.class_key() != j.class_key():
2142
+ return False
2143
+ else:
2144
+ return False
2145
+ return True
2146
+
2147
+
2148
+ def _ne(a, b):
2149
+ # use this as a second test after `a != b` if you want to make
2150
+ # sure that things are truly equal, e.g.
2151
+ # a, b = 0.5, S.Half
2152
+ # a !=b or _ne(a, b) -> True
2153
+ from .numbers import Number
2154
+ # 0.5 == S.Half
2155
+ if isinstance(a, Number) and isinstance(b, Number):
2156
+ return a.__class__ != b.__class__
2157
+
2158
+
2159
+ def _atomic(e, recursive=False):
2160
+ """Return atom-like quantities as far as substitution is
2161
+ concerned: Derivatives, Functions and Symbols. Do not
2162
+ return any 'atoms' that are inside such quantities unless
2163
+ they also appear outside, too, unless `recursive` is True.
2164
+
2165
+ Examples
2166
+ ========
2167
+
2168
+ >>> from sympy import Derivative, Function, cos
2169
+ >>> from sympy.abc import x, y
2170
+ >>> from sympy.core.basic import _atomic
2171
+ >>> f = Function('f')
2172
+ >>> _atomic(x + y)
2173
+ {x, y}
2174
+ >>> _atomic(x + f(y))
2175
+ {x, f(y)}
2176
+ >>> _atomic(Derivative(f(x), x) + cos(x) + y)
2177
+ {y, cos(x), Derivative(f(x), x)}
2178
+
2179
+ """
2180
+ pot = _preorder_traversal(e)
2181
+ seen = set()
2182
+ if isinstance(e, Basic):
2183
+ free = getattr(e, "free_symbols", None)
2184
+ if free is None:
2185
+ return {e}
2186
+ else:
2187
+ return set()
2188
+ from .symbol import Symbol
2189
+ from .function import Derivative, Function
2190
+ atoms = set()
2191
+ for p in pot:
2192
+ if p in seen:
2193
+ pot.skip()
2194
+ continue
2195
+ seen.add(p)
2196
+ if isinstance(p, Symbol) and p in free:
2197
+ atoms.add(p)
2198
+ elif isinstance(p, (Derivative, Function)):
2199
+ if not recursive:
2200
+ pot.skip()
2201
+ atoms.add(p)
2202
+ return atoms
2203
+
2204
+
2205
+ def _make_find_query(query):
2206
+ """Convert the argument of Basic.find() into a callable"""
2207
+ try:
2208
+ query = _sympify(query)
2209
+ except SympifyError:
2210
+ pass
2211
+ if isinstance(query, type):
2212
+ return lambda expr: isinstance(expr, query)
2213
+ elif isinstance(query, Basic):
2214
+ return lambda expr: expr.match(query) is not None
2215
+ return query
2216
+
2217
+ # Delayed to avoid cyclic import
2218
+ from .singleton import S
2219
+ from .traversal import (preorder_traversal as _preorder_traversal,
2220
+ iterargs, iterfreeargs)
2221
+
2222
+ preorder_traversal = deprecated(
2223
+ """
2224
+ Using preorder_traversal from the sympy.core.basic submodule is
2225
+ deprecated.
2226
+
2227
+ Instead, use preorder_traversal from the top-level sympy namespace, like
2228
+
2229
+ sympy.preorder_traversal
2230
+ """,
2231
+ deprecated_since_version="1.10",
2232
+ active_deprecations_target="deprecated-traversal-functions-moved",
2233
+ )(_preorder_traversal)
env-llmeval/lib/python3.10/site-packages/sympy/core/cache.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Caching facility for SymPy """
2
+ from importlib import import_module
3
+ from typing import Callable
4
+
5
+ class _cache(list):
6
+ """ List of cached functions """
7
+
8
+ def print_cache(self):
9
+ """print cache info"""
10
+
11
+ for item in self:
12
+ name = item.__name__
13
+ myfunc = item
14
+ while hasattr(myfunc, '__wrapped__'):
15
+ if hasattr(myfunc, 'cache_info'):
16
+ info = myfunc.cache_info()
17
+ break
18
+ else:
19
+ myfunc = myfunc.__wrapped__
20
+ else:
21
+ info = None
22
+
23
+ print(name, info)
24
+
25
+ def clear_cache(self):
26
+ """clear cache content"""
27
+ for item in self:
28
+ myfunc = item
29
+ while hasattr(myfunc, '__wrapped__'):
30
+ if hasattr(myfunc, 'cache_clear'):
31
+ myfunc.cache_clear()
32
+ break
33
+ else:
34
+ myfunc = myfunc.__wrapped__
35
+
36
+
37
+ # global cache registry:
38
+ CACHE = _cache()
39
+ # make clear and print methods available
40
+ print_cache = CACHE.print_cache
41
+ clear_cache = CACHE.clear_cache
42
+
43
+ from functools import lru_cache, wraps
44
+
45
+ def __cacheit(maxsize):
46
+ """caching decorator.
47
+
48
+ important: the result of cached function must be *immutable*
49
+
50
+
51
+ Examples
52
+ ========
53
+
54
+ >>> from sympy import cacheit
55
+ >>> @cacheit
56
+ ... def f(a, b):
57
+ ... return a+b
58
+
59
+ >>> @cacheit
60
+ ... def f(a, b): # noqa: F811
61
+ ... return [a, b] # <-- WRONG, returns mutable object
62
+
63
+ to force cacheit to check returned results mutability and consistency,
64
+ set environment variable SYMPY_USE_CACHE to 'debug'
65
+ """
66
+ def func_wrapper(func):
67
+ cfunc = lru_cache(maxsize, typed=True)(func)
68
+
69
+ @wraps(func)
70
+ def wrapper(*args, **kwargs):
71
+ try:
72
+ retval = cfunc(*args, **kwargs)
73
+ except TypeError as e:
74
+ if not e.args or not e.args[0].startswith('unhashable type:'):
75
+ raise
76
+ retval = func(*args, **kwargs)
77
+ return retval
78
+
79
+ wrapper.cache_info = cfunc.cache_info
80
+ wrapper.cache_clear = cfunc.cache_clear
81
+
82
+ CACHE.append(wrapper)
83
+ return wrapper
84
+
85
+ return func_wrapper
86
+ ########################################
87
+
88
+
89
+ def __cacheit_nocache(func):
90
+ return func
91
+
92
+
93
+ def __cacheit_debug(maxsize):
94
+ """cacheit + code to check cache consistency"""
95
+ def func_wrapper(func):
96
+ cfunc = __cacheit(maxsize)(func)
97
+
98
+ @wraps(func)
99
+ def wrapper(*args, **kw_args):
100
+ # always call function itself and compare it with cached version
101
+ r1 = func(*args, **kw_args)
102
+ r2 = cfunc(*args, **kw_args)
103
+
104
+ # try to see if the result is immutable
105
+ #
106
+ # this works because:
107
+ #
108
+ # hash([1,2,3]) -> raise TypeError
109
+ # hash({'a':1, 'b':2}) -> raise TypeError
110
+ # hash((1,[2,3])) -> raise TypeError
111
+ #
112
+ # hash((1,2,3)) -> just computes the hash
113
+ hash(r1), hash(r2)
114
+
115
+ # also see if returned values are the same
116
+ if r1 != r2:
117
+ raise RuntimeError("Returned values are not the same")
118
+ return r1
119
+ return wrapper
120
+ return func_wrapper
121
+
122
+
123
+ def _getenv(key, default=None):
124
+ from os import getenv
125
+ return getenv(key, default)
126
+
127
+ # SYMPY_USE_CACHE=yes/no/debug
128
+ USE_CACHE = _getenv('SYMPY_USE_CACHE', 'yes').lower()
129
+ # SYMPY_CACHE_SIZE=some_integer/None
130
+ # special cases :
131
+ # SYMPY_CACHE_SIZE=0 -> No caching
132
+ # SYMPY_CACHE_SIZE=None -> Unbounded caching
133
+ scs = _getenv('SYMPY_CACHE_SIZE', '1000')
134
+ if scs.lower() == 'none':
135
+ SYMPY_CACHE_SIZE = None
136
+ else:
137
+ try:
138
+ SYMPY_CACHE_SIZE = int(scs)
139
+ except ValueError:
140
+ raise RuntimeError(
141
+ 'SYMPY_CACHE_SIZE must be a valid integer or None. ' + \
142
+ 'Got: %s' % SYMPY_CACHE_SIZE)
143
+
144
+ if USE_CACHE == 'no':
145
+ cacheit = __cacheit_nocache
146
+ elif USE_CACHE == 'yes':
147
+ cacheit = __cacheit(SYMPY_CACHE_SIZE)
148
+ elif USE_CACHE == 'debug':
149
+ cacheit = __cacheit_debug(SYMPY_CACHE_SIZE) # a lot slower
150
+ else:
151
+ raise RuntimeError(
152
+ 'unrecognized value for SYMPY_USE_CACHE: %s' % USE_CACHE)
153
+
154
+
155
+ def cached_property(func):
156
+ '''Decorator to cache property method'''
157
+ attrname = '__' + func.__name__
158
+ _cached_property_sentinel = object()
159
+ def propfunc(self):
160
+ val = getattr(self, attrname, _cached_property_sentinel)
161
+ if val is _cached_property_sentinel:
162
+ val = func(self)
163
+ setattr(self, attrname, val)
164
+ return val
165
+ return property(propfunc)
166
+
167
+
168
+ def lazy_function(module : str, name : str) -> Callable:
169
+ """Create a lazy proxy for a function in a module.
170
+
171
+ The module containing the function is not imported until the function is used.
172
+
173
+ """
174
+ func = None
175
+
176
+ def _get_function():
177
+ nonlocal func
178
+ if func is None:
179
+ func = getattr(import_module(module), name)
180
+ return func
181
+
182
+ # The metaclass is needed so that help() shows the docstring
183
+ class LazyFunctionMeta(type):
184
+ @property
185
+ def __doc__(self):
186
+ docstring = _get_function().__doc__
187
+ docstring += f"\n\nNote: this is a {self.__class__.__name__} wrapper of '{module}.{name}'"
188
+ return docstring
189
+
190
+ class LazyFunction(metaclass=LazyFunctionMeta):
191
+ def __call__(self, *args, **kwargs):
192
+ # inline get of function for performance gh-23832
193
+ nonlocal func
194
+ if func is None:
195
+ func = getattr(import_module(module), name)
196
+ return func(*args, **kwargs)
197
+
198
+ @property
199
+ def __doc__(self):
200
+ docstring = _get_function().__doc__
201
+ docstring += f"\n\nNote: this is a {self.__class__.__name__} wrapper of '{module}.{name}'"
202
+ return docstring
203
+
204
+ def __str__(self):
205
+ return _get_function().__str__()
206
+
207
+ def __repr__(self):
208
+ return f"<{__class__.__name__} object at 0x{id(self):x}>: wrapping '{module}.{name}'"
209
+
210
+ return LazyFunction()
env-llmeval/lib/python3.10/site-packages/sympy/core/compatibility.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. deprecated:: 1.10
3
+
4
+ ``sympy.core.compatibility`` is deprecated. See
5
+ :ref:`sympy-core-compatibility`.
6
+
7
+ Reimplementations of constructs introduced in later versions of Python than
8
+ we support. Also some functions that are needed SymPy-wide and are located
9
+ here for easy import.
10
+
11
+ """
12
+
13
+
14
+ from sympy.utilities.exceptions import sympy_deprecation_warning
15
+
16
+ sympy_deprecation_warning("""
17
+ The sympy.core.compatibility submodule is deprecated.
18
+
19
+ This module was only ever intended for internal use. Some of the functions
20
+ that were in this module are available from the top-level SymPy namespace,
21
+ i.e.,
22
+
23
+ from sympy import ordered, default_sort_key
24
+
25
+ The remaining were only intended for internal SymPy use and should not be used
26
+ by user code.
27
+ """,
28
+ deprecated_since_version="1.10",
29
+ active_deprecations_target="deprecated-sympy-core-compatibility",
30
+ )
31
+
32
+
33
+ from .sorting import ordered, _nodes, default_sort_key # noqa:F401
34
+ from sympy.utilities.misc import as_int as _as_int # noqa:F401
35
+ from sympy.utilities.iterables import iterable, is_sequence, NotIterable # noqa:F401
env-llmeval/lib/python3.10/site-packages/sympy/core/containers.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module for SymPy containers
2
+
3
+ (SymPy objects that store other SymPy objects)
4
+
5
+ The containers implemented in this module are subclassed to Basic.
6
+ They are supposed to work seamlessly within the SymPy framework.
7
+ """
8
+
9
+ from collections import OrderedDict
10
+ from collections.abc import MutableSet
11
+ from typing import Any, Callable
12
+
13
+ from .basic import Basic
14
+ from .sorting import default_sort_key, ordered
15
+ from .sympify import _sympify, sympify, _sympy_converter, SympifyError
16
+ from sympy.core.kind import Kind
17
+ from sympy.utilities.iterables import iterable
18
+ from sympy.utilities.misc import as_int
19
+
20
+
21
+ class Tuple(Basic):
22
+ """
23
+ Wrapper around the builtin tuple object.
24
+
25
+ Explanation
26
+ ===========
27
+
28
+ The Tuple is a subclass of Basic, so that it works well in the
29
+ SymPy framework. The wrapped tuple is available as self.args, but
30
+ you can also access elements or slices with [:] syntax.
31
+
32
+ Parameters
33
+ ==========
34
+
35
+ sympify : bool
36
+ If ``False``, ``sympify`` is not called on ``args``. This
37
+ can be used for speedups for very large tuples where the
38
+ elements are known to already be SymPy objects.
39
+
40
+ Examples
41
+ ========
42
+
43
+ >>> from sympy import Tuple, symbols
44
+ >>> a, b, c, d = symbols('a b c d')
45
+ >>> Tuple(a, b, c)[1:]
46
+ (b, c)
47
+ >>> Tuple(a, b, c).subs(a, d)
48
+ (d, b, c)
49
+
50
+ """
51
+
52
+ def __new__(cls, *args, **kwargs):
53
+ if kwargs.get('sympify', True):
54
+ args = (sympify(arg) for arg in args)
55
+ obj = Basic.__new__(cls, *args)
56
+ return obj
57
+
58
+ def __getitem__(self, i):
59
+ if isinstance(i, slice):
60
+ indices = i.indices(len(self))
61
+ return Tuple(*(self.args[j] for j in range(*indices)))
62
+ return self.args[i]
63
+
64
+ def __len__(self):
65
+ return len(self.args)
66
+
67
+ def __contains__(self, item):
68
+ return item in self.args
69
+
70
+ def __iter__(self):
71
+ return iter(self.args)
72
+
73
+ def __add__(self, other):
74
+ if isinstance(other, Tuple):
75
+ return Tuple(*(self.args + other.args))
76
+ elif isinstance(other, tuple):
77
+ return Tuple(*(self.args + other))
78
+ else:
79
+ return NotImplemented
80
+
81
+ def __radd__(self, other):
82
+ if isinstance(other, Tuple):
83
+ return Tuple(*(other.args + self.args))
84
+ elif isinstance(other, tuple):
85
+ return Tuple(*(other + self.args))
86
+ else:
87
+ return NotImplemented
88
+
89
+ def __mul__(self, other):
90
+ try:
91
+ n = as_int(other)
92
+ except ValueError:
93
+ raise TypeError("Can't multiply sequence by non-integer of type '%s'" % type(other))
94
+ return self.func(*(self.args*n))
95
+
96
+ __rmul__ = __mul__
97
+
98
+ def __eq__(self, other):
99
+ if isinstance(other, Basic):
100
+ return super().__eq__(other)
101
+ return self.args == other
102
+
103
+ def __ne__(self, other):
104
+ if isinstance(other, Basic):
105
+ return super().__ne__(other)
106
+ return self.args != other
107
+
108
+ def __hash__(self):
109
+ return hash(self.args)
110
+
111
+ def _to_mpmath(self, prec):
112
+ return tuple(a._to_mpmath(prec) for a in self.args)
113
+
114
+ def __lt__(self, other):
115
+ return _sympify(self.args < other.args)
116
+
117
+ def __le__(self, other):
118
+ return _sympify(self.args <= other.args)
119
+
120
+ # XXX: Basic defines count() as something different, so we can't
121
+ # redefine it here. Originally this lead to cse() test failure.
122
+ def tuple_count(self, value) -> int:
123
+ """Return number of occurrences of value."""
124
+ return self.args.count(value)
125
+
126
+ def index(self, value, start=None, stop=None):
127
+ """Searches and returns the first index of the value."""
128
+ # XXX: One would expect:
129
+ #
130
+ # return self.args.index(value, start, stop)
131
+ #
132
+ # here. Any trouble with that? Yes:
133
+ #
134
+ # >>> (1,).index(1, None, None)
135
+ # Traceback (most recent call last):
136
+ # File "<stdin>", line 1, in <module>
137
+ # TypeError: slice indices must be integers or None or have an __index__ method
138
+ #
139
+ # See: http://bugs.python.org/issue13340
140
+
141
+ if start is None and stop is None:
142
+ return self.args.index(value)
143
+ elif stop is None:
144
+ return self.args.index(value, start)
145
+ else:
146
+ return self.args.index(value, start, stop)
147
+
148
+ @property
149
+ def kind(self):
150
+ """
151
+ The kind of a Tuple instance.
152
+
153
+ The kind of a Tuple is always of :class:`TupleKind` but
154
+ parametrised by the number of elements and the kind of each element.
155
+
156
+ Examples
157
+ ========
158
+
159
+ >>> from sympy import Tuple, Matrix
160
+ >>> Tuple(1, 2).kind
161
+ TupleKind(NumberKind, NumberKind)
162
+ >>> Tuple(Matrix([1, 2]), 1).kind
163
+ TupleKind(MatrixKind(NumberKind), NumberKind)
164
+ >>> Tuple(1, 2).kind.element_kind
165
+ (NumberKind, NumberKind)
166
+
167
+ See Also
168
+ ========
169
+
170
+ sympy.matrices.common.MatrixKind
171
+ sympy.core.kind.NumberKind
172
+ """
173
+ return TupleKind(*(i.kind for i in self.args))
174
+
175
+ _sympy_converter[tuple] = lambda tup: Tuple(*tup)
176
+
177
+
178
+
179
+
180
+
181
+ def tuple_wrapper(method):
182
+ """
183
+ Decorator that converts any tuple in the function arguments into a Tuple.
184
+
185
+ Explanation
186
+ ===========
187
+
188
+ The motivation for this is to provide simple user interfaces. The user can
189
+ call a function with regular tuples in the argument, and the wrapper will
190
+ convert them to Tuples before handing them to the function.
191
+
192
+ Explanation
193
+ ===========
194
+
195
+ >>> from sympy.core.containers import tuple_wrapper
196
+ >>> def f(*args):
197
+ ... return args
198
+ >>> g = tuple_wrapper(f)
199
+
200
+ The decorated function g sees only the Tuple argument:
201
+
202
+ >>> g(0, (1, 2), 3)
203
+ (0, (1, 2), 3)
204
+
205
+ """
206
+ def wrap_tuples(*args, **kw_args):
207
+ newargs = []
208
+ for arg in args:
209
+ if isinstance(arg, tuple):
210
+ newargs.append(Tuple(*arg))
211
+ else:
212
+ newargs.append(arg)
213
+ return method(*newargs, **kw_args)
214
+ return wrap_tuples
215
+
216
+
217
+ class Dict(Basic):
218
+ """
219
+ Wrapper around the builtin dict object.
220
+
221
+ Explanation
222
+ ===========
223
+
224
+ The Dict is a subclass of Basic, so that it works well in the
225
+ SymPy framework. Because it is immutable, it may be included
226
+ in sets, but its values must all be given at instantiation and
227
+ cannot be changed afterwards. Otherwise it behaves identically
228
+ to the Python dict.
229
+
230
+ Examples
231
+ ========
232
+
233
+ >>> from sympy import Dict, Symbol
234
+
235
+ >>> D = Dict({1: 'one', 2: 'two'})
236
+ >>> for key in D:
237
+ ... if key == 1:
238
+ ... print('%s %s' % (key, D[key]))
239
+ 1 one
240
+
241
+ The args are sympified so the 1 and 2 are Integers and the values
242
+ are Symbols. Queries automatically sympify args so the following work:
243
+
244
+ >>> 1 in D
245
+ True
246
+ >>> D.has(Symbol('one')) # searches keys and values
247
+ True
248
+ >>> 'one' in D # not in the keys
249
+ False
250
+ >>> D[1]
251
+ one
252
+
253
+ """
254
+
255
+ def __new__(cls, *args):
256
+ if len(args) == 1 and isinstance(args[0], (dict, Dict)):
257
+ items = [Tuple(k, v) for k, v in args[0].items()]
258
+ elif iterable(args) and all(len(arg) == 2 for arg in args):
259
+ items = [Tuple(k, v) for k, v in args]
260
+ else:
261
+ raise TypeError('Pass Dict args as Dict((k1, v1), ...) or Dict({k1: v1, ...})')
262
+ elements = frozenset(items)
263
+ obj = Basic.__new__(cls, *ordered(items))
264
+ obj.elements = elements
265
+ obj._dict = dict(items) # In case Tuple decides it wants to sympify
266
+ return obj
267
+
268
+ def __getitem__(self, key):
269
+ """x.__getitem__(y) <==> x[y]"""
270
+ try:
271
+ key = _sympify(key)
272
+ except SympifyError:
273
+ raise KeyError(key)
274
+
275
+ return self._dict[key]
276
+
277
+ def __setitem__(self, key, value):
278
+ raise NotImplementedError("SymPy Dicts are Immutable")
279
+
280
+ def items(self):
281
+ '''Returns a set-like object providing a view on dict's items.
282
+ '''
283
+ return self._dict.items()
284
+
285
+ def keys(self):
286
+ '''Returns the list of the dict's keys.'''
287
+ return self._dict.keys()
288
+
289
+ def values(self):
290
+ '''Returns the list of the dict's values.'''
291
+ return self._dict.values()
292
+
293
+ def __iter__(self):
294
+ '''x.__iter__() <==> iter(x)'''
295
+ return iter(self._dict)
296
+
297
+ def __len__(self):
298
+ '''x.__len__() <==> len(x)'''
299
+ return self._dict.__len__()
300
+
301
+ def get(self, key, default=None):
302
+ '''Returns the value for key if the key is in the dictionary.'''
303
+ try:
304
+ key = _sympify(key)
305
+ except SympifyError:
306
+ return default
307
+ return self._dict.get(key, default)
308
+
309
+ def __contains__(self, key):
310
+ '''D.__contains__(k) -> True if D has a key k, else False'''
311
+ try:
312
+ key = _sympify(key)
313
+ except SympifyError:
314
+ return False
315
+ return key in self._dict
316
+
317
+ def __lt__(self, other):
318
+ return _sympify(self.args < other.args)
319
+
320
+ @property
321
+ def _sorted_args(self):
322
+ return tuple(sorted(self.args, key=default_sort_key))
323
+
324
+ def __eq__(self, other):
325
+ if isinstance(other, dict):
326
+ return self == Dict(other)
327
+ return super().__eq__(other)
328
+
329
+ __hash__ : Callable[[Basic], Any] = Basic.__hash__
330
+
331
+ # this handles dict, defaultdict, OrderedDict
332
+ _sympy_converter[dict] = lambda d: Dict(*d.items())
333
+
334
+ class OrderedSet(MutableSet):
335
+ def __init__(self, iterable=None):
336
+ if iterable:
337
+ self.map = OrderedDict((item, None) for item in iterable)
338
+ else:
339
+ self.map = OrderedDict()
340
+
341
+ def __len__(self):
342
+ return len(self.map)
343
+
344
+ def __contains__(self, key):
345
+ return key in self.map
346
+
347
+ def add(self, key):
348
+ self.map[key] = None
349
+
350
+ def discard(self, key):
351
+ self.map.pop(key)
352
+
353
+ def pop(self, last=True):
354
+ return self.map.popitem(last=last)[0]
355
+
356
+ def __iter__(self):
357
+ yield from self.map.keys()
358
+
359
+ def __repr__(self):
360
+ if not self.map:
361
+ return '%s()' % (self.__class__.__name__,)
362
+ return '%s(%r)' % (self.__class__.__name__, list(self.map.keys()))
363
+
364
+ def intersection(self, other):
365
+ return self.__class__([val for val in self if val in other])
366
+
367
+ def difference(self, other):
368
+ return self.__class__([val for val in self if val not in other])
369
+
370
+ def update(self, iterable):
371
+ for val in iterable:
372
+ self.add(val)
373
+
374
+ class TupleKind(Kind):
375
+ """
376
+ TupleKind is a subclass of Kind, which is used to define Kind of ``Tuple``.
377
+
378
+ Parameters of TupleKind will be kinds of all the arguments in Tuples, for
379
+ example
380
+
381
+ Parameters
382
+ ==========
383
+
384
+ args : tuple(element_kind)
385
+ element_kind is kind of element.
386
+ args is tuple of kinds of element
387
+
388
+ Examples
389
+ ========
390
+
391
+ >>> from sympy import Tuple
392
+ >>> Tuple(1, 2).kind
393
+ TupleKind(NumberKind, NumberKind)
394
+ >>> Tuple(1, 2).kind.element_kind
395
+ (NumberKind, NumberKind)
396
+
397
+ See Also
398
+ ========
399
+
400
+ sympy.core.kind.NumberKind
401
+ MatrixKind
402
+ sympy.sets.sets.SetKind
403
+ """
404
+ def __new__(cls, *args):
405
+ obj = super().__new__(cls, *args)
406
+ obj.element_kind = args
407
+ return obj
408
+
409
+ def __repr__(self):
410
+ return "TupleKind{}".format(self.element_kind)
env-llmeval/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)
env-llmeval/lib/python3.10/site-packages/sympy/core/coreerrors.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """Definitions of common exceptions for :mod:`sympy.core` module. """
2
+
3
+
4
+ class BaseCoreError(Exception):
5
+ """Base class for core related exceptions. """
6
+
7
+
8
+ class NonCommutativeExpression(BaseCoreError):
9
+ """Raised when expression didn't have commutative property. """
env-llmeval/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)
env-llmeval/lib/python3.10/site-packages/sympy/core/exprtools.py ADDED
@@ -0,0 +1,1569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools for manipulating of large commutative expressions. """
2
+
3
+ from .add import Add
4
+ from .mul import Mul, _keep_coeff
5
+ from .power import Pow
6
+ from .basic import Basic
7
+ from .expr import Expr
8
+ from .function import expand_power_exp
9
+ from .sympify import sympify
10
+ from .numbers import Rational, Integer, Number, I, equal_valued
11
+ from .singleton import S
12
+ from .sorting import default_sort_key, ordered
13
+ from .symbol import Dummy
14
+ from .traversal import preorder_traversal
15
+ from .coreerrors import NonCommutativeExpression
16
+ from .containers import Tuple, Dict
17
+ from sympy.external.gmpy import SYMPY_INTS
18
+ from sympy.utilities.iterables import (common_prefix, common_suffix,
19
+ variations, iterable, is_sequence)
20
+
21
+ from collections import defaultdict
22
+ from typing import Tuple as tTuple
23
+
24
+
25
+ _eps = Dummy(positive=True)
26
+
27
+
28
+ def _isnumber(i):
29
+ return isinstance(i, (SYMPY_INTS, float)) or i.is_Number
30
+
31
+
32
+ def _monotonic_sign(self):
33
+ """Return the value closest to 0 that ``self`` may have if all symbols
34
+ are signed and the result is uniformly the same sign for all values of symbols.
35
+ If a symbol is only signed but not known to be an
36
+ integer or the result is 0 then a symbol representative of the sign of self
37
+ will be returned. Otherwise, None is returned if a) the sign could be positive
38
+ or negative or b) self is not in one of the following forms:
39
+
40
+ - L(x, y, ...) + A: a function linear in all symbols x, y, ... with an
41
+ additive constant; if A is zero then the function can be a monomial whose
42
+ sign is monotonic over the range of the variables, e.g. (x + 1)**3 if x is
43
+ nonnegative.
44
+ - A/L(x, y, ...) + B: the inverse of a function linear in all symbols x, y, ...
45
+ that does not have a sign change from positive to negative for any set
46
+ of values for the variables.
47
+ - M(x, y, ...) + A: a monomial M whose factors are all signed and a constant, A.
48
+ - A/M(x, y, ...) + B: the inverse of a monomial and constants A and B.
49
+ - P(x): a univariate polynomial
50
+
51
+ Examples
52
+ ========
53
+
54
+ >>> from sympy.core.exprtools import _monotonic_sign as F
55
+ >>> from sympy import Dummy
56
+ >>> nn = Dummy(integer=True, nonnegative=True)
57
+ >>> p = Dummy(integer=True, positive=True)
58
+ >>> p2 = Dummy(integer=True, positive=True)
59
+ >>> F(nn + 1)
60
+ 1
61
+ >>> F(p - 1)
62
+ _nneg
63
+ >>> F(nn*p + 1)
64
+ 1
65
+ >>> F(p2*p + 1)
66
+ 2
67
+ >>> F(nn - 1) # could be negative, zero or positive
68
+ """
69
+ if not self.is_extended_real:
70
+ return
71
+
72
+ if (-self).is_Symbol:
73
+ rv = _monotonic_sign(-self)
74
+ return rv if rv is None else -rv
75
+
76
+ if not self.is_Add and self.as_numer_denom()[1].is_number:
77
+ s = self
78
+ if s.is_prime:
79
+ if s.is_odd:
80
+ return Integer(3)
81
+ else:
82
+ return Integer(2)
83
+ elif s.is_composite:
84
+ if s.is_odd:
85
+ return Integer(9)
86
+ else:
87
+ return Integer(4)
88
+ elif s.is_positive:
89
+ if s.is_even:
90
+ if s.is_prime is False:
91
+ return Integer(4)
92
+ else:
93
+ return Integer(2)
94
+ elif s.is_integer:
95
+ return S.One
96
+ else:
97
+ return _eps
98
+ elif s.is_extended_negative:
99
+ if s.is_even:
100
+ return Integer(-2)
101
+ elif s.is_integer:
102
+ return S.NegativeOne
103
+ else:
104
+ return -_eps
105
+ if s.is_zero or s.is_extended_nonpositive or s.is_extended_nonnegative:
106
+ return S.Zero
107
+ return None
108
+
109
+ # univariate polynomial
110
+ free = self.free_symbols
111
+ if len(free) == 1:
112
+ if self.is_polynomial():
113
+ from sympy.polys.polytools import real_roots
114
+ from sympy.polys.polyroots import roots
115
+ from sympy.polys.polyerrors import PolynomialError
116
+ x = free.pop()
117
+ x0 = _monotonic_sign(x)
118
+ if x0 in (_eps, -_eps):
119
+ x0 = S.Zero
120
+ if x0 is not None:
121
+ d = self.diff(x)
122
+ if d.is_number:
123
+ currentroots = []
124
+ else:
125
+ try:
126
+ currentroots = real_roots(d)
127
+ except (PolynomialError, NotImplementedError):
128
+ currentroots = [r for r in roots(d, x) if r.is_extended_real]
129
+ y = self.subs(x, x0)
130
+ if x.is_nonnegative and all(
131
+ (r - x0).is_nonpositive for r in currentroots):
132
+ if y.is_nonnegative and d.is_positive:
133
+ if y:
134
+ return y if y.is_positive else Dummy('pos', positive=True)
135
+ else:
136
+ return Dummy('nneg', nonnegative=True)
137
+ if y.is_nonpositive and d.is_negative:
138
+ if y:
139
+ return y if y.is_negative else Dummy('neg', negative=True)
140
+ else:
141
+ return Dummy('npos', nonpositive=True)
142
+ elif x.is_nonpositive and all(
143
+ (r - x0).is_nonnegative for r in currentroots):
144
+ if y.is_nonnegative and d.is_negative:
145
+ if y:
146
+ return Dummy('pos', positive=True)
147
+ else:
148
+ return Dummy('nneg', nonnegative=True)
149
+ if y.is_nonpositive and d.is_positive:
150
+ if y:
151
+ return Dummy('neg', negative=True)
152
+ else:
153
+ return Dummy('npos', nonpositive=True)
154
+ else:
155
+ n, d = self.as_numer_denom()
156
+ den = None
157
+ if n.is_number:
158
+ den = _monotonic_sign(d)
159
+ elif not d.is_number:
160
+ if _monotonic_sign(n) is not None:
161
+ den = _monotonic_sign(d)
162
+ if den is not None and (den.is_positive or den.is_negative):
163
+ v = n*den
164
+ if v.is_positive:
165
+ return Dummy('pos', positive=True)
166
+ elif v.is_nonnegative:
167
+ return Dummy('nneg', nonnegative=True)
168
+ elif v.is_negative:
169
+ return Dummy('neg', negative=True)
170
+ elif v.is_nonpositive:
171
+ return Dummy('npos', nonpositive=True)
172
+ return None
173
+
174
+ # multivariate
175
+ c, a = self.as_coeff_Add()
176
+ v = None
177
+ if not a.is_polynomial():
178
+ # F/A or A/F where A is a number and F is a signed, rational monomial
179
+ n, d = a.as_numer_denom()
180
+ if not (n.is_number or d.is_number):
181
+ return
182
+ if (
183
+ a.is_Mul or a.is_Pow) and \
184
+ a.is_rational and \
185
+ all(p.exp.is_Integer for p in a.atoms(Pow) if p.is_Pow) and \
186
+ (a.is_positive or a.is_negative):
187
+ v = S.One
188
+ for ai in Mul.make_args(a):
189
+ if ai.is_number:
190
+ v *= ai
191
+ continue
192
+ reps = {}
193
+ for x in ai.free_symbols:
194
+ reps[x] = _monotonic_sign(x)
195
+ if reps[x] is None:
196
+ return
197
+ v *= ai.subs(reps)
198
+ elif c:
199
+ # signed linear expression
200
+ if not any(p for p in a.atoms(Pow) if not p.is_number) and (a.is_nonpositive or a.is_nonnegative):
201
+ free = list(a.free_symbols)
202
+ p = {}
203
+ for i in free:
204
+ v = _monotonic_sign(i)
205
+ if v is None:
206
+ return
207
+ p[i] = v or (_eps if i.is_nonnegative else -_eps)
208
+ v = a.xreplace(p)
209
+ if v is not None:
210
+ rv = v + c
211
+ if v.is_nonnegative and rv.is_positive:
212
+ return rv.subs(_eps, 0)
213
+ if v.is_nonpositive and rv.is_negative:
214
+ return rv.subs(_eps, 0)
215
+
216
+
217
+ def decompose_power(expr: Expr) -> tTuple[Expr, int]:
218
+ """
219
+ Decompose power into symbolic base and integer exponent.
220
+
221
+ Examples
222
+ ========
223
+
224
+ >>> from sympy.core.exprtools import decompose_power
225
+ >>> from sympy.abc import x, y
226
+ >>> from sympy import exp
227
+
228
+ >>> decompose_power(x)
229
+ (x, 1)
230
+ >>> decompose_power(x**2)
231
+ (x, 2)
232
+ >>> decompose_power(exp(2*y/3))
233
+ (exp(y/3), 2)
234
+
235
+ """
236
+ base, exp = expr.as_base_exp()
237
+
238
+ if exp.is_Number:
239
+ if exp.is_Rational:
240
+ if not exp.is_Integer:
241
+ base = Pow(base, Rational(1, exp.q)) # type: ignore
242
+ e = exp.p # type: ignore
243
+ else:
244
+ base, e = expr, 1
245
+ else:
246
+ exp, tail = exp.as_coeff_Mul(rational=True)
247
+
248
+ if exp is S.NegativeOne:
249
+ base, e = Pow(base, tail), -1
250
+ elif exp is not S.One:
251
+ # todo: after dropping python 3.7 support, use overload and Literal
252
+ # in as_coeff_Mul to make exp Rational, and remove these 2 ignores
253
+ tail = _keep_coeff(Rational(1, exp.q), tail) # type: ignore
254
+ base, e = Pow(base, tail), exp.p # type: ignore
255
+ else:
256
+ base, e = expr, 1
257
+
258
+ return base, e
259
+
260
+
261
+ def decompose_power_rat(expr: Expr) -> tTuple[Expr, Rational]:
262
+ """
263
+ Decompose power into symbolic base and rational exponent;
264
+ if the exponent is not a Rational, then separate only the
265
+ integer coefficient.
266
+
267
+ Examples
268
+ ========
269
+
270
+ >>> from sympy.core.exprtools import decompose_power_rat
271
+ >>> from sympy.abc import x
272
+ >>> from sympy import sqrt, exp
273
+
274
+ >>> decompose_power_rat(sqrt(x))
275
+ (x, 1/2)
276
+ >>> decompose_power_rat(exp(-3*x/2))
277
+ (exp(x/2), -3)
278
+
279
+ """
280
+ _ = base, exp = expr.as_base_exp()
281
+ return _ if exp.is_Rational else decompose_power(expr)
282
+
283
+
284
+ class Factors:
285
+ """Efficient representation of ``f_1*f_2*...*f_n``."""
286
+
287
+ __slots__ = ('factors', 'gens')
288
+
289
+ def __init__(self, factors=None): # Factors
290
+ """Initialize Factors from dict or expr.
291
+
292
+ Examples
293
+ ========
294
+
295
+ >>> from sympy.core.exprtools import Factors
296
+ >>> from sympy.abc import x
297
+ >>> from sympy import I
298
+ >>> e = 2*x**3
299
+ >>> Factors(e)
300
+ Factors({2: 1, x: 3})
301
+ >>> Factors(e.as_powers_dict())
302
+ Factors({2: 1, x: 3})
303
+ >>> f = _
304
+ >>> f.factors # underlying dictionary
305
+ {2: 1, x: 3}
306
+ >>> f.gens # base of each factor
307
+ frozenset({2, x})
308
+ >>> Factors(0)
309
+ Factors({0: 1})
310
+ >>> Factors(I)
311
+ Factors({I: 1})
312
+
313
+ Notes
314
+ =====
315
+
316
+ Although a dictionary can be passed, only minimal checking is
317
+ performed: powers of -1 and I are made canonical.
318
+
319
+ """
320
+ if isinstance(factors, (SYMPY_INTS, float)):
321
+ factors = S(factors)
322
+ if isinstance(factors, Factors):
323
+ factors = factors.factors.copy()
324
+ elif factors in (None, S.One):
325
+ factors = {}
326
+ elif factors is S.Zero or factors == 0:
327
+ factors = {S.Zero: S.One}
328
+ elif isinstance(factors, Number):
329
+ n = factors
330
+ factors = {}
331
+ if n < 0:
332
+ factors[S.NegativeOne] = S.One
333
+ n = -n
334
+ if n is not S.One:
335
+ if n.is_Float or n.is_Integer or n is S.Infinity:
336
+ factors[n] = S.One
337
+ elif n.is_Rational:
338
+ # since we're processing Numbers, the denominator is
339
+ # stored with a negative exponent; all other factors
340
+ # are left .
341
+ if n.p != 1:
342
+ factors[Integer(n.p)] = S.One
343
+ factors[Integer(n.q)] = S.NegativeOne
344
+ else:
345
+ raise ValueError('Expected Float|Rational|Integer, not %s' % n)
346
+ elif isinstance(factors, Basic) and not factors.args:
347
+ factors = {factors: S.One}
348
+ elif isinstance(factors, Expr):
349
+ c, nc = factors.args_cnc()
350
+ i = c.count(I)
351
+ for _ in range(i):
352
+ c.remove(I)
353
+ factors = dict(Mul._from_args(c).as_powers_dict())
354
+ # Handle all rational Coefficients
355
+ for f in list(factors.keys()):
356
+ if isinstance(f, Rational) and not isinstance(f, Integer):
357
+ p, q = Integer(f.p), Integer(f.q)
358
+ factors[p] = (factors[p] if p in factors else S.Zero) + factors[f]
359
+ factors[q] = (factors[q] if q in factors else S.Zero) - factors[f]
360
+ factors.pop(f)
361
+ if i:
362
+ factors[I] = factors.get(I, S.Zero) + i
363
+ if nc:
364
+ factors[Mul(*nc, evaluate=False)] = S.One
365
+ else:
366
+ factors = factors.copy() # /!\ should be dict-like
367
+
368
+ # tidy up -/+1 and I exponents if Rational
369
+
370
+ handle = [k for k in factors if k is I or k in (-1, 1)]
371
+ if handle:
372
+ i1 = S.One
373
+ for k in handle:
374
+ if not _isnumber(factors[k]):
375
+ continue
376
+ i1 *= k**factors.pop(k)
377
+ if i1 is not S.One:
378
+ for a in i1.args if i1.is_Mul else [i1]: # at worst, -1.0*I*(-1)**e
379
+ if a is S.NegativeOne:
380
+ factors[a] = S.One
381
+ elif a is I:
382
+ factors[I] = S.One
383
+ elif a.is_Pow:
384
+ factors[a.base] = factors.get(a.base, S.Zero) + a.exp
385
+ elif equal_valued(a, 1):
386
+ factors[a] = S.One
387
+ elif equal_valued(a, -1):
388
+ factors[-a] = S.One
389
+ factors[S.NegativeOne] = S.One
390
+ else:
391
+ raise ValueError('unexpected factor in i1: %s' % a)
392
+
393
+ self.factors = factors
394
+ keys = getattr(factors, 'keys', None)
395
+ if keys is None:
396
+ raise TypeError('expecting Expr or dictionary')
397
+ self.gens = frozenset(keys())
398
+
399
+ def __hash__(self): # Factors
400
+ keys = tuple(ordered(self.factors.keys()))
401
+ values = [self.factors[k] for k in keys]
402
+ return hash((keys, values))
403
+
404
+ def __repr__(self): # Factors
405
+ return "Factors({%s})" % ', '.join(
406
+ ['%s: %s' % (k, v) for k, v in ordered(self.factors.items())])
407
+
408
+ @property
409
+ def is_zero(self): # Factors
410
+ """
411
+ >>> from sympy.core.exprtools import Factors
412
+ >>> Factors(0).is_zero
413
+ True
414
+ """
415
+ f = self.factors
416
+ return len(f) == 1 and S.Zero in f
417
+
418
+ @property
419
+ def is_one(self): # Factors
420
+ """
421
+ >>> from sympy.core.exprtools import Factors
422
+ >>> Factors(1).is_one
423
+ True
424
+ """
425
+ return not self.factors
426
+
427
+ def as_expr(self): # Factors
428
+ """Return the underlying expression.
429
+
430
+ Examples
431
+ ========
432
+
433
+ >>> from sympy.core.exprtools import Factors
434
+ >>> from sympy.abc import x, y
435
+ >>> Factors((x*y**2).as_powers_dict()).as_expr()
436
+ x*y**2
437
+
438
+ """
439
+
440
+ args = []
441
+ for factor, exp in self.factors.items():
442
+ if exp != 1:
443
+ if isinstance(exp, Integer):
444
+ b, e = factor.as_base_exp()
445
+ e = _keep_coeff(exp, e)
446
+ args.append(b**e)
447
+ else:
448
+ args.append(factor**exp)
449
+ else:
450
+ args.append(factor)
451
+ return Mul(*args)
452
+
453
+ def mul(self, other): # Factors
454
+ """Return Factors of ``self * other``.
455
+
456
+ Examples
457
+ ========
458
+
459
+ >>> from sympy.core.exprtools import Factors
460
+ >>> from sympy.abc import x, y, z
461
+ >>> a = Factors((x*y**2).as_powers_dict())
462
+ >>> b = Factors((x*y/z).as_powers_dict())
463
+ >>> a.mul(b)
464
+ Factors({x: 2, y: 3, z: -1})
465
+ >>> a*b
466
+ Factors({x: 2, y: 3, z: -1})
467
+ """
468
+ if not isinstance(other, Factors):
469
+ other = Factors(other)
470
+ if any(f.is_zero for f in (self, other)):
471
+ return Factors(S.Zero)
472
+ factors = dict(self.factors)
473
+
474
+ for factor, exp in other.factors.items():
475
+ if factor in factors:
476
+ exp = factors[factor] + exp
477
+
478
+ if not exp:
479
+ del factors[factor]
480
+ continue
481
+
482
+ factors[factor] = exp
483
+
484
+ return Factors(factors)
485
+
486
+ def normal(self, other):
487
+ """Return ``self`` and ``other`` with ``gcd`` removed from each.
488
+ The only differences between this and method ``div`` is that this
489
+ is 1) optimized for the case when there are few factors in common and
490
+ 2) this does not raise an error if ``other`` is zero.
491
+
492
+ See Also
493
+ ========
494
+ div
495
+
496
+ """
497
+ if not isinstance(other, Factors):
498
+ other = Factors(other)
499
+ if other.is_zero:
500
+ return (Factors(), Factors(S.Zero))
501
+ if self.is_zero:
502
+ return (Factors(S.Zero), Factors())
503
+
504
+ self_factors = dict(self.factors)
505
+ other_factors = dict(other.factors)
506
+
507
+ for factor, self_exp in self.factors.items():
508
+ try:
509
+ other_exp = other.factors[factor]
510
+ except KeyError:
511
+ continue
512
+
513
+ exp = self_exp - other_exp
514
+
515
+ if not exp:
516
+ del self_factors[factor]
517
+ del other_factors[factor]
518
+ elif _isnumber(exp):
519
+ if exp > 0:
520
+ self_factors[factor] = exp
521
+ del other_factors[factor]
522
+ else:
523
+ del self_factors[factor]
524
+ other_factors[factor] = -exp
525
+ else:
526
+ r = self_exp.extract_additively(other_exp)
527
+ if r is not None:
528
+ if r:
529
+ self_factors[factor] = r
530
+ del other_factors[factor]
531
+ else: # should be handled already
532
+ del self_factors[factor]
533
+ del other_factors[factor]
534
+ else:
535
+ sc, sa = self_exp.as_coeff_Add()
536
+ if sc:
537
+ oc, oa = other_exp.as_coeff_Add()
538
+ diff = sc - oc
539
+ if diff > 0:
540
+ self_factors[factor] -= oc
541
+ other_exp = oa
542
+ elif diff < 0:
543
+ self_factors[factor] -= sc
544
+ other_factors[factor] -= sc
545
+ other_exp = oa - diff
546
+ else:
547
+ self_factors[factor] = sa
548
+ other_exp = oa
549
+ if other_exp:
550
+ other_factors[factor] = other_exp
551
+ else:
552
+ del other_factors[factor]
553
+
554
+ return Factors(self_factors), Factors(other_factors)
555
+
556
+ def div(self, other): # Factors
557
+ """Return ``self`` and ``other`` with ``gcd`` removed from each.
558
+ This is optimized for the case when there are many factors in common.
559
+
560
+ Examples
561
+ ========
562
+
563
+ >>> from sympy.core.exprtools import Factors
564
+ >>> from sympy.abc import x, y, z
565
+ >>> from sympy import S
566
+
567
+ >>> a = Factors((x*y**2).as_powers_dict())
568
+ >>> a.div(a)
569
+ (Factors({}), Factors({}))
570
+ >>> a.div(x*z)
571
+ (Factors({y: 2}), Factors({z: 1}))
572
+
573
+ The ``/`` operator only gives ``quo``:
574
+
575
+ >>> a/x
576
+ Factors({y: 2})
577
+
578
+ Factors treats its factors as though they are all in the numerator, so
579
+ if you violate this assumption the results will be correct but will
580
+ not strictly correspond to the numerator and denominator of the ratio:
581
+
582
+ >>> a.div(x/z)
583
+ (Factors({y: 2}), Factors({z: -1}))
584
+
585
+ Factors is also naive about bases: it does not attempt any denesting
586
+ of Rational-base terms, for example the following does not become
587
+ 2**(2*x)/2.
588
+
589
+ >>> Factors(2**(2*x + 2)).div(S(8))
590
+ (Factors({2: 2*x + 2}), Factors({8: 1}))
591
+
592
+ factor_terms can clean up such Rational-bases powers:
593
+
594
+ >>> from sympy import factor_terms
595
+ >>> n, d = Factors(2**(2*x + 2)).div(S(8))
596
+ >>> n.as_expr()/d.as_expr()
597
+ 2**(2*x + 2)/8
598
+ >>> factor_terms(_)
599
+ 2**(2*x)/2
600
+
601
+ """
602
+ quo, rem = dict(self.factors), {}
603
+
604
+ if not isinstance(other, Factors):
605
+ other = Factors(other)
606
+ if other.is_zero:
607
+ raise ZeroDivisionError
608
+ if self.is_zero:
609
+ return (Factors(S.Zero), Factors())
610
+
611
+ for factor, exp in other.factors.items():
612
+ if factor in quo:
613
+ d = quo[factor] - exp
614
+ if _isnumber(d):
615
+ if d <= 0:
616
+ del quo[factor]
617
+
618
+ if d >= 0:
619
+ if d:
620
+ quo[factor] = d
621
+
622
+ continue
623
+
624
+ exp = -d
625
+
626
+ else:
627
+ r = quo[factor].extract_additively(exp)
628
+ if r is not None:
629
+ if r:
630
+ quo[factor] = r
631
+ else: # should be handled already
632
+ del quo[factor]
633
+ else:
634
+ other_exp = exp
635
+ sc, sa = quo[factor].as_coeff_Add()
636
+ if sc:
637
+ oc, oa = other_exp.as_coeff_Add()
638
+ diff = sc - oc
639
+ if diff > 0:
640
+ quo[factor] -= oc
641
+ other_exp = oa
642
+ elif diff < 0:
643
+ quo[factor] -= sc
644
+ other_exp = oa - diff
645
+ else:
646
+ quo[factor] = sa
647
+ other_exp = oa
648
+ if other_exp:
649
+ rem[factor] = other_exp
650
+ else:
651
+ assert factor not in rem
652
+ continue
653
+
654
+ rem[factor] = exp
655
+
656
+ return Factors(quo), Factors(rem)
657
+
658
+ def quo(self, other): # Factors
659
+ """Return numerator Factor of ``self / other``.
660
+
661
+ Examples
662
+ ========
663
+
664
+ >>> from sympy.core.exprtools import Factors
665
+ >>> from sympy.abc import x, y, z
666
+ >>> a = Factors((x*y**2).as_powers_dict())
667
+ >>> b = Factors((x*y/z).as_powers_dict())
668
+ >>> a.quo(b) # same as a/b
669
+ Factors({y: 1})
670
+ """
671
+ return self.div(other)[0]
672
+
673
+ def rem(self, other): # Factors
674
+ """Return denominator Factors of ``self / other``.
675
+
676
+ Examples
677
+ ========
678
+
679
+ >>> from sympy.core.exprtools import Factors
680
+ >>> from sympy.abc import x, y, z
681
+ >>> a = Factors((x*y**2).as_powers_dict())
682
+ >>> b = Factors((x*y/z).as_powers_dict())
683
+ >>> a.rem(b)
684
+ Factors({z: -1})
685
+ >>> a.rem(a)
686
+ Factors({})
687
+ """
688
+ return self.div(other)[1]
689
+
690
+ def pow(self, other): # Factors
691
+ """Return self raised to a non-negative integer power.
692
+
693
+ Examples
694
+ ========
695
+
696
+ >>> from sympy.core.exprtools import Factors
697
+ >>> from sympy.abc import x, y
698
+ >>> a = Factors((x*y**2).as_powers_dict())
699
+ >>> a**2
700
+ Factors({x: 2, y: 4})
701
+
702
+ """
703
+ if isinstance(other, Factors):
704
+ other = other.as_expr()
705
+ if other.is_Integer:
706
+ other = int(other)
707
+ if isinstance(other, SYMPY_INTS) and other >= 0:
708
+ factors = {}
709
+
710
+ if other:
711
+ for factor, exp in self.factors.items():
712
+ factors[factor] = exp*other
713
+
714
+ return Factors(factors)
715
+ else:
716
+ raise ValueError("expected non-negative integer, got %s" % other)
717
+
718
+ def gcd(self, other): # Factors
719
+ """Return Factors of ``gcd(self, other)``. The keys are
720
+ the intersection of factors with the minimum exponent for
721
+ each factor.
722
+
723
+ Examples
724
+ ========
725
+
726
+ >>> from sympy.core.exprtools import Factors
727
+ >>> from sympy.abc import x, y, z
728
+ >>> a = Factors((x*y**2).as_powers_dict())
729
+ >>> b = Factors((x*y/z).as_powers_dict())
730
+ >>> a.gcd(b)
731
+ Factors({x: 1, y: 1})
732
+ """
733
+ if not isinstance(other, Factors):
734
+ other = Factors(other)
735
+ if other.is_zero:
736
+ return Factors(self.factors)
737
+
738
+ factors = {}
739
+
740
+ for factor, exp in self.factors.items():
741
+ factor, exp = sympify(factor), sympify(exp)
742
+ if factor in other.factors:
743
+ lt = (exp - other.factors[factor]).is_negative
744
+ if lt == True:
745
+ factors[factor] = exp
746
+ elif lt == False:
747
+ factors[factor] = other.factors[factor]
748
+
749
+ return Factors(factors)
750
+
751
+ def lcm(self, other): # Factors
752
+ """Return Factors of ``lcm(self, other)`` which are
753
+ the union of factors with the maximum exponent for
754
+ each factor.
755
+
756
+ Examples
757
+ ========
758
+
759
+ >>> from sympy.core.exprtools import Factors
760
+ >>> from sympy.abc import x, y, z
761
+ >>> a = Factors((x*y**2).as_powers_dict())
762
+ >>> b = Factors((x*y/z).as_powers_dict())
763
+ >>> a.lcm(b)
764
+ Factors({x: 1, y: 2, z: -1})
765
+ """
766
+ if not isinstance(other, Factors):
767
+ other = Factors(other)
768
+ if any(f.is_zero for f in (self, other)):
769
+ return Factors(S.Zero)
770
+
771
+ factors = dict(self.factors)
772
+
773
+ for factor, exp in other.factors.items():
774
+ if factor in factors:
775
+ exp = max(exp, factors[factor])
776
+
777
+ factors[factor] = exp
778
+
779
+ return Factors(factors)
780
+
781
+ def __mul__(self, other): # Factors
782
+ return self.mul(other)
783
+
784
+ def __divmod__(self, other): # Factors
785
+ return self.div(other)
786
+
787
+ def __truediv__(self, other): # Factors
788
+ return self.quo(other)
789
+
790
+ def __mod__(self, other): # Factors
791
+ return self.rem(other)
792
+
793
+ def __pow__(self, other): # Factors
794
+ return self.pow(other)
795
+
796
+ def __eq__(self, other): # Factors
797
+ if not isinstance(other, Factors):
798
+ other = Factors(other)
799
+ return self.factors == other.factors
800
+
801
+ def __ne__(self, other): # Factors
802
+ return not self == other
803
+
804
+
805
+ class Term:
806
+ """Efficient representation of ``coeff*(numer/denom)``. """
807
+
808
+ __slots__ = ('coeff', 'numer', 'denom')
809
+
810
+ def __init__(self, term, numer=None, denom=None): # Term
811
+ if numer is None and denom is None:
812
+ if not term.is_commutative:
813
+ raise NonCommutativeExpression(
814
+ 'commutative expression expected')
815
+
816
+ coeff, factors = term.as_coeff_mul()
817
+ numer, denom = defaultdict(int), defaultdict(int)
818
+
819
+ for factor in factors:
820
+ base, exp = decompose_power(factor)
821
+
822
+ if base.is_Add:
823
+ cont, base = base.primitive()
824
+ coeff *= cont**exp
825
+
826
+ if exp > 0:
827
+ numer[base] += exp
828
+ else:
829
+ denom[base] += -exp
830
+
831
+ numer = Factors(numer)
832
+ denom = Factors(denom)
833
+ else:
834
+ coeff = term
835
+
836
+ if numer is None:
837
+ numer = Factors()
838
+
839
+ if denom is None:
840
+ denom = Factors()
841
+
842
+ self.coeff = coeff
843
+ self.numer = numer
844
+ self.denom = denom
845
+
846
+ def __hash__(self): # Term
847
+ return hash((self.coeff, self.numer, self.denom))
848
+
849
+ def __repr__(self): # Term
850
+ return "Term(%s, %s, %s)" % (self.coeff, self.numer, self.denom)
851
+
852
+ def as_expr(self): # Term
853
+ return self.coeff*(self.numer.as_expr()/self.denom.as_expr())
854
+
855
+ def mul(self, other): # Term
856
+ coeff = self.coeff*other.coeff
857
+ numer = self.numer.mul(other.numer)
858
+ denom = self.denom.mul(other.denom)
859
+
860
+ numer, denom = numer.normal(denom)
861
+
862
+ return Term(coeff, numer, denom)
863
+
864
+ def inv(self): # Term
865
+ return Term(1/self.coeff, self.denom, self.numer)
866
+
867
+ def quo(self, other): # Term
868
+ return self.mul(other.inv())
869
+
870
+ def pow(self, other): # Term
871
+ if other < 0:
872
+ return self.inv().pow(-other)
873
+ else:
874
+ return Term(self.coeff ** other,
875
+ self.numer.pow(other),
876
+ self.denom.pow(other))
877
+
878
+ def gcd(self, other): # Term
879
+ return Term(self.coeff.gcd(other.coeff),
880
+ self.numer.gcd(other.numer),
881
+ self.denom.gcd(other.denom))
882
+
883
+ def lcm(self, other): # Term
884
+ return Term(self.coeff.lcm(other.coeff),
885
+ self.numer.lcm(other.numer),
886
+ self.denom.lcm(other.denom))
887
+
888
+ def __mul__(self, other): # Term
889
+ if isinstance(other, Term):
890
+ return self.mul(other)
891
+ else:
892
+ return NotImplemented
893
+
894
+ def __truediv__(self, other): # Term
895
+ if isinstance(other, Term):
896
+ return self.quo(other)
897
+ else:
898
+ return NotImplemented
899
+
900
+ def __pow__(self, other): # Term
901
+ if isinstance(other, SYMPY_INTS):
902
+ return self.pow(other)
903
+ else:
904
+ return NotImplemented
905
+
906
+ def __eq__(self, other): # Term
907
+ return (self.coeff == other.coeff and
908
+ self.numer == other.numer and
909
+ self.denom == other.denom)
910
+
911
+ def __ne__(self, other): # Term
912
+ return not self == other
913
+
914
+
915
+ def _gcd_terms(terms, isprimitive=False, fraction=True):
916
+ """Helper function for :func:`gcd_terms`.
917
+
918
+ Parameters
919
+ ==========
920
+
921
+ isprimitive : boolean, optional
922
+ If ``isprimitive`` is True then the call to primitive
923
+ for an Add will be skipped. This is useful when the
924
+ content has already been extracted.
925
+
926
+ fraction : boolean, optional
927
+ If ``fraction`` is True then the expression will appear over a common
928
+ denominator, the lcm of all term denominators.
929
+ """
930
+
931
+ if isinstance(terms, Basic) and not isinstance(terms, Tuple):
932
+ terms = Add.make_args(terms)
933
+
934
+ terms = list(map(Term, [t for t in terms if t]))
935
+
936
+ # there is some simplification that may happen if we leave this
937
+ # here rather than duplicate it before the mapping of Term onto
938
+ # the terms
939
+ if len(terms) == 0:
940
+ return S.Zero, S.Zero, S.One
941
+
942
+ if len(terms) == 1:
943
+ cont = terms[0].coeff
944
+ numer = terms[0].numer.as_expr()
945
+ denom = terms[0].denom.as_expr()
946
+
947
+ else:
948
+ cont = terms[0]
949
+ for term in terms[1:]:
950
+ cont = cont.gcd(term)
951
+
952
+ for i, term in enumerate(terms):
953
+ terms[i] = term.quo(cont)
954
+
955
+ if fraction:
956
+ denom = terms[0].denom
957
+
958
+ for term in terms[1:]:
959
+ denom = denom.lcm(term.denom)
960
+
961
+ numers = []
962
+ for term in terms:
963
+ numer = term.numer.mul(denom.quo(term.denom))
964
+ numers.append(term.coeff*numer.as_expr())
965
+ else:
966
+ numers = [t.as_expr() for t in terms]
967
+ denom = Term(S.One).numer
968
+
969
+ cont = cont.as_expr()
970
+ numer = Add(*numers)
971
+ denom = denom.as_expr()
972
+
973
+ if not isprimitive and numer.is_Add:
974
+ _cont, numer = numer.primitive()
975
+ cont *= _cont
976
+
977
+ return cont, numer, denom
978
+
979
+
980
+ def gcd_terms(terms, isprimitive=False, clear=True, fraction=True):
981
+ """Compute the GCD of ``terms`` and put them together.
982
+
983
+ Parameters
984
+ ==========
985
+
986
+ terms : Expr
987
+ Can be an expression or a non-Basic sequence of expressions
988
+ which will be handled as though they are terms from a sum.
989
+
990
+ isprimitive : bool, optional
991
+ If ``isprimitive`` is True the _gcd_terms will not run the primitive
992
+ method on the terms.
993
+
994
+ clear : bool, optional
995
+ It controls the removal of integers from the denominator of an Add
996
+ expression. When True (default), all numerical denominator will be cleared;
997
+ when False the denominators will be cleared only if all terms had numerical
998
+ denominators other than 1.
999
+
1000
+ fraction : bool, optional
1001
+ When True (default), will put the expression over a common
1002
+ denominator.
1003
+
1004
+ Examples
1005
+ ========
1006
+
1007
+ >>> from sympy import gcd_terms
1008
+ >>> from sympy.abc import x, y
1009
+
1010
+ >>> gcd_terms((x + 1)**2*y + (x + 1)*y**2)
1011
+ y*(x + 1)*(x + y + 1)
1012
+ >>> gcd_terms(x/2 + 1)
1013
+ (x + 2)/2
1014
+ >>> gcd_terms(x/2 + 1, clear=False)
1015
+ x/2 + 1
1016
+ >>> gcd_terms(x/2 + y/2, clear=False)
1017
+ (x + y)/2
1018
+ >>> gcd_terms(x/2 + 1/x)
1019
+ (x**2 + 2)/(2*x)
1020
+ >>> gcd_terms(x/2 + 1/x, fraction=False)
1021
+ (x + 2/x)/2
1022
+ >>> gcd_terms(x/2 + 1/x, fraction=False, clear=False)
1023
+ x/2 + 1/x
1024
+
1025
+ >>> gcd_terms(x/2/y + 1/x/y)
1026
+ (x**2 + 2)/(2*x*y)
1027
+ >>> gcd_terms(x/2/y + 1/x/y, clear=False)
1028
+ (x**2/2 + 1)/(x*y)
1029
+ >>> gcd_terms(x/2/y + 1/x/y, clear=False, fraction=False)
1030
+ (x/2 + 1/x)/y
1031
+
1032
+ The ``clear`` flag was ignored in this case because the returned
1033
+ expression was a rational expression, not a simple sum.
1034
+
1035
+ See Also
1036
+ ========
1037
+
1038
+ factor_terms, sympy.polys.polytools.terms_gcd
1039
+
1040
+ """
1041
+ def mask(terms):
1042
+ """replace nc portions of each term with a unique Dummy symbols
1043
+ and return the replacements to restore them"""
1044
+ args = [(a, []) if a.is_commutative else a.args_cnc() for a in terms]
1045
+ reps = []
1046
+ for i, (c, nc) in enumerate(args):
1047
+ if nc:
1048
+ nc = Mul(*nc)
1049
+ d = Dummy()
1050
+ reps.append((d, nc))
1051
+ c.append(d)
1052
+ args[i] = Mul(*c)
1053
+ else:
1054
+ args[i] = c
1055
+ return args, dict(reps)
1056
+
1057
+ isadd = isinstance(terms, Add)
1058
+ addlike = isadd or not isinstance(terms, Basic) and \
1059
+ is_sequence(terms, include=set) and \
1060
+ not isinstance(terms, Dict)
1061
+
1062
+ if addlike:
1063
+ if isadd: # i.e. an Add
1064
+ terms = list(terms.args)
1065
+ else:
1066
+ terms = sympify(terms)
1067
+ terms, reps = mask(terms)
1068
+ cont, numer, denom = _gcd_terms(terms, isprimitive, fraction)
1069
+ numer = numer.xreplace(reps)
1070
+ coeff, factors = cont.as_coeff_Mul()
1071
+ if not clear:
1072
+ c, _coeff = coeff.as_coeff_Mul()
1073
+ if not c.is_Integer and not clear and numer.is_Add:
1074
+ n, d = c.as_numer_denom()
1075
+ _numer = numer/d
1076
+ if any(a.as_coeff_Mul()[0].is_Integer
1077
+ for a in _numer.args):
1078
+ numer = _numer
1079
+ coeff = n*_coeff
1080
+ return _keep_coeff(coeff, factors*numer/denom, clear=clear)
1081
+
1082
+ if not isinstance(terms, Basic):
1083
+ return terms
1084
+
1085
+ if terms.is_Atom:
1086
+ return terms
1087
+
1088
+ if terms.is_Mul:
1089
+ c, args = terms.as_coeff_mul()
1090
+ return _keep_coeff(c, Mul(*[gcd_terms(i, isprimitive, clear, fraction)
1091
+ for i in args]), clear=clear)
1092
+
1093
+ def handle(a):
1094
+ # don't treat internal args like terms of an Add
1095
+ if not isinstance(a, Expr):
1096
+ if isinstance(a, Basic):
1097
+ if not a.args:
1098
+ return a
1099
+ return a.func(*[handle(i) for i in a.args])
1100
+ return type(a)([handle(i) for i in a])
1101
+ return gcd_terms(a, isprimitive, clear, fraction)
1102
+
1103
+ if isinstance(terms, Dict):
1104
+ return Dict(*[(k, handle(v)) for k, v in terms.args])
1105
+ return terms.func(*[handle(i) for i in terms.args])
1106
+
1107
+
1108
+ def _factor_sum_int(expr, **kwargs):
1109
+ """Return Sum or Integral object with factors that are not
1110
+ in the wrt variables removed. In cases where there are additive
1111
+ terms in the function of the object that are independent, the
1112
+ object will be separated into two objects.
1113
+
1114
+ Examples
1115
+ ========
1116
+
1117
+ >>> from sympy import Sum, factor_terms
1118
+ >>> from sympy.abc import x, y
1119
+ >>> factor_terms(Sum(x + y, (x, 1, 3)))
1120
+ y*Sum(1, (x, 1, 3)) + Sum(x, (x, 1, 3))
1121
+ >>> factor_terms(Sum(x*y, (x, 1, 3)))
1122
+ y*Sum(x, (x, 1, 3))
1123
+
1124
+ Notes
1125
+ =====
1126
+
1127
+ If a function in the summand or integrand is replaced
1128
+ with a symbol, then this simplification should not be
1129
+ done or else an incorrect result will be obtained when
1130
+ the symbol is replaced with an expression that depends
1131
+ on the variables of summation/integration:
1132
+
1133
+ >>> eq = Sum(y, (x, 1, 3))
1134
+ >>> factor_terms(eq).subs(y, x).doit()
1135
+ 3*x
1136
+ >>> eq.subs(y, x).doit()
1137
+ 6
1138
+ """
1139
+ result = expr.function
1140
+ if result == 0:
1141
+ return S.Zero
1142
+ limits = expr.limits
1143
+
1144
+ # get the wrt variables
1145
+ wrt = {i.args[0] for i in limits}
1146
+
1147
+ # factor out any common terms that are independent of wrt
1148
+ f = factor_terms(result, **kwargs)
1149
+ i, d = f.as_independent(*wrt)
1150
+ if isinstance(f, Add):
1151
+ return i * expr.func(1, *limits) + expr.func(d, *limits)
1152
+ else:
1153
+ return i * expr.func(d, *limits)
1154
+
1155
+
1156
+ def factor_terms(expr, radical=False, clear=False, fraction=False, sign=True):
1157
+ """Remove common factors from terms in all arguments without
1158
+ changing the underlying structure of the expr. No expansion or
1159
+ simplification (and no processing of non-commutatives) is performed.
1160
+
1161
+ Parameters
1162
+ ==========
1163
+
1164
+ radical: bool, optional
1165
+ If radical=True then a radical common to all terms will be factored
1166
+ out of any Add sub-expressions of the expr.
1167
+
1168
+ clear : bool, optional
1169
+ If clear=False (default) then coefficients will not be separated
1170
+ from a single Add if they can be distributed to leave one or more
1171
+ terms with integer coefficients.
1172
+
1173
+ fraction : bool, optional
1174
+ If fraction=True (default is False) then a common denominator will be
1175
+ constructed for the expression.
1176
+
1177
+ sign : bool, optional
1178
+ If sign=True (default) then even if the only factor in common is a -1,
1179
+ it will be factored out of the expression.
1180
+
1181
+ Examples
1182
+ ========
1183
+
1184
+ >>> from sympy import factor_terms, Symbol
1185
+ >>> from sympy.abc import x, y
1186
+ >>> factor_terms(x + x*(2 + 4*y)**3)
1187
+ x*(8*(2*y + 1)**3 + 1)
1188
+ >>> A = Symbol('A', commutative=False)
1189
+ >>> factor_terms(x*A + x*A + x*y*A)
1190
+ x*(y*A + 2*A)
1191
+
1192
+ When ``clear`` is False, a rational will only be factored out of an
1193
+ Add expression if all terms of the Add have coefficients that are
1194
+ fractions:
1195
+
1196
+ >>> factor_terms(x/2 + 1, clear=False)
1197
+ x/2 + 1
1198
+ >>> factor_terms(x/2 + 1, clear=True)
1199
+ (x + 2)/2
1200
+
1201
+ If a -1 is all that can be factored out, to *not* factor it out, the
1202
+ flag ``sign`` must be False:
1203
+
1204
+ >>> factor_terms(-x - y)
1205
+ -(x + y)
1206
+ >>> factor_terms(-x - y, sign=False)
1207
+ -x - y
1208
+ >>> factor_terms(-2*x - 2*y, sign=False)
1209
+ -2*(x + y)
1210
+
1211
+ See Also
1212
+ ========
1213
+
1214
+ gcd_terms, sympy.polys.polytools.terms_gcd
1215
+
1216
+ """
1217
+ def do(expr):
1218
+ from sympy.concrete.summations import Sum
1219
+ from sympy.integrals.integrals import Integral
1220
+ is_iterable = iterable(expr)
1221
+
1222
+ if not isinstance(expr, Basic) or expr.is_Atom:
1223
+ if is_iterable:
1224
+ return type(expr)([do(i) for i in expr])
1225
+ return expr
1226
+
1227
+ if expr.is_Pow or expr.is_Function or \
1228
+ is_iterable or not hasattr(expr, 'args_cnc'):
1229
+ args = expr.args
1230
+ newargs = tuple([do(i) for i in args])
1231
+ if newargs == args:
1232
+ return expr
1233
+ return expr.func(*newargs)
1234
+
1235
+ if isinstance(expr, (Sum, Integral)):
1236
+ return _factor_sum_int(expr,
1237
+ radical=radical, clear=clear,
1238
+ fraction=fraction, sign=sign)
1239
+
1240
+ cont, p = expr.as_content_primitive(radical=radical, clear=clear)
1241
+ if p.is_Add:
1242
+ list_args = [do(a) for a in Add.make_args(p)]
1243
+ # get a common negative (if there) which gcd_terms does not remove
1244
+ if not any(a.as_coeff_Mul()[0].extract_multiplicatively(-1) is None
1245
+ for a in list_args):
1246
+ cont = -cont
1247
+ list_args = [-a for a in list_args]
1248
+ # watch out for exp(-(x+2)) which gcd_terms will change to exp(-x-2)
1249
+ special = {}
1250
+ for i, a in enumerate(list_args):
1251
+ b, e = a.as_base_exp()
1252
+ if e.is_Mul and e != Mul(*e.args):
1253
+ list_args[i] = Dummy()
1254
+ special[list_args[i]] = a
1255
+ # rebuild p not worrying about the order which gcd_terms will fix
1256
+ p = Add._from_args(list_args)
1257
+ p = gcd_terms(p,
1258
+ isprimitive=True,
1259
+ clear=clear,
1260
+ fraction=fraction).xreplace(special)
1261
+ elif p.args:
1262
+ p = p.func(
1263
+ *[do(a) for a in p.args])
1264
+ rv = _keep_coeff(cont, p, clear=clear, sign=sign)
1265
+ return rv
1266
+ expr = sympify(expr)
1267
+ return do(expr)
1268
+
1269
+
1270
+ def _mask_nc(eq, name=None):
1271
+ """
1272
+ Return ``eq`` with non-commutative objects replaced with Dummy
1273
+ symbols. A dictionary that can be used to restore the original
1274
+ values is returned: if it is None, the expression is noncommutative
1275
+ and cannot be made commutative. The third value returned is a list
1276
+ of any non-commutative symbols that appear in the returned equation.
1277
+
1278
+ Explanation
1279
+ ===========
1280
+
1281
+ All non-commutative objects other than Symbols are replaced with
1282
+ a non-commutative Symbol. Identical objects will be identified
1283
+ by identical symbols.
1284
+
1285
+ If there is only 1 non-commutative object in an expression it will
1286
+ be replaced with a commutative symbol. Otherwise, the non-commutative
1287
+ entities are retained and the calling routine should handle
1288
+ replacements in this case since some care must be taken to keep
1289
+ track of the ordering of symbols when they occur within Muls.
1290
+
1291
+ Parameters
1292
+ ==========
1293
+
1294
+ name : str
1295
+ ``name``, if given, is the name that will be used with numbered Dummy
1296
+ variables that will replace the non-commutative objects and is mainly
1297
+ used for doctesting purposes.
1298
+
1299
+ Examples
1300
+ ========
1301
+
1302
+ >>> from sympy.physics.secondquant import Commutator, NO, F, Fd
1303
+ >>> from sympy import symbols
1304
+ >>> from sympy.core.exprtools import _mask_nc
1305
+ >>> from sympy.abc import x, y
1306
+ >>> A, B, C = symbols('A,B,C', commutative=False)
1307
+
1308
+ One nc-symbol:
1309
+
1310
+ >>> _mask_nc(A**2 - x**2, 'd')
1311
+ (_d0**2 - x**2, {_d0: A}, [])
1312
+
1313
+ Multiple nc-symbols:
1314
+
1315
+ >>> _mask_nc(A**2 - B**2, 'd')
1316
+ (A**2 - B**2, {}, [A, B])
1317
+
1318
+ An nc-object with nc-symbols but no others outside of it:
1319
+
1320
+ >>> _mask_nc(1 + x*Commutator(A, B), 'd')
1321
+ (_d0*x + 1, {_d0: Commutator(A, B)}, [])
1322
+ >>> _mask_nc(NO(Fd(x)*F(y)), 'd')
1323
+ (_d0, {_d0: NO(CreateFermion(x)*AnnihilateFermion(y))}, [])
1324
+
1325
+ Multiple nc-objects:
1326
+
1327
+ >>> eq = x*Commutator(A, B) + x*Commutator(A, C)*Commutator(A, B)
1328
+ >>> _mask_nc(eq, 'd')
1329
+ (x*_d0 + x*_d1*_d0, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1])
1330
+
1331
+ Multiple nc-objects and nc-symbols:
1332
+
1333
+ >>> eq = A*Commutator(A, B) + B*Commutator(A, C)
1334
+ >>> _mask_nc(eq, 'd')
1335
+ (A*_d0 + B*_d1, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1, A, B])
1336
+
1337
+ """
1338
+ name = name or 'mask'
1339
+ # Make Dummy() append sequential numbers to the name
1340
+
1341
+ def numbered_names():
1342
+ i = 0
1343
+ while True:
1344
+ yield name + str(i)
1345
+ i += 1
1346
+
1347
+ names = numbered_names()
1348
+
1349
+ def Dummy(*args, **kwargs):
1350
+ from .symbol import Dummy
1351
+ return Dummy(next(names), *args, **kwargs)
1352
+
1353
+ expr = eq
1354
+ if expr.is_commutative:
1355
+ return eq, {}, []
1356
+
1357
+ # identify nc-objects; symbols and other
1358
+ rep = []
1359
+ nc_obj = set()
1360
+ nc_syms = set()
1361
+ pot = preorder_traversal(expr, keys=default_sort_key)
1362
+ for i, a in enumerate(pot):
1363
+ if any(a == r[0] for r in rep):
1364
+ pot.skip()
1365
+ elif not a.is_commutative:
1366
+ if a.is_symbol:
1367
+ nc_syms.add(a)
1368
+ pot.skip()
1369
+ elif not (a.is_Add or a.is_Mul or a.is_Pow):
1370
+ nc_obj.add(a)
1371
+ pot.skip()
1372
+
1373
+ # If there is only one nc symbol or object, it can be factored regularly
1374
+ # but polys is going to complain, so replace it with a Dummy.
1375
+ if len(nc_obj) == 1 and not nc_syms:
1376
+ rep.append((nc_obj.pop(), Dummy()))
1377
+ elif len(nc_syms) == 1 and not nc_obj:
1378
+ rep.append((nc_syms.pop(), Dummy()))
1379
+
1380
+ # Any remaining nc-objects will be replaced with an nc-Dummy and
1381
+ # identified as an nc-Symbol to watch out for
1382
+ nc_obj = sorted(nc_obj, key=default_sort_key)
1383
+ for n in nc_obj:
1384
+ nc = Dummy(commutative=False)
1385
+ rep.append((n, nc))
1386
+ nc_syms.add(nc)
1387
+ expr = expr.subs(rep)
1388
+
1389
+ nc_syms = list(nc_syms)
1390
+ nc_syms.sort(key=default_sort_key)
1391
+ return expr, {v: k for k, v in rep}, nc_syms
1392
+
1393
+
1394
+ def factor_nc(expr):
1395
+ """Return the factored form of ``expr`` while handling non-commutative
1396
+ expressions.
1397
+
1398
+ Examples
1399
+ ========
1400
+
1401
+ >>> from sympy import factor_nc, Symbol
1402
+ >>> from sympy.abc import x
1403
+ >>> A = Symbol('A', commutative=False)
1404
+ >>> B = Symbol('B', commutative=False)
1405
+ >>> factor_nc((x**2 + 2*A*x + A**2).expand())
1406
+ (x + A)**2
1407
+ >>> factor_nc(((x + A)*(x + B)).expand())
1408
+ (x + A)*(x + B)
1409
+ """
1410
+ expr = sympify(expr)
1411
+ if not isinstance(expr, Expr) or not expr.args:
1412
+ return expr
1413
+ if not expr.is_Add:
1414
+ return expr.func(*[factor_nc(a) for a in expr.args])
1415
+ expr = expr.func(*[expand_power_exp(i) for i in expr.args])
1416
+
1417
+ from sympy.polys.polytools import gcd, factor
1418
+ expr, rep, nc_symbols = _mask_nc(expr)
1419
+
1420
+ if rep:
1421
+ return factor(expr).subs(rep)
1422
+ else:
1423
+ args = [a.args_cnc() for a in Add.make_args(expr)]
1424
+ c = g = l = r = S.One
1425
+ hit = False
1426
+ # find any commutative gcd term
1427
+ for i, a in enumerate(args):
1428
+ if i == 0:
1429
+ c = Mul._from_args(a[0])
1430
+ elif a[0]:
1431
+ c = gcd(c, Mul._from_args(a[0]))
1432
+ else:
1433
+ c = S.One
1434
+ if c is not S.One:
1435
+ hit = True
1436
+ c, g = c.as_coeff_Mul()
1437
+ if g is not S.One:
1438
+ for i, (cc, _) in enumerate(args):
1439
+ cc = list(Mul.make_args(Mul._from_args(list(cc))/g))
1440
+ args[i][0] = cc
1441
+ for i, (cc, _) in enumerate(args):
1442
+ if cc:
1443
+ cc[0] = cc[0]/c
1444
+ else:
1445
+ cc = [1/c]
1446
+ args[i][0] = cc
1447
+ # find any noncommutative common prefix
1448
+ for i, a in enumerate(args):
1449
+ if i == 0:
1450
+ n = a[1][:]
1451
+ else:
1452
+ n = common_prefix(n, a[1])
1453
+ if not n:
1454
+ # is there a power that can be extracted?
1455
+ if not args[0][1]:
1456
+ break
1457
+ b, e = args[0][1][0].as_base_exp()
1458
+ ok = False
1459
+ if e.is_Integer:
1460
+ for t in args:
1461
+ if not t[1]:
1462
+ break
1463
+ bt, et = t[1][0].as_base_exp()
1464
+ if et.is_Integer and bt == b:
1465
+ e = min(e, et)
1466
+ else:
1467
+ break
1468
+ else:
1469
+ ok = hit = True
1470
+ l = b**e
1471
+ il = b**-e
1472
+ for _ in args:
1473
+ _[1][0] = il*_[1][0]
1474
+ break
1475
+ if not ok:
1476
+ break
1477
+ else:
1478
+ hit = True
1479
+ lenn = len(n)
1480
+ l = Mul(*n)
1481
+ for _ in args:
1482
+ _[1] = _[1][lenn:]
1483
+ # find any noncommutative common suffix
1484
+ for i, a in enumerate(args):
1485
+ if i == 0:
1486
+ n = a[1][:]
1487
+ else:
1488
+ n = common_suffix(n, a[1])
1489
+ if not n:
1490
+ # is there a power that can be extracted?
1491
+ if not args[0][1]:
1492
+ break
1493
+ b, e = args[0][1][-1].as_base_exp()
1494
+ ok = False
1495
+ if e.is_Integer:
1496
+ for t in args:
1497
+ if not t[1]:
1498
+ break
1499
+ bt, et = t[1][-1].as_base_exp()
1500
+ if et.is_Integer and bt == b:
1501
+ e = min(e, et)
1502
+ else:
1503
+ break
1504
+ else:
1505
+ ok = hit = True
1506
+ r = b**e
1507
+ il = b**-e
1508
+ for _ in args:
1509
+ _[1][-1] = _[1][-1]*il
1510
+ break
1511
+ if not ok:
1512
+ break
1513
+ else:
1514
+ hit = True
1515
+ lenn = len(n)
1516
+ r = Mul(*n)
1517
+ for _ in args:
1518
+ _[1] = _[1][:len(_[1]) - lenn]
1519
+ if hit:
1520
+ mid = Add(*[Mul(*cc)*Mul(*nc) for cc, nc in args])
1521
+ else:
1522
+ mid = expr
1523
+
1524
+ from sympy.simplify.powsimp import powsimp
1525
+
1526
+ # sort the symbols so the Dummys would appear in the same
1527
+ # order as the original symbols, otherwise you may introduce
1528
+ # a factor of -1, e.g. A**2 - B**2) -- {A:y, B:x} --> y**2 - x**2
1529
+ # and the former factors into two terms, (A - B)*(A + B) while the
1530
+ # latter factors into 3 terms, (-1)*(x - y)*(x + y)
1531
+ rep1 = [(n, Dummy()) for n in sorted(nc_symbols, key=default_sort_key)]
1532
+ unrep1 = [(v, k) for k, v in rep1]
1533
+ unrep1.reverse()
1534
+ new_mid, r2, _ = _mask_nc(mid.subs(rep1))
1535
+ new_mid = powsimp(factor(new_mid))
1536
+
1537
+ new_mid = new_mid.subs(r2).subs(unrep1)
1538
+
1539
+ if new_mid.is_Pow:
1540
+ return _keep_coeff(c, g*l*new_mid*r)
1541
+
1542
+ if new_mid.is_Mul:
1543
+ def _pemexpand(expr):
1544
+ "Expand with the minimal set of hints necessary to check the result."
1545
+ return expr.expand(deep=True, mul=True, power_exp=True,
1546
+ power_base=False, basic=False, multinomial=True, log=False)
1547
+ # XXX TODO there should be a way to inspect what order the terms
1548
+ # must be in and just select the plausible ordering without
1549
+ # checking permutations
1550
+ cfac = []
1551
+ ncfac = []
1552
+ for f in new_mid.args:
1553
+ if f.is_commutative:
1554
+ cfac.append(f)
1555
+ else:
1556
+ b, e = f.as_base_exp()
1557
+ if e.is_Integer:
1558
+ ncfac.extend([b]*e)
1559
+ else:
1560
+ ncfac.append(f)
1561
+ pre_mid = g*Mul(*cfac)*l
1562
+ target = _pemexpand(expr/c)
1563
+ for s in variations(ncfac, len(ncfac)):
1564
+ ok = pre_mid*Mul(*s)*r
1565
+ if _pemexpand(ok) == target:
1566
+ return _keep_coeff(c, ok)
1567
+
1568
+ # mid was an Add that didn't factor successfully
1569
+ return _keep_coeff(c, g*l*mid*r)
env-llmeval/lib/python3.10/site-packages/sympy/core/facts.py ADDED
@@ -0,0 +1,634 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""This is rule-based deduction system for SymPy
2
+
3
+ The whole thing is split into two parts
4
+
5
+ - rules compilation and preparation of tables
6
+ - runtime inference
7
+
8
+ For rule-based inference engines, the classical work is RETE algorithm [1],
9
+ [2] Although we are not implementing it in full (or even significantly)
10
+ it's still worth a read to understand the underlying ideas.
11
+
12
+ In short, every rule in a system of rules is one of two forms:
13
+
14
+ - atom -> ... (alpha rule)
15
+ - And(atom1, atom2, ...) -> ... (beta rule)
16
+
17
+
18
+ The major complexity is in efficient beta-rules processing and usually for an
19
+ expert system a lot of effort goes into code that operates on beta-rules.
20
+
21
+
22
+ Here we take minimalistic approach to get something usable first.
23
+
24
+ - (preparation) of alpha- and beta- networks, everything except
25
+ - (runtime) FactRules.deduce_all_facts
26
+
27
+ _____________________________________
28
+ ( Kirr: I've never thought that doing )
29
+ ( logic stuff is that difficult... )
30
+ -------------------------------------
31
+ o ^__^
32
+ o (oo)\_______
33
+ (__)\ )\/\
34
+ ||----w |
35
+ || ||
36
+
37
+
38
+ Some references on the topic
39
+ ----------------------------
40
+
41
+ [1] https://en.wikipedia.org/wiki/Rete_algorithm
42
+ [2] http://reports-archive.adm.cs.cmu.edu/anon/1995/CMU-CS-95-113.pdf
43
+
44
+ https://en.wikipedia.org/wiki/Propositional_formula
45
+ https://en.wikipedia.org/wiki/Inference_rule
46
+ https://en.wikipedia.org/wiki/List_of_rules_of_inference
47
+ """
48
+
49
+ from collections import defaultdict
50
+ from typing import Iterator
51
+
52
+ from .logic import Logic, And, Or, Not
53
+
54
+
55
+ def _base_fact(atom):
56
+ """Return the literal fact of an atom.
57
+
58
+ Effectively, this merely strips the Not around a fact.
59
+ """
60
+ if isinstance(atom, Not):
61
+ return atom.arg
62
+ else:
63
+ return atom
64
+
65
+
66
+ def _as_pair(atom):
67
+ if isinstance(atom, Not):
68
+ return (atom.arg, False)
69
+ else:
70
+ return (atom, True)
71
+
72
+ # XXX this prepares forward-chaining rules for alpha-network
73
+
74
+
75
+ def transitive_closure(implications):
76
+ """
77
+ Computes the transitive closure of a list of implications
78
+
79
+ Uses Warshall's algorithm, as described at
80
+ http://www.cs.hope.edu/~cusack/Notes/Notes/DiscreteMath/Warshall.pdf.
81
+ """
82
+ full_implications = set(implications)
83
+ literals = set().union(*map(set, full_implications))
84
+
85
+ for k in literals:
86
+ for i in literals:
87
+ if (i, k) in full_implications:
88
+ for j in literals:
89
+ if (k, j) in full_implications:
90
+ full_implications.add((i, j))
91
+
92
+ return full_implications
93
+
94
+
95
+ def deduce_alpha_implications(implications):
96
+ """deduce all implications
97
+
98
+ Description by example
99
+ ----------------------
100
+
101
+ given set of logic rules:
102
+
103
+ a -> b
104
+ b -> c
105
+
106
+ we deduce all possible rules:
107
+
108
+ a -> b, c
109
+ b -> c
110
+
111
+
112
+ implications: [] of (a,b)
113
+ return: {} of a -> set([b, c, ...])
114
+ """
115
+ implications = implications + [(Not(j), Not(i)) for (i, j) in implications]
116
+ res = defaultdict(set)
117
+ full_implications = transitive_closure(implications)
118
+ for a, b in full_implications:
119
+ if a == b:
120
+ continue # skip a->a cyclic input
121
+
122
+ res[a].add(b)
123
+
124
+ # Clean up tautologies and check consistency
125
+ for a, impl in res.items():
126
+ impl.discard(a)
127
+ na = Not(a)
128
+ if na in impl:
129
+ raise ValueError(
130
+ 'implications are inconsistent: %s -> %s %s' % (a, na, impl))
131
+
132
+ return res
133
+
134
+
135
+ def apply_beta_to_alpha_route(alpha_implications, beta_rules):
136
+ """apply additional beta-rules (And conditions) to already-built
137
+ alpha implication tables
138
+
139
+ TODO: write about
140
+
141
+ - static extension of alpha-chains
142
+ - attaching refs to beta-nodes to alpha chains
143
+
144
+
145
+ e.g.
146
+
147
+ alpha_implications:
148
+
149
+ a -> [b, !c, d]
150
+ b -> [d]
151
+ ...
152
+
153
+
154
+ beta_rules:
155
+
156
+ &(b,d) -> e
157
+
158
+
159
+ then we'll extend a's rule to the following
160
+
161
+ a -> [b, !c, d, e]
162
+ """
163
+ x_impl = {}
164
+ for x in alpha_implications.keys():
165
+ x_impl[x] = (set(alpha_implications[x]), [])
166
+ for bcond, bimpl in beta_rules:
167
+ for bk in bcond.args:
168
+ if bk in x_impl:
169
+ continue
170
+ x_impl[bk] = (set(), [])
171
+
172
+ # static extensions to alpha rules:
173
+ # A: x -> a,b B: &(a,b) -> c ==> A: x -> a,b,c
174
+ seen_static_extension = True
175
+ while seen_static_extension:
176
+ seen_static_extension = False
177
+
178
+ for bcond, bimpl in beta_rules:
179
+ if not isinstance(bcond, And):
180
+ raise TypeError("Cond is not And")
181
+ bargs = set(bcond.args)
182
+ for x, (ximpls, bb) in x_impl.items():
183
+ x_all = ximpls | {x}
184
+ # A: ... -> a B: &(...) -> a is non-informative
185
+ if bimpl not in x_all and bargs.issubset(x_all):
186
+ ximpls.add(bimpl)
187
+
188
+ # we introduced new implication - now we have to restore
189
+ # completeness of the whole set.
190
+ bimpl_impl = x_impl.get(bimpl)
191
+ if bimpl_impl is not None:
192
+ ximpls |= bimpl_impl[0]
193
+ seen_static_extension = True
194
+
195
+ # attach beta-nodes which can be possibly triggered by an alpha-chain
196
+ for bidx, (bcond, bimpl) in enumerate(beta_rules):
197
+ bargs = set(bcond.args)
198
+ for x, (ximpls, bb) in x_impl.items():
199
+ x_all = ximpls | {x}
200
+ # A: ... -> a B: &(...) -> a (non-informative)
201
+ if bimpl in x_all:
202
+ continue
203
+ # A: x -> a... B: &(!a,...) -> ... (will never trigger)
204
+ # A: x -> a... B: &(...) -> !a (will never trigger)
205
+ if any(Not(xi) in bargs or Not(xi) == bimpl for xi in x_all):
206
+ continue
207
+
208
+ if bargs & x_all:
209
+ bb.append(bidx)
210
+
211
+ return x_impl
212
+
213
+
214
+ def rules_2prereq(rules):
215
+ """build prerequisites table from rules
216
+
217
+ Description by example
218
+ ----------------------
219
+
220
+ given set of logic rules:
221
+
222
+ a -> b, c
223
+ b -> c
224
+
225
+ we build prerequisites (from what points something can be deduced):
226
+
227
+ b <- a
228
+ c <- a, b
229
+
230
+ rules: {} of a -> [b, c, ...]
231
+ return: {} of c <- [a, b, ...]
232
+
233
+ Note however, that this prerequisites may be *not* enough to prove a
234
+ fact. An example is 'a -> b' rule, where prereq(a) is b, and prereq(b)
235
+ is a. That's because a=T -> b=T, and b=F -> a=F, but a=F -> b=?
236
+ """
237
+ prereq = defaultdict(set)
238
+ for (a, _), impl in rules.items():
239
+ if isinstance(a, Not):
240
+ a = a.args[0]
241
+ for (i, _) in impl:
242
+ if isinstance(i, Not):
243
+ i = i.args[0]
244
+ prereq[i].add(a)
245
+ return prereq
246
+
247
+ ################
248
+ # RULES PROVER #
249
+ ################
250
+
251
+
252
+ class TautologyDetected(Exception):
253
+ """(internal) Prover uses it for reporting detected tautology"""
254
+ pass
255
+
256
+
257
+ class Prover:
258
+ """ai - prover of logic rules
259
+
260
+ given a set of initial rules, Prover tries to prove all possible rules
261
+ which follow from given premises.
262
+
263
+ As a result proved_rules are always either in one of two forms: alpha or
264
+ beta:
265
+
266
+ Alpha rules
267
+ -----------
268
+
269
+ This are rules of the form::
270
+
271
+ a -> b & c & d & ...
272
+
273
+
274
+ Beta rules
275
+ ----------
276
+
277
+ This are rules of the form::
278
+
279
+ &(a,b,...) -> c & d & ...
280
+
281
+
282
+ i.e. beta rules are join conditions that say that something follows when
283
+ *several* facts are true at the same time.
284
+ """
285
+
286
+ def __init__(self):
287
+ self.proved_rules = []
288
+ self._rules_seen = set()
289
+
290
+ def split_alpha_beta(self):
291
+ """split proved rules into alpha and beta chains"""
292
+ rules_alpha = [] # a -> b
293
+ rules_beta = [] # &(...) -> b
294
+ for a, b in self.proved_rules:
295
+ if isinstance(a, And):
296
+ rules_beta.append((a, b))
297
+ else:
298
+ rules_alpha.append((a, b))
299
+ return rules_alpha, rules_beta
300
+
301
+ @property
302
+ def rules_alpha(self):
303
+ return self.split_alpha_beta()[0]
304
+
305
+ @property
306
+ def rules_beta(self):
307
+ return self.split_alpha_beta()[1]
308
+
309
+ def process_rule(self, a, b):
310
+ """process a -> b rule""" # TODO write more?
311
+ if (not a) or isinstance(b, bool):
312
+ return
313
+ if isinstance(a, bool):
314
+ return
315
+ if (a, b) in self._rules_seen:
316
+ return
317
+ else:
318
+ self._rules_seen.add((a, b))
319
+
320
+ # this is the core of processing
321
+ try:
322
+ self._process_rule(a, b)
323
+ except TautologyDetected:
324
+ pass
325
+
326
+ def _process_rule(self, a, b):
327
+ # right part first
328
+
329
+ # a -> b & c --> a -> b ; a -> c
330
+ # (?) FIXME this is only correct when b & c != null !
331
+
332
+ if isinstance(b, And):
333
+ sorted_bargs = sorted(b.args, key=str)
334
+ for barg in sorted_bargs:
335
+ self.process_rule(a, barg)
336
+
337
+ # a -> b | c --> !b & !c -> !a
338
+ # --> a & !b -> c
339
+ # --> a & !c -> b
340
+ elif isinstance(b, Or):
341
+ sorted_bargs = sorted(b.args, key=str)
342
+ # detect tautology first
343
+ if not isinstance(a, Logic): # Atom
344
+ # tautology: a -> a|c|...
345
+ if a in sorted_bargs:
346
+ raise TautologyDetected(a, b, 'a -> a|c|...')
347
+ self.process_rule(And(*[Not(barg) for barg in b.args]), Not(a))
348
+
349
+ for bidx in range(len(sorted_bargs)):
350
+ barg = sorted_bargs[bidx]
351
+ brest = sorted_bargs[:bidx] + sorted_bargs[bidx + 1:]
352
+ self.process_rule(And(a, Not(barg)), Or(*brest))
353
+
354
+ # left part
355
+
356
+ # a & b -> c --> IRREDUCIBLE CASE -- WE STORE IT AS IS
357
+ # (this will be the basis of beta-network)
358
+ elif isinstance(a, And):
359
+ sorted_aargs = sorted(a.args, key=str)
360
+ if b in sorted_aargs:
361
+ raise TautologyDetected(a, b, 'a & b -> a')
362
+ self.proved_rules.append((a, b))
363
+ # XXX NOTE at present we ignore !c -> !a | !b
364
+
365
+ elif isinstance(a, Or):
366
+ sorted_aargs = sorted(a.args, key=str)
367
+ if b in sorted_aargs:
368
+ raise TautologyDetected(a, b, 'a | b -> a')
369
+ for aarg in sorted_aargs:
370
+ self.process_rule(aarg, b)
371
+
372
+ else:
373
+ # both `a` and `b` are atoms
374
+ self.proved_rules.append((a, b)) # a -> b
375
+ self.proved_rules.append((Not(b), Not(a))) # !b -> !a
376
+
377
+ ########################################
378
+
379
+
380
+ class FactRules:
381
+ """Rules that describe how to deduce facts in logic space
382
+
383
+ When defined, these rules allow implications to quickly be determined
384
+ for a set of facts. For this precomputed deduction tables are used.
385
+ see `deduce_all_facts` (forward-chaining)
386
+
387
+ Also it is possible to gather prerequisites for a fact, which is tried
388
+ to be proven. (backward-chaining)
389
+
390
+
391
+ Definition Syntax
392
+ -----------------
393
+
394
+ a -> b -- a=T -> b=T (and automatically b=F -> a=F)
395
+ a -> !b -- a=T -> b=F
396
+ a == b -- a -> b & b -> a
397
+ a -> b & c -- a=T -> b=T & c=T
398
+ # TODO b | c
399
+
400
+
401
+ Internals
402
+ ---------
403
+
404
+ .full_implications[k, v]: all the implications of fact k=v
405
+ .beta_triggers[k, v]: beta rules that might be triggered when k=v
406
+ .prereq -- {} k <- [] of k's prerequisites
407
+
408
+ .defined_facts -- set of defined fact names
409
+ """
410
+
411
+ def __init__(self, rules):
412
+ """Compile rules into internal lookup tables"""
413
+
414
+ if isinstance(rules, str):
415
+ rules = rules.splitlines()
416
+
417
+ # --- parse and process rules ---
418
+ P = Prover()
419
+
420
+ for rule in rules:
421
+ # XXX `a` is hardcoded to be always atom
422
+ a, op, b = rule.split(None, 2)
423
+
424
+ a = Logic.fromstring(a)
425
+ b = Logic.fromstring(b)
426
+
427
+ if op == '->':
428
+ P.process_rule(a, b)
429
+ elif op == '==':
430
+ P.process_rule(a, b)
431
+ P.process_rule(b, a)
432
+ else:
433
+ raise ValueError('unknown op %r' % op)
434
+
435
+ # --- build deduction networks ---
436
+ self.beta_rules = []
437
+ for bcond, bimpl in P.rules_beta:
438
+ self.beta_rules.append(
439
+ ({_as_pair(a) for a in bcond.args}, _as_pair(bimpl)))
440
+
441
+ # deduce alpha implications
442
+ impl_a = deduce_alpha_implications(P.rules_alpha)
443
+
444
+ # now:
445
+ # - apply beta rules to alpha chains (static extension), and
446
+ # - further associate beta rules to alpha chain (for inference
447
+ # at runtime)
448
+ impl_ab = apply_beta_to_alpha_route(impl_a, P.rules_beta)
449
+
450
+ # extract defined fact names
451
+ self.defined_facts = {_base_fact(k) for k in impl_ab.keys()}
452
+
453
+ # build rels (forward chains)
454
+ full_implications = defaultdict(set)
455
+ beta_triggers = defaultdict(set)
456
+ for k, (impl, betaidxs) in impl_ab.items():
457
+ full_implications[_as_pair(k)] = {_as_pair(i) for i in impl}
458
+ beta_triggers[_as_pair(k)] = betaidxs
459
+
460
+ self.full_implications = full_implications
461
+ self.beta_triggers = beta_triggers
462
+
463
+ # build prereq (backward chains)
464
+ prereq = defaultdict(set)
465
+ rel_prereq = rules_2prereq(full_implications)
466
+ for k, pitems in rel_prereq.items():
467
+ prereq[k] |= pitems
468
+ self.prereq = prereq
469
+
470
+ def _to_python(self) -> str:
471
+ """ Generate a string with plain python representation of the instance """
472
+ return '\n'.join(self.print_rules())
473
+
474
+ @classmethod
475
+ def _from_python(cls, data : dict):
476
+ """ Generate an instance from the plain python representation """
477
+ self = cls('')
478
+ for key in ['full_implications', 'beta_triggers', 'prereq']:
479
+ d=defaultdict(set)
480
+ d.update(data[key])
481
+ setattr(self, key, d)
482
+ self.beta_rules = data['beta_rules']
483
+ self.defined_facts = set(data['defined_facts'])
484
+
485
+ return self
486
+
487
+ def _defined_facts_lines(self):
488
+ yield 'defined_facts = ['
489
+ for fact in sorted(self.defined_facts):
490
+ yield f' {fact!r},'
491
+ yield '] # defined_facts'
492
+
493
+ def _full_implications_lines(self):
494
+ yield 'full_implications = dict( ['
495
+ for fact in sorted(self.defined_facts):
496
+ for value in (True, False):
497
+ yield f' # Implications of {fact} = {value}:'
498
+ yield f' (({fact!r}, {value!r}), set( ('
499
+ implications = self.full_implications[(fact, value)]
500
+ for implied in sorted(implications):
501
+ yield f' {implied!r},'
502
+ yield ' ) ),'
503
+ yield ' ),'
504
+ yield ' ] ) # full_implications'
505
+
506
+ def _prereq_lines(self):
507
+ yield 'prereq = {'
508
+ yield ''
509
+ for fact in sorted(self.prereq):
510
+ yield f' # facts that could determine the value of {fact}'
511
+ yield f' {fact!r}: {{'
512
+ for pfact in sorted(self.prereq[fact]):
513
+ yield f' {pfact!r},'
514
+ yield ' },'
515
+ yield ''
516
+ yield '} # prereq'
517
+
518
+ def _beta_rules_lines(self):
519
+ reverse_implications = defaultdict(list)
520
+ for n, (pre, implied) in enumerate(self.beta_rules):
521
+ reverse_implications[implied].append((pre, n))
522
+
523
+ yield '# Note: the order of the beta rules is used in the beta_triggers'
524
+ yield 'beta_rules = ['
525
+ yield ''
526
+ m = 0
527
+ indices = {}
528
+ for implied in sorted(reverse_implications):
529
+ fact, value = implied
530
+ yield f' # Rules implying {fact} = {value}'
531
+ for pre, n in reverse_implications[implied]:
532
+ indices[n] = m
533
+ m += 1
534
+ setstr = ", ".join(map(str, sorted(pre)))
535
+ yield f' ({{{setstr}}},'
536
+ yield f' {implied!r}),'
537
+ yield ''
538
+ yield '] # beta_rules'
539
+
540
+ yield 'beta_triggers = {'
541
+ for query in sorted(self.beta_triggers):
542
+ fact, value = query
543
+ triggers = [indices[n] for n in self.beta_triggers[query]]
544
+ yield f' {query!r}: {triggers!r},'
545
+ yield '} # beta_triggers'
546
+
547
+ def print_rules(self) -> Iterator[str]:
548
+ """ Returns a generator with lines to represent the facts and rules """
549
+ yield from self._defined_facts_lines()
550
+ yield ''
551
+ yield ''
552
+ yield from self._full_implications_lines()
553
+ yield ''
554
+ yield ''
555
+ yield from self._prereq_lines()
556
+ yield ''
557
+ yield ''
558
+ yield from self._beta_rules_lines()
559
+ yield ''
560
+ yield ''
561
+ yield "generated_assumptions = {'defined_facts': defined_facts, 'full_implications': full_implications,"
562
+ yield " 'prereq': prereq, 'beta_rules': beta_rules, 'beta_triggers': beta_triggers}"
563
+
564
+
565
+ class InconsistentAssumptions(ValueError):
566
+ def __str__(self):
567
+ kb, fact, value = self.args
568
+ return "%s, %s=%s" % (kb, fact, value)
569
+
570
+
571
+ class FactKB(dict):
572
+ """
573
+ A simple propositional knowledge base relying on compiled inference rules.
574
+ """
575
+ def __str__(self):
576
+ return '{\n%s}' % ',\n'.join(
577
+ ["\t%s: %s" % i for i in sorted(self.items())])
578
+
579
+ def __init__(self, rules):
580
+ self.rules = rules
581
+
582
+ def _tell(self, k, v):
583
+ """Add fact k=v to the knowledge base.
584
+
585
+ Returns True if the KB has actually been updated, False otherwise.
586
+ """
587
+ if k in self and self[k] is not None:
588
+ if self[k] == v:
589
+ return False
590
+ else:
591
+ raise InconsistentAssumptions(self, k, v)
592
+ else:
593
+ self[k] = v
594
+ return True
595
+
596
+ # *********************************************
597
+ # * This is the workhorse, so keep it *fast*. *
598
+ # *********************************************
599
+ def deduce_all_facts(self, facts):
600
+ """
601
+ Update the KB with all the implications of a list of facts.
602
+
603
+ Facts can be specified as a dictionary or as a list of (key, value)
604
+ pairs.
605
+ """
606
+ # keep frequently used attributes locally, so we'll avoid extra
607
+ # attribute access overhead
608
+ full_implications = self.rules.full_implications
609
+ beta_triggers = self.rules.beta_triggers
610
+ beta_rules = self.rules.beta_rules
611
+
612
+ if isinstance(facts, dict):
613
+ facts = facts.items()
614
+
615
+ while facts:
616
+ beta_maytrigger = set()
617
+
618
+ # --- alpha chains ---
619
+ for k, v in facts:
620
+ if not self._tell(k, v) or v is None:
621
+ continue
622
+
623
+ # lookup routing tables
624
+ for key, value in full_implications[k, v]:
625
+ self._tell(key, value)
626
+
627
+ beta_maytrigger.update(beta_triggers[k, v])
628
+
629
+ # --- beta chains ---
630
+ facts = []
631
+ for bidx in beta_maytrigger:
632
+ bcond, bimpl = beta_rules[bidx]
633
+ if all(self.get(k) is v for k, v in bcond):
634
+ facts.append(bimpl)
env-llmeval/lib/python3.10/site-packages/sympy/core/kind.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module to efficiently partition SymPy objects.
3
+
4
+ This system is introduced because class of SymPy object does not always
5
+ represent the mathematical classification of the entity. For example,
6
+ ``Integral(1, x)`` and ``Integral(Matrix([1,2]), x)`` are both instance
7
+ of ``Integral`` class. However the former is number and the latter is
8
+ matrix.
9
+
10
+ One way to resolve this is defining subclass for each mathematical type,
11
+ such as ``MatAdd`` for the addition between matrices. Basic algebraic
12
+ operation such as addition or multiplication take this approach, but
13
+ defining every class for every mathematical object is not scalable.
14
+
15
+ Therefore, we define the "kind" of the object and let the expression
16
+ infer the kind of itself from its arguments. Function and class can
17
+ filter the arguments by their kind, and behave differently according to
18
+ the type of itself.
19
+
20
+ This module defines basic kinds for core objects. Other kinds such as
21
+ ``ArrayKind`` or ``MatrixKind`` can be found in corresponding modules.
22
+
23
+ .. notes::
24
+ This approach is experimental, and can be replaced or deleted in the future.
25
+ See https://github.com/sympy/sympy/pull/20549.
26
+ """
27
+
28
+ from collections import defaultdict
29
+
30
+ from .cache import cacheit
31
+ from sympy.multipledispatch.dispatcher import (Dispatcher,
32
+ ambiguity_warn, ambiguity_register_error_ignore_dup,
33
+ str_signature, RaiseNotImplementedError)
34
+
35
+
36
+ class KindMeta(type):
37
+ """
38
+ Metaclass for ``Kind``.
39
+
40
+ Assigns empty ``dict`` as class attribute ``_inst`` for every class,
41
+ in order to endow singleton-like behavior.
42
+ """
43
+ def __new__(cls, clsname, bases, dct):
44
+ dct['_inst'] = {}
45
+ return super().__new__(cls, clsname, bases, dct)
46
+
47
+
48
+ class Kind(object, metaclass=KindMeta):
49
+ """
50
+ Base class for kinds.
51
+
52
+ Kind of the object represents the mathematical classification that
53
+ the entity falls into. It is expected that functions and classes
54
+ recognize and filter the argument by its kind.
55
+
56
+ Kind of every object must be carefully selected so that it shows the
57
+ intention of design. Expressions may have different kind according
58
+ to the kind of its arguments. For example, arguments of ``Add``
59
+ must have common kind since addition is group operator, and the
60
+ resulting ``Add()`` has the same kind.
61
+
62
+ For the performance, each kind is as broad as possible and is not
63
+ based on set theory. For example, ``NumberKind`` includes not only
64
+ complex number but expression containing ``S.Infinity`` or ``S.NaN``
65
+ which are not strictly number.
66
+
67
+ Kind may have arguments as parameter. For example, ``MatrixKind()``
68
+ may be constructed with one element which represents the kind of its
69
+ elements.
70
+
71
+ ``Kind`` behaves in singleton-like fashion. Same signature will
72
+ return the same object.
73
+
74
+ """
75
+ def __new__(cls, *args):
76
+ if args in cls._inst:
77
+ inst = cls._inst[args]
78
+ else:
79
+ inst = super().__new__(cls)
80
+ cls._inst[args] = inst
81
+ return inst
82
+
83
+
84
+ class _UndefinedKind(Kind):
85
+ """
86
+ Default kind for all SymPy object. If the kind is not defined for
87
+ the object, or if the object cannot infer the kind from its
88
+ arguments, this will be returned.
89
+
90
+ Examples
91
+ ========
92
+
93
+ >>> from sympy import Expr
94
+ >>> Expr().kind
95
+ UndefinedKind
96
+ """
97
+ def __new__(cls):
98
+ return super().__new__(cls)
99
+
100
+ def __repr__(self):
101
+ return "UndefinedKind"
102
+
103
+ UndefinedKind = _UndefinedKind()
104
+
105
+
106
+ class _NumberKind(Kind):
107
+ """
108
+ Kind for all numeric object.
109
+
110
+ This kind represents every number, including complex numbers,
111
+ infinity and ``S.NaN``. Other objects such as quaternions do not
112
+ have this kind.
113
+
114
+ Most ``Expr`` are initially designed to represent the number, so
115
+ this will be the most common kind in SymPy core. For example
116
+ ``Symbol()``, which represents a scalar, has this kind as long as it
117
+ is commutative.
118
+
119
+ Numbers form a field. Any operation between number-kind objects will
120
+ result this kind as well.
121
+
122
+ Examples
123
+ ========
124
+
125
+ >>> from sympy import S, oo, Symbol
126
+ >>> S.One.kind
127
+ NumberKind
128
+ >>> (-oo).kind
129
+ NumberKind
130
+ >>> S.NaN.kind
131
+ NumberKind
132
+
133
+ Commutative symbol are treated as number.
134
+
135
+ >>> x = Symbol('x')
136
+ >>> x.kind
137
+ NumberKind
138
+ >>> Symbol('y', commutative=False).kind
139
+ UndefinedKind
140
+
141
+ Operation between numbers results number.
142
+
143
+ >>> (x+1).kind
144
+ NumberKind
145
+
146
+ See Also
147
+ ========
148
+
149
+ sympy.core.expr.Expr.is_Number : check if the object is strictly
150
+ subclass of ``Number`` class.
151
+
152
+ sympy.core.expr.Expr.is_number : check if the object is number
153
+ without any free symbol.
154
+
155
+ """
156
+ def __new__(cls):
157
+ return super().__new__(cls)
158
+
159
+ def __repr__(self):
160
+ return "NumberKind"
161
+
162
+ NumberKind = _NumberKind()
163
+
164
+
165
+ class _BooleanKind(Kind):
166
+ """
167
+ Kind for boolean objects.
168
+
169
+ SymPy's ``S.true``, ``S.false``, and built-in ``True`` and ``False``
170
+ have this kind. Boolean number ``1`` and ``0`` are not relevant.
171
+
172
+ Examples
173
+ ========
174
+
175
+ >>> from sympy import S, Q
176
+ >>> S.true.kind
177
+ BooleanKind
178
+ >>> Q.even(3).kind
179
+ BooleanKind
180
+ """
181
+ def __new__(cls):
182
+ return super().__new__(cls)
183
+
184
+ def __repr__(self):
185
+ return "BooleanKind"
186
+
187
+ BooleanKind = _BooleanKind()
188
+
189
+
190
+ class KindDispatcher:
191
+ """
192
+ Dispatcher to select a kind from multiple kinds by binary dispatching.
193
+
194
+ .. notes::
195
+ This approach is experimental, and can be replaced or deleted in
196
+ the future.
197
+
198
+ Explanation
199
+ ===========
200
+
201
+ SymPy object's :obj:`sympy.core.kind.Kind()` vaguely represents the
202
+ algebraic structure where the object belongs to. Therefore, with
203
+ given operation, we can always find a dominating kind among the
204
+ different kinds. This class selects the kind by recursive binary
205
+ dispatching. If the result cannot be determined, ``UndefinedKind``
206
+ is returned.
207
+
208
+ Examples
209
+ ========
210
+
211
+ Multiplication between numbers return number.
212
+
213
+ >>> from sympy import NumberKind, Mul
214
+ >>> Mul._kind_dispatcher(NumberKind, NumberKind)
215
+ NumberKind
216
+
217
+ Multiplication between number and unknown-kind object returns unknown kind.
218
+
219
+ >>> from sympy import UndefinedKind
220
+ >>> Mul._kind_dispatcher(NumberKind, UndefinedKind)
221
+ UndefinedKind
222
+
223
+ Any number and order of kinds is allowed.
224
+
225
+ >>> Mul._kind_dispatcher(UndefinedKind, NumberKind)
226
+ UndefinedKind
227
+ >>> Mul._kind_dispatcher(NumberKind, UndefinedKind, NumberKind)
228
+ UndefinedKind
229
+
230
+ Since matrix forms a vector space over scalar field, multiplication
231
+ between matrix with numeric element and number returns matrix with
232
+ numeric element.
233
+
234
+ >>> from sympy.matrices import MatrixKind
235
+ >>> Mul._kind_dispatcher(MatrixKind(NumberKind), NumberKind)
236
+ MatrixKind(NumberKind)
237
+
238
+ If a matrix with number element and another matrix with unknown-kind
239
+ element are multiplied, we know that the result is matrix but the
240
+ kind of its elements is unknown.
241
+
242
+ >>> Mul._kind_dispatcher(MatrixKind(NumberKind), MatrixKind(UndefinedKind))
243
+ MatrixKind(UndefinedKind)
244
+
245
+ Parameters
246
+ ==========
247
+
248
+ name : str
249
+
250
+ commutative : bool, optional
251
+ If True, binary dispatch will be automatically registered in
252
+ reversed order as well.
253
+
254
+ doc : str, optional
255
+
256
+ """
257
+ def __init__(self, name, commutative=False, doc=None):
258
+ self.name = name
259
+ self.doc = doc
260
+ self.commutative = commutative
261
+ self._dispatcher = Dispatcher(name)
262
+
263
+ def __repr__(self):
264
+ return "<dispatched %s>" % self.name
265
+
266
+ def register(self, *types, **kwargs):
267
+ """
268
+ Register the binary dispatcher for two kind classes.
269
+
270
+ If *self.commutative* is ``True``, signature in reversed order is
271
+ automatically registered as well.
272
+ """
273
+ on_ambiguity = kwargs.pop("on_ambiguity", None)
274
+ if not on_ambiguity:
275
+ if self.commutative:
276
+ on_ambiguity = ambiguity_register_error_ignore_dup
277
+ else:
278
+ on_ambiguity = ambiguity_warn
279
+ kwargs.update(on_ambiguity=on_ambiguity)
280
+
281
+ if not len(types) == 2:
282
+ raise RuntimeError(
283
+ "Only binary dispatch is supported, but got %s types: <%s>." % (
284
+ len(types), str_signature(types)
285
+ ))
286
+
287
+ def _(func):
288
+ self._dispatcher.add(types, func, **kwargs)
289
+ if self.commutative:
290
+ self._dispatcher.add(tuple(reversed(types)), func, **kwargs)
291
+ return _
292
+
293
+ def __call__(self, *args, **kwargs):
294
+ if self.commutative:
295
+ kinds = frozenset(args)
296
+ else:
297
+ kinds = []
298
+ prev = None
299
+ for a in args:
300
+ if prev is not a:
301
+ kinds.append(a)
302
+ prev = a
303
+ return self.dispatch_kinds(kinds, **kwargs)
304
+
305
+ @cacheit
306
+ def dispatch_kinds(self, kinds, **kwargs):
307
+ # Quick exit for the case where all kinds are same
308
+ if len(kinds) == 1:
309
+ result, = kinds
310
+ if not isinstance(result, Kind):
311
+ raise RuntimeError("%s is not a kind." % result)
312
+ return result
313
+
314
+ for i,kind in enumerate(kinds):
315
+ if not isinstance(kind, Kind):
316
+ raise RuntimeError("%s is not a kind." % kind)
317
+
318
+ if i == 0:
319
+ result = kind
320
+ else:
321
+ prev_kind = result
322
+
323
+ t1, t2 = type(prev_kind), type(kind)
324
+ k1, k2 = prev_kind, kind
325
+ func = self._dispatcher.dispatch(t1, t2)
326
+ if func is None and self.commutative:
327
+ # try reversed order
328
+ func = self._dispatcher.dispatch(t2, t1)
329
+ k1, k2 = k2, k1
330
+ if func is None:
331
+ # unregistered kind relation
332
+ result = UndefinedKind
333
+ else:
334
+ result = func(k1, k2)
335
+ if not isinstance(result, Kind):
336
+ raise RuntimeError(
337
+ "Dispatcher for {!r} and {!r} must return a Kind, but got {!r}".format(
338
+ prev_kind, kind, result
339
+ ))
340
+
341
+ return result
342
+
343
+ @property
344
+ def __doc__(self):
345
+ docs = [
346
+ "Kind dispatcher : %s" % self.name,
347
+ "Note that support for this is experimental. See the docs for :class:`KindDispatcher` for details"
348
+ ]
349
+
350
+ if self.doc:
351
+ docs.append(self.doc)
352
+
353
+ s = "Registered kind classes\n"
354
+ s += '=' * len(s)
355
+ docs.append(s)
356
+
357
+ amb_sigs = []
358
+
359
+ typ_sigs = defaultdict(list)
360
+ for sigs in self._dispatcher.ordering[::-1]:
361
+ key = self._dispatcher.funcs[sigs]
362
+ typ_sigs[key].append(sigs)
363
+
364
+ for func, sigs in typ_sigs.items():
365
+
366
+ sigs_str = ', '.join('<%s>' % str_signature(sig) for sig in sigs)
367
+
368
+ if isinstance(func, RaiseNotImplementedError):
369
+ amb_sigs.append(sigs_str)
370
+ continue
371
+
372
+ s = 'Inputs: %s\n' % sigs_str
373
+ s += '-' * len(s) + '\n'
374
+ if func.__doc__:
375
+ s += func.__doc__.strip()
376
+ else:
377
+ s += func.__name__
378
+ docs.append(s)
379
+
380
+ if amb_sigs:
381
+ s = "Ambiguous kind classes\n"
382
+ s += '=' * len(s)
383
+ docs.append(s)
384
+
385
+ s = '\n'.join(amb_sigs)
386
+ docs.append(s)
387
+
388
+ return '\n\n'.join(docs)
env-llmeval/lib/python3.10/site-packages/sympy/core/logic.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logic expressions handling
2
+
3
+ NOTE
4
+ ----
5
+
6
+ at present this is mainly needed for facts.py, feel free however to improve
7
+ this stuff for general purpose.
8
+ """
9
+
10
+ from __future__ import annotations
11
+ from typing import Optional
12
+
13
+ # Type of a fuzzy bool
14
+ FuzzyBool = Optional[bool]
15
+
16
+
17
+ def _torf(args):
18
+ """Return True if all args are True, False if they
19
+ are all False, else None.
20
+
21
+ >>> from sympy.core.logic import _torf
22
+ >>> _torf((True, True))
23
+ True
24
+ >>> _torf((False, False))
25
+ False
26
+ >>> _torf((True, False))
27
+ """
28
+ sawT = sawF = False
29
+ for a in args:
30
+ if a is True:
31
+ if sawF:
32
+ return
33
+ sawT = True
34
+ elif a is False:
35
+ if sawT:
36
+ return
37
+ sawF = True
38
+ else:
39
+ return
40
+ return sawT
41
+
42
+
43
+ def _fuzzy_group(args, quick_exit=False):
44
+ """Return True if all args are True, None if there is any None else False
45
+ unless ``quick_exit`` is True (then return None as soon as a second False
46
+ is seen.
47
+
48
+ ``_fuzzy_group`` is like ``fuzzy_and`` except that it is more
49
+ conservative in returning a False, waiting to make sure that all
50
+ arguments are True or False and returning None if any arguments are
51
+ None. It also has the capability of permiting only a single False and
52
+ returning None if more than one is seen. For example, the presence of a
53
+ single transcendental amongst rationals would indicate that the group is
54
+ no longer rational; but a second transcendental in the group would make the
55
+ determination impossible.
56
+
57
+
58
+ Examples
59
+ ========
60
+
61
+ >>> from sympy.core.logic import _fuzzy_group
62
+
63
+ By default, multiple Falses mean the group is broken:
64
+
65
+ >>> _fuzzy_group([False, False, True])
66
+ False
67
+
68
+ If multiple Falses mean the group status is unknown then set
69
+ `quick_exit` to True so None can be returned when the 2nd False is seen:
70
+
71
+ >>> _fuzzy_group([False, False, True], quick_exit=True)
72
+
73
+ But if only a single False is seen then the group is known to
74
+ be broken:
75
+
76
+ >>> _fuzzy_group([False, True, True], quick_exit=True)
77
+ False
78
+
79
+ """
80
+ saw_other = False
81
+ for a in args:
82
+ if a is True:
83
+ continue
84
+ if a is None:
85
+ return
86
+ if quick_exit and saw_other:
87
+ return
88
+ saw_other = True
89
+ return not saw_other
90
+
91
+
92
+ def fuzzy_bool(x):
93
+ """Return True, False or None according to x.
94
+
95
+ Whereas bool(x) returns True or False, fuzzy_bool allows
96
+ for the None value and non-false values (which become None), too.
97
+
98
+ Examples
99
+ ========
100
+
101
+ >>> from sympy.core.logic import fuzzy_bool
102
+ >>> from sympy.abc import x
103
+ >>> fuzzy_bool(x), fuzzy_bool(None)
104
+ (None, None)
105
+ >>> bool(x), bool(None)
106
+ (True, False)
107
+
108
+ """
109
+ if x is None:
110
+ return None
111
+ if x in (True, False):
112
+ return bool(x)
113
+
114
+
115
+ def fuzzy_and(args):
116
+ """Return True (all True), False (any False) or None.
117
+
118
+ Examples
119
+ ========
120
+
121
+ >>> from sympy.core.logic import fuzzy_and
122
+ >>> from sympy import Dummy
123
+
124
+ If you had a list of objects to test the commutivity of
125
+ and you want the fuzzy_and logic applied, passing an
126
+ iterator will allow the commutativity to only be computed
127
+ as many times as necessary. With this list, False can be
128
+ returned after analyzing the first symbol:
129
+
130
+ >>> syms = [Dummy(commutative=False), Dummy()]
131
+ >>> fuzzy_and(s.is_commutative for s in syms)
132
+ False
133
+
134
+ That False would require less work than if a list of pre-computed
135
+ items was sent:
136
+
137
+ >>> fuzzy_and([s.is_commutative for s in syms])
138
+ False
139
+ """
140
+
141
+ rv = True
142
+ for ai in args:
143
+ ai = fuzzy_bool(ai)
144
+ if ai is False:
145
+ return False
146
+ if rv: # this will stop updating if a None is ever trapped
147
+ rv = ai
148
+ return rv
149
+
150
+
151
+ def fuzzy_not(v):
152
+ """
153
+ Not in fuzzy logic
154
+
155
+ Return None if `v` is None else `not v`.
156
+
157
+ Examples
158
+ ========
159
+
160
+ >>> from sympy.core.logic import fuzzy_not
161
+ >>> fuzzy_not(True)
162
+ False
163
+ >>> fuzzy_not(None)
164
+ >>> fuzzy_not(False)
165
+ True
166
+
167
+ """
168
+ if v is None:
169
+ return v
170
+ else:
171
+ return not v
172
+
173
+
174
+ def fuzzy_or(args):
175
+ """
176
+ Or in fuzzy logic. Returns True (any True), False (all False), or None
177
+
178
+ See the docstrings of fuzzy_and and fuzzy_not for more info. fuzzy_or is
179
+ related to the two by the standard De Morgan's law.
180
+
181
+ >>> from sympy.core.logic import fuzzy_or
182
+ >>> fuzzy_or([True, False])
183
+ True
184
+ >>> fuzzy_or([True, None])
185
+ True
186
+ >>> fuzzy_or([False, False])
187
+ False
188
+ >>> print(fuzzy_or([False, None]))
189
+ None
190
+
191
+ """
192
+ rv = False
193
+ for ai in args:
194
+ ai = fuzzy_bool(ai)
195
+ if ai is True:
196
+ return True
197
+ if rv is False: # this will stop updating if a None is ever trapped
198
+ rv = ai
199
+ return rv
200
+
201
+
202
+ def fuzzy_xor(args):
203
+ """Return None if any element of args is not True or False, else
204
+ True (if there are an odd number of True elements), else False."""
205
+ t = f = 0
206
+ for a in args:
207
+ ai = fuzzy_bool(a)
208
+ if ai:
209
+ t += 1
210
+ elif ai is False:
211
+ f += 1
212
+ else:
213
+ return
214
+ return t % 2 == 1
215
+
216
+
217
+ def fuzzy_nand(args):
218
+ """Return False if all args are True, True if they are all False,
219
+ else None."""
220
+ return fuzzy_not(fuzzy_and(args))
221
+
222
+
223
+ class Logic:
224
+ """Logical expression"""
225
+ # {} 'op' -> LogicClass
226
+ op_2class: dict[str, type[Logic]] = {}
227
+
228
+ def __new__(cls, *args):
229
+ obj = object.__new__(cls)
230
+ obj.args = args
231
+ return obj
232
+
233
+ def __getnewargs__(self):
234
+ return self.args
235
+
236
+ def __hash__(self):
237
+ return hash((type(self).__name__,) + tuple(self.args))
238
+
239
+ def __eq__(a, b):
240
+ if not isinstance(b, type(a)):
241
+ return False
242
+ else:
243
+ return a.args == b.args
244
+
245
+ def __ne__(a, b):
246
+ if not isinstance(b, type(a)):
247
+ return True
248
+ else:
249
+ return a.args != b.args
250
+
251
+ def __lt__(self, other):
252
+ if self.__cmp__(other) == -1:
253
+ return True
254
+ return False
255
+
256
+ def __cmp__(self, other):
257
+ if type(self) is not type(other):
258
+ a = str(type(self))
259
+ b = str(type(other))
260
+ else:
261
+ a = self.args
262
+ b = other.args
263
+ return (a > b) - (a < b)
264
+
265
+ def __str__(self):
266
+ return '%s(%s)' % (self.__class__.__name__,
267
+ ', '.join(str(a) for a in self.args))
268
+
269
+ __repr__ = __str__
270
+
271
+ @staticmethod
272
+ def fromstring(text):
273
+ """Logic from string with space around & and | but none after !.
274
+
275
+ e.g.
276
+
277
+ !a & b | c
278
+ """
279
+ lexpr = None # current logical expression
280
+ schedop = None # scheduled operation
281
+ for term in text.split():
282
+ # operation symbol
283
+ if term in '&|':
284
+ if schedop is not None:
285
+ raise ValueError(
286
+ 'double op forbidden: "%s %s"' % (term, schedop))
287
+ if lexpr is None:
288
+ raise ValueError(
289
+ '%s cannot be in the beginning of expression' % term)
290
+ schedop = term
291
+ continue
292
+ if '&' in term or '|' in term:
293
+ raise ValueError('& and | must have space around them')
294
+ if term[0] == '!':
295
+ if len(term) == 1:
296
+ raise ValueError('do not include space after "!"')
297
+ term = Not(term[1:])
298
+
299
+ # already scheduled operation, e.g. '&'
300
+ if schedop:
301
+ lexpr = Logic.op_2class[schedop](lexpr, term)
302
+ schedop = None
303
+ continue
304
+
305
+ # this should be atom
306
+ if lexpr is not None:
307
+ raise ValueError(
308
+ 'missing op between "%s" and "%s"' % (lexpr, term))
309
+
310
+ lexpr = term
311
+
312
+ # let's check that we ended up in correct state
313
+ if schedop is not None:
314
+ raise ValueError('premature end-of-expression in "%s"' % text)
315
+ if lexpr is None:
316
+ raise ValueError('"%s" is empty' % text)
317
+
318
+ # everything looks good now
319
+ return lexpr
320
+
321
+
322
+ class AndOr_Base(Logic):
323
+
324
+ def __new__(cls, *args):
325
+ bargs = []
326
+ for a in args:
327
+ if a == cls.op_x_notx:
328
+ return a
329
+ elif a == (not cls.op_x_notx):
330
+ continue # skip this argument
331
+ bargs.append(a)
332
+
333
+ args = sorted(set(cls.flatten(bargs)), key=hash)
334
+
335
+ for a in args:
336
+ if Not(a) in args:
337
+ return cls.op_x_notx
338
+
339
+ if len(args) == 1:
340
+ return args.pop()
341
+ elif len(args) == 0:
342
+ return not cls.op_x_notx
343
+
344
+ return Logic.__new__(cls, *args)
345
+
346
+ @classmethod
347
+ def flatten(cls, args):
348
+ # quick-n-dirty flattening for And and Or
349
+ args_queue = list(args)
350
+ res = []
351
+
352
+ while True:
353
+ try:
354
+ arg = args_queue.pop(0)
355
+ except IndexError:
356
+ break
357
+ if isinstance(arg, Logic):
358
+ if isinstance(arg, cls):
359
+ args_queue.extend(arg.args)
360
+ continue
361
+ res.append(arg)
362
+
363
+ args = tuple(res)
364
+ return args
365
+
366
+
367
+ class And(AndOr_Base):
368
+ op_x_notx = False
369
+
370
+ def _eval_propagate_not(self):
371
+ # !(a&b&c ...) == !a | !b | !c ...
372
+ return Or(*[Not(a) for a in self.args])
373
+
374
+ # (a|b|...) & c == (a&c) | (b&c) | ...
375
+ def expand(self):
376
+
377
+ # first locate Or
378
+ for i, arg in enumerate(self.args):
379
+ if isinstance(arg, Or):
380
+ arest = self.args[:i] + self.args[i + 1:]
381
+
382
+ orterms = [And(*(arest + (a,))) for a in arg.args]
383
+ for j in range(len(orterms)):
384
+ if isinstance(orterms[j], Logic):
385
+ orterms[j] = orterms[j].expand()
386
+
387
+ res = Or(*orterms)
388
+ return res
389
+
390
+ return self
391
+
392
+
393
+ class Or(AndOr_Base):
394
+ op_x_notx = True
395
+
396
+ def _eval_propagate_not(self):
397
+ # !(a|b|c ...) == !a & !b & !c ...
398
+ return And(*[Not(a) for a in self.args])
399
+
400
+
401
+ class Not(Logic):
402
+
403
+ def __new__(cls, arg):
404
+ if isinstance(arg, str):
405
+ return Logic.__new__(cls, arg)
406
+
407
+ elif isinstance(arg, bool):
408
+ return not arg
409
+ elif isinstance(arg, Not):
410
+ return arg.args[0]
411
+
412
+ elif isinstance(arg, Logic):
413
+ # XXX this is a hack to expand right from the beginning
414
+ arg = arg._eval_propagate_not()
415
+ return arg
416
+
417
+ else:
418
+ raise ValueError('Not: unknown argument %r' % (arg,))
419
+
420
+ @property
421
+ def arg(self):
422
+ return self.args[0]
423
+
424
+
425
+ Logic.op_2class['&'] = And
426
+ Logic.op_2class['|'] = Or
427
+ Logic.op_2class['!'] = Not
env-llmeval/lib/python3.10/site-packages/sympy/core/mul.py ADDED
@@ -0,0 +1,2195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple as tTuple
2
+ from collections import defaultdict
3
+ from functools import cmp_to_key, reduce
4
+ from itertools import product
5
+ import operator
6
+
7
+ from .sympify import sympify
8
+ from .basic import Basic
9
+ from .singleton import S
10
+ from .operations import AssocOp, AssocOpDispatcher
11
+ from .cache import cacheit
12
+ from .logic import fuzzy_not, _fuzzy_group
13
+ from .expr import Expr
14
+ from .parameters import global_parameters
15
+ from .kind import KindDispatcher
16
+ from .traversal import bottom_up
17
+
18
+ from sympy.utilities.iterables import sift
19
+
20
+ # internal marker to indicate:
21
+ # "there are still non-commutative objects -- don't forget to process them"
22
+ class NC_Marker:
23
+ is_Order = False
24
+ is_Mul = False
25
+ is_Number = False
26
+ is_Poly = False
27
+
28
+ is_commutative = False
29
+
30
+
31
+ # Key for sorting commutative args in canonical order
32
+ _args_sortkey = cmp_to_key(Basic.compare)
33
+ def _mulsort(args):
34
+ # in-place sorting of args
35
+ args.sort(key=_args_sortkey)
36
+
37
+
38
+ def _unevaluated_Mul(*args):
39
+ """Return a well-formed unevaluated Mul: Numbers are collected and
40
+ put in slot 0, any arguments that are Muls will be flattened, and args
41
+ are sorted. Use this when args have changed but you still want to return
42
+ an unevaluated Mul.
43
+
44
+ Examples
45
+ ========
46
+
47
+ >>> from sympy.core.mul import _unevaluated_Mul as uMul
48
+ >>> from sympy import S, sqrt, Mul
49
+ >>> from sympy.abc import x
50
+ >>> a = uMul(*[S(3.0), x, S(2)])
51
+ >>> a.args[0]
52
+ 6.00000000000000
53
+ >>> a.args[1]
54
+ x
55
+
56
+ Two unevaluated Muls with the same arguments will
57
+ always compare as equal during testing:
58
+
59
+ >>> m = uMul(sqrt(2), sqrt(3))
60
+ >>> m == uMul(sqrt(3), sqrt(2))
61
+ True
62
+ >>> u = Mul(sqrt(3), sqrt(2), evaluate=False)
63
+ >>> m == uMul(u)
64
+ True
65
+ >>> m == Mul(*m.args)
66
+ False
67
+
68
+ """
69
+ args = list(args)
70
+ newargs = []
71
+ ncargs = []
72
+ co = S.One
73
+ while args:
74
+ a = args.pop()
75
+ if a.is_Mul:
76
+ c, nc = a.args_cnc()
77
+ args.extend(c)
78
+ if nc:
79
+ ncargs.append(Mul._from_args(nc))
80
+ elif a.is_Number:
81
+ co *= a
82
+ else:
83
+ newargs.append(a)
84
+ _mulsort(newargs)
85
+ if co is not S.One:
86
+ newargs.insert(0, co)
87
+ if ncargs:
88
+ newargs.append(Mul._from_args(ncargs))
89
+ return Mul._from_args(newargs)
90
+
91
+
92
+ class Mul(Expr, AssocOp):
93
+ """
94
+ Expression representing multiplication operation for algebraic field.
95
+
96
+ .. deprecated:: 1.7
97
+
98
+ Using arguments that aren't subclasses of :class:`~.Expr` in core
99
+ operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
100
+ deprecated. See :ref:`non-expr-args-deprecated` for details.
101
+
102
+ Every argument of ``Mul()`` must be ``Expr``. Infix operator ``*``
103
+ on most scalar objects in SymPy calls this class.
104
+
105
+ Another use of ``Mul()`` is to represent the structure of abstract
106
+ multiplication so that its arguments can be substituted to return
107
+ different class. Refer to examples section for this.
108
+
109
+ ``Mul()`` evaluates the argument unless ``evaluate=False`` is passed.
110
+ The evaluation logic includes:
111
+
112
+ 1. Flattening
113
+ ``Mul(x, Mul(y, z))`` -> ``Mul(x, y, z)``
114
+
115
+ 2. Identity removing
116
+ ``Mul(x, 1, y)`` -> ``Mul(x, y)``
117
+
118
+ 3. Exponent collecting by ``.as_base_exp()``
119
+ ``Mul(x, x**2)`` -> ``Pow(x, 3)``
120
+
121
+ 4. Term sorting
122
+ ``Mul(y, x, 2)`` -> ``Mul(2, x, y)``
123
+
124
+ Since multiplication can be vector space operation, arguments may
125
+ have the different :obj:`sympy.core.kind.Kind()`. Kind of the
126
+ resulting object is automatically inferred.
127
+
128
+ Examples
129
+ ========
130
+
131
+ >>> from sympy import Mul
132
+ >>> from sympy.abc import x, y
133
+ >>> Mul(x, 1)
134
+ x
135
+ >>> Mul(x, x)
136
+ x**2
137
+
138
+ If ``evaluate=False`` is passed, result is not evaluated.
139
+
140
+ >>> Mul(1, 2, evaluate=False)
141
+ 1*2
142
+ >>> Mul(x, x, evaluate=False)
143
+ x*x
144
+
145
+ ``Mul()`` also represents the general structure of multiplication
146
+ operation.
147
+
148
+ >>> from sympy import MatrixSymbol
149
+ >>> A = MatrixSymbol('A', 2,2)
150
+ >>> expr = Mul(x,y).subs({y:A})
151
+ >>> expr
152
+ x*A
153
+ >>> type(expr)
154
+ <class 'sympy.matrices.expressions.matmul.MatMul'>
155
+
156
+ See Also
157
+ ========
158
+
159
+ MatMul
160
+
161
+ """
162
+ __slots__ = ()
163
+
164
+ args: tTuple[Expr]
165
+
166
+ is_Mul = True
167
+
168
+ _args_type = Expr
169
+ _kind_dispatcher = KindDispatcher("Mul_kind_dispatcher", commutative=True)
170
+
171
+ @property
172
+ def kind(self):
173
+ arg_kinds = (a.kind for a in self.args)
174
+ return self._kind_dispatcher(*arg_kinds)
175
+
176
+ def could_extract_minus_sign(self):
177
+ if self == (-self):
178
+ return False # e.g. zoo*x == -zoo*x
179
+ c = self.args[0]
180
+ return c.is_Number and c.is_extended_negative
181
+
182
+ def __neg__(self):
183
+ c, args = self.as_coeff_mul()
184
+ if args[0] is not S.ComplexInfinity:
185
+ c = -c
186
+ if c is not S.One:
187
+ if args[0].is_Number:
188
+ args = list(args)
189
+ if c is S.NegativeOne:
190
+ args[0] = -args[0]
191
+ else:
192
+ args[0] *= c
193
+ else:
194
+ args = (c,) + args
195
+ return self._from_args(args, self.is_commutative)
196
+
197
+ @classmethod
198
+ def flatten(cls, seq):
199
+ """Return commutative, noncommutative and order arguments by
200
+ combining related terms.
201
+
202
+ Notes
203
+ =====
204
+ * In an expression like ``a*b*c``, Python process this through SymPy
205
+ as ``Mul(Mul(a, b), c)``. This can have undesirable consequences.
206
+
207
+ - Sometimes terms are not combined as one would like:
208
+ {c.f. https://github.com/sympy/sympy/issues/4596}
209
+
210
+ >>> from sympy import Mul, sqrt
211
+ >>> from sympy.abc import x, y, z
212
+ >>> 2*(x + 1) # this is the 2-arg Mul behavior
213
+ 2*x + 2
214
+ >>> y*(x + 1)*2
215
+ 2*y*(x + 1)
216
+ >>> 2*(x + 1)*y # 2-arg result will be obtained first
217
+ y*(2*x + 2)
218
+ >>> Mul(2, x + 1, y) # all 3 args simultaneously processed
219
+ 2*y*(x + 1)
220
+ >>> 2*((x + 1)*y) # parentheses can control this behavior
221
+ 2*y*(x + 1)
222
+
223
+ Powers with compound bases may not find a single base to
224
+ combine with unless all arguments are processed at once.
225
+ Post-processing may be necessary in such cases.
226
+ {c.f. https://github.com/sympy/sympy/issues/5728}
227
+
228
+ >>> a = sqrt(x*sqrt(y))
229
+ >>> a**3
230
+ (x*sqrt(y))**(3/2)
231
+ >>> Mul(a,a,a)
232
+ (x*sqrt(y))**(3/2)
233
+ >>> a*a*a
234
+ x*sqrt(y)*sqrt(x*sqrt(y))
235
+ >>> _.subs(a.base, z).subs(z, a.base)
236
+ (x*sqrt(y))**(3/2)
237
+
238
+ - If more than two terms are being multiplied then all the
239
+ previous terms will be re-processed for each new argument.
240
+ So if each of ``a``, ``b`` and ``c`` were :class:`Mul`
241
+ expression, then ``a*b*c`` (or building up the product
242
+ with ``*=``) will process all the arguments of ``a`` and
243
+ ``b`` twice: once when ``a*b`` is computed and again when
244
+ ``c`` is multiplied.
245
+
246
+ Using ``Mul(a, b, c)`` will process all arguments once.
247
+
248
+ * The results of Mul are cached according to arguments, so flatten
249
+ will only be called once for ``Mul(a, b, c)``. If you can
250
+ structure a calculation so the arguments are most likely to be
251
+ repeats then this can save time in computing the answer. For
252
+ example, say you had a Mul, M, that you wished to divide by ``d[i]``
253
+ and multiply by ``n[i]`` and you suspect there are many repeats
254
+ in ``n``. It would be better to compute ``M*n[i]/d[i]`` rather
255
+ than ``M/d[i]*n[i]`` since every time n[i] is a repeat, the
256
+ product, ``M*n[i]`` will be returned without flattening -- the
257
+ cached value will be returned. If you divide by the ``d[i]``
258
+ first (and those are more unique than the ``n[i]``) then that will
259
+ create a new Mul, ``M/d[i]`` the args of which will be traversed
260
+ again when it is multiplied by ``n[i]``.
261
+
262
+ {c.f. https://github.com/sympy/sympy/issues/5706}
263
+
264
+ This consideration is moot if the cache is turned off.
265
+
266
+ NB
267
+ --
268
+ The validity of the above notes depends on the implementation
269
+ details of Mul and flatten which may change at any time. Therefore,
270
+ you should only consider them when your code is highly performance
271
+ sensitive.
272
+
273
+ Removal of 1 from the sequence is already handled by AssocOp.__new__.
274
+ """
275
+
276
+ from sympy.calculus.accumulationbounds import AccumBounds
277
+ from sympy.matrices.expressions import MatrixExpr
278
+ rv = None
279
+ if len(seq) == 2:
280
+ a, b = seq
281
+ if b.is_Rational:
282
+ a, b = b, a
283
+ seq = [a, b]
284
+ assert a is not S.One
285
+ if not a.is_zero and a.is_Rational:
286
+ r, b = b.as_coeff_Mul()
287
+ if b.is_Add:
288
+ if r is not S.One: # 2-arg hack
289
+ # leave the Mul as a Mul?
290
+ ar = a*r
291
+ if ar is S.One:
292
+ arb = b
293
+ else:
294
+ arb = cls(a*r, b, evaluate=False)
295
+ rv = [arb], [], None
296
+ elif global_parameters.distribute and b.is_commutative:
297
+ newb = Add(*[_keep_coeff(a, bi) for bi in b.args])
298
+ rv = [newb], [], None
299
+ if rv:
300
+ return rv
301
+
302
+ # apply associativity, separate commutative part of seq
303
+ c_part = [] # out: commutative factors
304
+ nc_part = [] # out: non-commutative factors
305
+
306
+ nc_seq = []
307
+
308
+ coeff = S.One # standalone term
309
+ # e.g. 3 * ...
310
+
311
+ c_powers = [] # (base,exp) n
312
+ # e.g. (x,n) for x
313
+
314
+ num_exp = [] # (num-base, exp) y
315
+ # e.g. (3, y) for ... * 3 * ...
316
+
317
+ neg1e = S.Zero # exponent on -1 extracted from Number-based Pow and I
318
+
319
+ pnum_rat = {} # (num-base, Rat-exp) 1/2
320
+ # e.g. (3, 1/2) for ... * 3 * ...
321
+
322
+ order_symbols = None
323
+
324
+ # --- PART 1 ---
325
+ #
326
+ # "collect powers and coeff":
327
+ #
328
+ # o coeff
329
+ # o c_powers
330
+ # o num_exp
331
+ # o neg1e
332
+ # o pnum_rat
333
+ #
334
+ # NOTE: this is optimized for all-objects-are-commutative case
335
+ for o in seq:
336
+ # O(x)
337
+ if o.is_Order:
338
+ o, order_symbols = o.as_expr_variables(order_symbols)
339
+
340
+ # Mul([...])
341
+ if o.is_Mul:
342
+ if o.is_commutative:
343
+ seq.extend(o.args) # XXX zerocopy?
344
+
345
+ else:
346
+ # NCMul can have commutative parts as well
347
+ for q in o.args:
348
+ if q.is_commutative:
349
+ seq.append(q)
350
+ else:
351
+ nc_seq.append(q)
352
+
353
+ # append non-commutative marker, so we don't forget to
354
+ # process scheduled non-commutative objects
355
+ seq.append(NC_Marker)
356
+
357
+ continue
358
+
359
+ # 3
360
+ elif o.is_Number:
361
+ if o is S.NaN or coeff is S.ComplexInfinity and o.is_zero:
362
+ # we know for sure the result will be nan
363
+ return [S.NaN], [], None
364
+ elif coeff.is_Number or isinstance(coeff, AccumBounds): # it could be zoo
365
+ coeff *= o
366
+ if coeff is S.NaN:
367
+ # we know for sure the result will be nan
368
+ return [S.NaN], [], None
369
+ continue
370
+
371
+ elif isinstance(o, AccumBounds):
372
+ coeff = o.__mul__(coeff)
373
+ continue
374
+
375
+ elif o is S.ComplexInfinity:
376
+ if not coeff:
377
+ # 0 * zoo = NaN
378
+ return [S.NaN], [], None
379
+ coeff = S.ComplexInfinity
380
+ continue
381
+
382
+ elif o is S.ImaginaryUnit:
383
+ neg1e += S.Half
384
+ continue
385
+
386
+ elif o.is_commutative:
387
+ # e
388
+ # o = b
389
+ b, e = o.as_base_exp()
390
+
391
+ # y
392
+ # 3
393
+ if o.is_Pow:
394
+ if b.is_Number:
395
+
396
+ # get all the factors with numeric base so they can be
397
+ # combined below, but don't combine negatives unless
398
+ # the exponent is an integer
399
+ if e.is_Rational:
400
+ if e.is_Integer:
401
+ coeff *= Pow(b, e) # it is an unevaluated power
402
+ continue
403
+ elif e.is_negative: # also a sign of an unevaluated power
404
+ seq.append(Pow(b, e))
405
+ continue
406
+ elif b.is_negative:
407
+ neg1e += e
408
+ b = -b
409
+ if b is not S.One:
410
+ pnum_rat.setdefault(b, []).append(e)
411
+ continue
412
+ elif b.is_positive or e.is_integer:
413
+ num_exp.append((b, e))
414
+ continue
415
+
416
+ c_powers.append((b, e))
417
+
418
+ # NON-COMMUTATIVE
419
+ # TODO: Make non-commutative exponents not combine automatically
420
+ else:
421
+ if o is not NC_Marker:
422
+ nc_seq.append(o)
423
+
424
+ # process nc_seq (if any)
425
+ while nc_seq:
426
+ o = nc_seq.pop(0)
427
+ if not nc_part:
428
+ nc_part.append(o)
429
+ continue
430
+
431
+ # b c b+c
432
+ # try to combine last terms: a * a -> a
433
+ o1 = nc_part.pop()
434
+ b1, e1 = o1.as_base_exp()
435
+ b2, e2 = o.as_base_exp()
436
+ new_exp = e1 + e2
437
+ # Only allow powers to combine if the new exponent is
438
+ # not an Add. This allow things like a**2*b**3 == a**5
439
+ # if a.is_commutative == False, but prohibits
440
+ # a**x*a**y and x**a*x**b from combining (x,y commute).
441
+ if b1 == b2 and (not new_exp.is_Add):
442
+ o12 = b1 ** new_exp
443
+
444
+ # now o12 could be a commutative object
445
+ if o12.is_commutative:
446
+ seq.append(o12)
447
+ continue
448
+ else:
449
+ nc_seq.insert(0, o12)
450
+
451
+ else:
452
+ nc_part.extend([o1, o])
453
+
454
+ # We do want a combined exponent if it would not be an Add, such as
455
+ # y 2y 3y
456
+ # x * x -> x
457
+ # We determine if two exponents have the same term by using
458
+ # as_coeff_Mul.
459
+ #
460
+ # Unfortunately, this isn't smart enough to consider combining into
461
+ # exponents that might already be adds, so things like:
462
+ # z - y y
463
+ # x * x will be left alone. This is because checking every possible
464
+ # combination can slow things down.
465
+
466
+ # gather exponents of common bases...
467
+ def _gather(c_powers):
468
+ common_b = {} # b:e
469
+ for b, e in c_powers:
470
+ co = e.as_coeff_Mul()
471
+ common_b.setdefault(b, {}).setdefault(
472
+ co[1], []).append(co[0])
473
+ for b, d in common_b.items():
474
+ for di, li in d.items():
475
+ d[di] = Add(*li)
476
+ new_c_powers = []
477
+ for b, e in common_b.items():
478
+ new_c_powers.extend([(b, c*t) for t, c in e.items()])
479
+ return new_c_powers
480
+
481
+ # in c_powers
482
+ c_powers = _gather(c_powers)
483
+
484
+ # and in num_exp
485
+ num_exp = _gather(num_exp)
486
+
487
+ # --- PART 2 ---
488
+ #
489
+ # o process collected powers (x**0 -> 1; x**1 -> x; otherwise Pow)
490
+ # o combine collected powers (2**x * 3**x -> 6**x)
491
+ # with numeric base
492
+
493
+ # ................................
494
+ # now we have:
495
+ # - coeff:
496
+ # - c_powers: (b, e)
497
+ # - num_exp: (2, e)
498
+ # - pnum_rat: {(1/3, [1/3, 2/3, 1/4])}
499
+
500
+ # 0 1
501
+ # x -> 1 x -> x
502
+
503
+ # this should only need to run twice; if it fails because
504
+ # it needs to be run more times, perhaps this should be
505
+ # changed to a "while True" loop -- the only reason it
506
+ # isn't such now is to allow a less-than-perfect result to
507
+ # be obtained rather than raising an error or entering an
508
+ # infinite loop
509
+ for i in range(2):
510
+ new_c_powers = []
511
+ changed = False
512
+ for b, e in c_powers:
513
+ if e.is_zero:
514
+ # canceling out infinities yields NaN
515
+ if (b.is_Add or b.is_Mul) and any(infty in b.args
516
+ for infty in (S.ComplexInfinity, S.Infinity,
517
+ S.NegativeInfinity)):
518
+ return [S.NaN], [], None
519
+ continue
520
+ if e is S.One:
521
+ if b.is_Number:
522
+ coeff *= b
523
+ continue
524
+ p = b
525
+ if e is not S.One:
526
+ p = Pow(b, e)
527
+ # check to make sure that the base doesn't change
528
+ # after exponentiation; to allow for unevaluated
529
+ # Pow, we only do so if b is not already a Pow
530
+ if p.is_Pow and not b.is_Pow:
531
+ bi = b
532
+ b, e = p.as_base_exp()
533
+ if b != bi:
534
+ changed = True
535
+ c_part.append(p)
536
+ new_c_powers.append((b, e))
537
+ # there might have been a change, but unless the base
538
+ # matches some other base, there is nothing to do
539
+ if changed and len({
540
+ b for b, e in new_c_powers}) != len(new_c_powers):
541
+ # start over again
542
+ c_part = []
543
+ c_powers = _gather(new_c_powers)
544
+ else:
545
+ break
546
+
547
+ # x x x
548
+ # 2 * 3 -> 6
549
+ inv_exp_dict = {} # exp:Mul(num-bases) x x
550
+ # e.g. x:6 for ... * 2 * 3 * ...
551
+ for b, e in num_exp:
552
+ inv_exp_dict.setdefault(e, []).append(b)
553
+ for e, b in inv_exp_dict.items():
554
+ inv_exp_dict[e] = cls(*b)
555
+ c_part.extend([Pow(b, e) for e, b in inv_exp_dict.items() if e])
556
+
557
+ # b, e -> e' = sum(e), b
558
+ # {(1/5, [1/3]), (1/2, [1/12, 1/4]} -> {(1/3, [1/5, 1/2])}
559
+ comb_e = {}
560
+ for b, e in pnum_rat.items():
561
+ comb_e.setdefault(Add(*e), []).append(b)
562
+ del pnum_rat
563
+ # process them, reducing exponents to values less than 1
564
+ # and updating coeff if necessary else adding them to
565
+ # num_rat for further processing
566
+ num_rat = []
567
+ for e, b in comb_e.items():
568
+ b = cls(*b)
569
+ if e.q == 1:
570
+ coeff *= Pow(b, e)
571
+ continue
572
+ if e.p > e.q:
573
+ e_i, ep = divmod(e.p, e.q)
574
+ coeff *= Pow(b, e_i)
575
+ e = Rational(ep, e.q)
576
+ num_rat.append((b, e))
577
+ del comb_e
578
+
579
+ # extract gcd of bases in num_rat
580
+ # 2**(1/3)*6**(1/4) -> 2**(1/3+1/4)*3**(1/4)
581
+ pnew = defaultdict(list)
582
+ i = 0 # steps through num_rat which may grow
583
+ while i < len(num_rat):
584
+ bi, ei = num_rat[i]
585
+ grow = []
586
+ for j in range(i + 1, len(num_rat)):
587
+ bj, ej = num_rat[j]
588
+ g = bi.gcd(bj)
589
+ if g is not S.One:
590
+ # 4**r1*6**r2 -> 2**(r1+r2) * 2**r1 * 3**r2
591
+ # this might have a gcd with something else
592
+ e = ei + ej
593
+ if e.q == 1:
594
+ coeff *= Pow(g, e)
595
+ else:
596
+ if e.p > e.q:
597
+ e_i, ep = divmod(e.p, e.q) # change e in place
598
+ coeff *= Pow(g, e_i)
599
+ e = Rational(ep, e.q)
600
+ grow.append((g, e))
601
+ # update the jth item
602
+ num_rat[j] = (bj/g, ej)
603
+ # update bi that we are checking with
604
+ bi = bi/g
605
+ if bi is S.One:
606
+ break
607
+ if bi is not S.One:
608
+ obj = Pow(bi, ei)
609
+ if obj.is_Number:
610
+ coeff *= obj
611
+ else:
612
+ # changes like sqrt(12) -> 2*sqrt(3)
613
+ for obj in Mul.make_args(obj):
614
+ if obj.is_Number:
615
+ coeff *= obj
616
+ else:
617
+ assert obj.is_Pow
618
+ bi, ei = obj.args
619
+ pnew[ei].append(bi)
620
+
621
+ num_rat.extend(grow)
622
+ i += 1
623
+
624
+ # combine bases of the new powers
625
+ for e, b in pnew.items():
626
+ pnew[e] = cls(*b)
627
+
628
+ # handle -1 and I
629
+ if neg1e:
630
+ # treat I as (-1)**(1/2) and compute -1's total exponent
631
+ p, q = neg1e.as_numer_denom()
632
+ # if the integer part is odd, extract -1
633
+ n, p = divmod(p, q)
634
+ if n % 2:
635
+ coeff = -coeff
636
+ # if it's a multiple of 1/2 extract I
637
+ if q == 2:
638
+ c_part.append(S.ImaginaryUnit)
639
+ elif p:
640
+ # see if there is any positive base this power of
641
+ # -1 can join
642
+ neg1e = Rational(p, q)
643
+ for e, b in pnew.items():
644
+ if e == neg1e and b.is_positive:
645
+ pnew[e] = -b
646
+ break
647
+ else:
648
+ # keep it separate; we've already evaluated it as
649
+ # much as possible so evaluate=False
650
+ c_part.append(Pow(S.NegativeOne, neg1e, evaluate=False))
651
+
652
+ # add all the pnew powers
653
+ c_part.extend([Pow(b, e) for e, b in pnew.items()])
654
+
655
+ # oo, -oo
656
+ if coeff in (S.Infinity, S.NegativeInfinity):
657
+ def _handle_for_oo(c_part, coeff_sign):
658
+ new_c_part = []
659
+ for t in c_part:
660
+ if t.is_extended_positive:
661
+ continue
662
+ if t.is_extended_negative:
663
+ coeff_sign *= -1
664
+ continue
665
+ new_c_part.append(t)
666
+ return new_c_part, coeff_sign
667
+ c_part, coeff_sign = _handle_for_oo(c_part, 1)
668
+ nc_part, coeff_sign = _handle_for_oo(nc_part, coeff_sign)
669
+ coeff *= coeff_sign
670
+
671
+ # zoo
672
+ if coeff is S.ComplexInfinity:
673
+ # zoo might be
674
+ # infinite_real + bounded_im
675
+ # bounded_real + infinite_im
676
+ # infinite_real + infinite_im
677
+ # and non-zero real or imaginary will not change that status.
678
+ c_part = [c for c in c_part if not (fuzzy_not(c.is_zero) and
679
+ c.is_extended_real is not None)]
680
+ nc_part = [c for c in nc_part if not (fuzzy_not(c.is_zero) and
681
+ c.is_extended_real is not None)]
682
+
683
+ # 0
684
+ elif coeff.is_zero:
685
+ # we know for sure the result will be 0 except the multiplicand
686
+ # is infinity or a matrix
687
+ if any(isinstance(c, MatrixExpr) for c in nc_part):
688
+ return [coeff], nc_part, order_symbols
689
+ if any(c.is_finite == False for c in c_part):
690
+ return [S.NaN], [], order_symbols
691
+ return [coeff], [], order_symbols
692
+
693
+ # check for straggling Numbers that were produced
694
+ _new = []
695
+ for i in c_part:
696
+ if i.is_Number:
697
+ coeff *= i
698
+ else:
699
+ _new.append(i)
700
+ c_part = _new
701
+
702
+ # order commutative part canonically
703
+ _mulsort(c_part)
704
+
705
+ # current code expects coeff to be always in slot-0
706
+ if coeff is not S.One:
707
+ c_part.insert(0, coeff)
708
+
709
+ # we are done
710
+ if (global_parameters.distribute and not nc_part and len(c_part) == 2 and
711
+ c_part[0].is_Number and c_part[0].is_finite and c_part[1].is_Add):
712
+ # 2*(1+a) -> 2 + 2 * a
713
+ coeff = c_part[0]
714
+ c_part = [Add(*[coeff*f for f in c_part[1].args])]
715
+
716
+ return c_part, nc_part, order_symbols
717
+
718
+ def _eval_power(self, e):
719
+
720
+ # don't break up NC terms: (A*B)**3 != A**3*B**3, it is A*B*A*B*A*B
721
+ cargs, nc = self.args_cnc(split_1=False)
722
+
723
+ if e.is_Integer:
724
+ return Mul(*[Pow(b, e, evaluate=False) for b in cargs]) * \
725
+ Pow(Mul._from_args(nc), e, evaluate=False)
726
+ if e.is_Rational and e.q == 2:
727
+ if self.is_imaginary:
728
+ a = self.as_real_imag()[1]
729
+ if a.is_Rational:
730
+ from .power import integer_nthroot
731
+ n, d = abs(a/2).as_numer_denom()
732
+ n, t = integer_nthroot(n, 2)
733
+ if t:
734
+ d, t = integer_nthroot(d, 2)
735
+ if t:
736
+ from sympy.functions.elementary.complexes import sign
737
+ r = sympify(n)/d
738
+ return _unevaluated_Mul(r**e.p, (1 + sign(a)*S.ImaginaryUnit)**e.p)
739
+
740
+ p = Pow(self, e, evaluate=False)
741
+
742
+ if e.is_Rational or e.is_Float:
743
+ return p._eval_expand_power_base()
744
+
745
+ return p
746
+
747
+ @classmethod
748
+ def class_key(cls):
749
+ return 3, 0, cls.__name__
750
+
751
+ def _eval_evalf(self, prec):
752
+ c, m = self.as_coeff_Mul()
753
+ if c is S.NegativeOne:
754
+ if m.is_Mul:
755
+ rv = -AssocOp._eval_evalf(m, prec)
756
+ else:
757
+ mnew = m._eval_evalf(prec)
758
+ if mnew is not None:
759
+ m = mnew
760
+ rv = -m
761
+ else:
762
+ rv = AssocOp._eval_evalf(self, prec)
763
+ if rv.is_number:
764
+ return rv.expand()
765
+ return rv
766
+
767
+ @property
768
+ def _mpc_(self):
769
+ """
770
+ Convert self to an mpmath mpc if possible
771
+ """
772
+ from .numbers import Float
773
+ im_part, imag_unit = self.as_coeff_Mul()
774
+ if imag_unit is not S.ImaginaryUnit:
775
+ # ValueError may seem more reasonable but since it's a @property,
776
+ # we need to use AttributeError to keep from confusing things like
777
+ # hasattr.
778
+ raise AttributeError("Cannot convert Mul to mpc. Must be of the form Number*I")
779
+
780
+ return (Float(0)._mpf_, Float(im_part)._mpf_)
781
+
782
+ @cacheit
783
+ def as_two_terms(self):
784
+ """Return head and tail of self.
785
+
786
+ This is the most efficient way to get the head and tail of an
787
+ expression.
788
+
789
+ - if you want only the head, use self.args[0];
790
+ - if you want to process the arguments of the tail then use
791
+ self.as_coef_mul() which gives the head and a tuple containing
792
+ the arguments of the tail when treated as a Mul.
793
+ - if you want the coefficient when self is treated as an Add
794
+ then use self.as_coeff_add()[0]
795
+
796
+ Examples
797
+ ========
798
+
799
+ >>> from sympy.abc import x, y
800
+ >>> (3*x*y).as_two_terms()
801
+ (3, x*y)
802
+ """
803
+ args = self.args
804
+
805
+ if len(args) == 1:
806
+ return S.One, self
807
+ elif len(args) == 2:
808
+ return args
809
+
810
+ else:
811
+ return args[0], self._new_rawargs(*args[1:])
812
+
813
+ @cacheit
814
+ def as_coeff_mul(self, *deps, rational=True, **kwargs):
815
+ if deps:
816
+ l1, l2 = sift(self.args, lambda x: x.has(*deps), binary=True)
817
+ return self._new_rawargs(*l2), tuple(l1)
818
+ args = self.args
819
+ if args[0].is_Number:
820
+ if not rational or args[0].is_Rational:
821
+ return args[0], args[1:]
822
+ elif args[0].is_extended_negative:
823
+ return S.NegativeOne, (-args[0],) + args[1:]
824
+ return S.One, args
825
+
826
+ def as_coeff_Mul(self, rational=False):
827
+ """
828
+ Efficiently extract the coefficient of a product.
829
+ """
830
+ coeff, args = self.args[0], self.args[1:]
831
+
832
+ if coeff.is_Number:
833
+ if not rational or coeff.is_Rational:
834
+ if len(args) == 1:
835
+ return coeff, args[0]
836
+ else:
837
+ return coeff, self._new_rawargs(*args)
838
+ elif coeff.is_extended_negative:
839
+ return S.NegativeOne, self._new_rawargs(*((-coeff,) + args))
840
+ return S.One, self
841
+
842
+ def as_real_imag(self, deep=True, **hints):
843
+ from sympy.functions.elementary.complexes import Abs, im, re
844
+ other = []
845
+ coeffr = []
846
+ coeffi = []
847
+ addterms = S.One
848
+ for a in self.args:
849
+ r, i = a.as_real_imag()
850
+ if i.is_zero:
851
+ coeffr.append(r)
852
+ elif r.is_zero:
853
+ coeffi.append(i*S.ImaginaryUnit)
854
+ elif a.is_commutative:
855
+ aconj = a.conjugate() if other else None
856
+ # search for complex conjugate pairs:
857
+ for i, x in enumerate(other):
858
+ if x == aconj:
859
+ coeffr.append(Abs(x)**2)
860
+ del other[i]
861
+ break
862
+ else:
863
+ if a.is_Add:
864
+ addterms *= a
865
+ else:
866
+ other.append(a)
867
+ else:
868
+ other.append(a)
869
+ m = self.func(*other)
870
+ if hints.get('ignore') == m:
871
+ return
872
+ if len(coeffi) % 2:
873
+ imco = im(coeffi.pop(0))
874
+ # all other pairs make a real factor; they will be
875
+ # put into reco below
876
+ else:
877
+ imco = S.Zero
878
+ reco = self.func(*(coeffr + coeffi))
879
+ r, i = (reco*re(m), reco*im(m))
880
+ if addterms == 1:
881
+ if m == 1:
882
+ if imco.is_zero:
883
+ return (reco, S.Zero)
884
+ else:
885
+ return (S.Zero, reco*imco)
886
+ if imco is S.Zero:
887
+ return (r, i)
888
+ return (-imco*i, imco*r)
889
+ from .function import expand_mul
890
+ addre, addim = expand_mul(addterms, deep=False).as_real_imag()
891
+ if imco is S.Zero:
892
+ return (r*addre - i*addim, i*addre + r*addim)
893
+ else:
894
+ r, i = -imco*i, imco*r
895
+ return (r*addre - i*addim, r*addim + i*addre)
896
+
897
+ @staticmethod
898
+ def _expandsums(sums):
899
+ """
900
+ Helper function for _eval_expand_mul.
901
+
902
+ sums must be a list of instances of Basic.
903
+ """
904
+
905
+ L = len(sums)
906
+ if L == 1:
907
+ return sums[0].args
908
+ terms = []
909
+ left = Mul._expandsums(sums[:L//2])
910
+ right = Mul._expandsums(sums[L//2:])
911
+
912
+ terms = [Mul(a, b) for a in left for b in right]
913
+ added = Add(*terms)
914
+ return Add.make_args(added) # it may have collapsed down to one term
915
+
916
+ def _eval_expand_mul(self, **hints):
917
+ from sympy.simplify.radsimp import fraction
918
+
919
+ # Handle things like 1/(x*(x + 1)), which are automatically converted
920
+ # to 1/x*1/(x + 1)
921
+ expr = self
922
+ n, d = fraction(expr)
923
+ if d.is_Mul:
924
+ n, d = [i._eval_expand_mul(**hints) if i.is_Mul else i
925
+ for i in (n, d)]
926
+ expr = n/d
927
+ if not expr.is_Mul:
928
+ return expr
929
+
930
+ plain, sums, rewrite = [], [], False
931
+ for factor in expr.args:
932
+ if factor.is_Add:
933
+ sums.append(factor)
934
+ rewrite = True
935
+ else:
936
+ if factor.is_commutative:
937
+ plain.append(factor)
938
+ else:
939
+ sums.append(Basic(factor)) # Wrapper
940
+
941
+ if not rewrite:
942
+ return expr
943
+ else:
944
+ plain = self.func(*plain)
945
+ if sums:
946
+ deep = hints.get("deep", False)
947
+ terms = self.func._expandsums(sums)
948
+ args = []
949
+ for term in terms:
950
+ t = self.func(plain, term)
951
+ if t.is_Mul and any(a.is_Add for a in t.args) and deep:
952
+ t = t._eval_expand_mul()
953
+ args.append(t)
954
+ return Add(*args)
955
+ else:
956
+ return plain
957
+
958
+ @cacheit
959
+ def _eval_derivative(self, s):
960
+ args = list(self.args)
961
+ terms = []
962
+ for i in range(len(args)):
963
+ d = args[i].diff(s)
964
+ if d:
965
+ # Note: reduce is used in step of Mul as Mul is unable to
966
+ # handle subtypes and operation priority:
967
+ terms.append(reduce(lambda x, y: x*y, (args[:i] + [d] + args[i + 1:]), S.One))
968
+ return Add.fromiter(terms)
969
+
970
+ @cacheit
971
+ def _eval_derivative_n_times(self, s, n):
972
+ from .function import AppliedUndef
973
+ from .symbol import Symbol, symbols, Dummy
974
+ if not isinstance(s, (AppliedUndef, Symbol)):
975
+ # other types of s may not be well behaved, e.g.
976
+ # (cos(x)*sin(y)).diff([[x, y, z]])
977
+ return super()._eval_derivative_n_times(s, n)
978
+ from .numbers import Integer
979
+ args = self.args
980
+ m = len(args)
981
+ if isinstance(n, (int, Integer)):
982
+ # https://en.wikipedia.org/wiki/General_Leibniz_rule#More_than_two_factors
983
+ terms = []
984
+ from sympy.ntheory.multinomial import multinomial_coefficients_iterator
985
+ for kvals, c in multinomial_coefficients_iterator(m, n):
986
+ p = Mul(*[arg.diff((s, k)) for k, arg in zip(kvals, args)])
987
+ terms.append(c * p)
988
+ return Add(*terms)
989
+ from sympy.concrete.summations import Sum
990
+ from sympy.functions.combinatorial.factorials import factorial
991
+ from sympy.functions.elementary.miscellaneous import Max
992
+ kvals = symbols("k1:%i" % m, cls=Dummy)
993
+ klast = n - sum(kvals)
994
+ nfact = factorial(n)
995
+ e, l = (# better to use the multinomial?
996
+ nfact/prod(map(factorial, kvals))/factorial(klast)*\
997
+ Mul(*[args[t].diff((s, kvals[t])) for t in range(m-1)])*\
998
+ args[-1].diff((s, Max(0, klast))),
999
+ [(k, 0, n) for k in kvals])
1000
+ return Sum(e, *l)
1001
+
1002
+ def _eval_difference_delta(self, n, step):
1003
+ from sympy.series.limitseq import difference_delta as dd
1004
+ arg0 = self.args[0]
1005
+ rest = Mul(*self.args[1:])
1006
+ return (arg0.subs(n, n + step) * dd(rest, n, step) + dd(arg0, n, step) *
1007
+ rest)
1008
+
1009
+ def _matches_simple(self, expr, repl_dict):
1010
+ # handle (w*3).matches('x*5') -> {w: x*5/3}
1011
+ coeff, terms = self.as_coeff_Mul()
1012
+ terms = Mul.make_args(terms)
1013
+ if len(terms) == 1:
1014
+ newexpr = self.__class__._combine_inverse(expr, coeff)
1015
+ return terms[0].matches(newexpr, repl_dict)
1016
+ return
1017
+
1018
+ def matches(self, expr, repl_dict=None, old=False):
1019
+ expr = sympify(expr)
1020
+ if self.is_commutative and expr.is_commutative:
1021
+ return self._matches_commutative(expr, repl_dict, old)
1022
+ elif self.is_commutative is not expr.is_commutative:
1023
+ return None
1024
+
1025
+ # Proceed only if both both expressions are non-commutative
1026
+ c1, nc1 = self.args_cnc()
1027
+ c2, nc2 = expr.args_cnc()
1028
+ c1, c2 = [c or [1] for c in [c1, c2]]
1029
+
1030
+ # TODO: Should these be self.func?
1031
+ comm_mul_self = Mul(*c1)
1032
+ comm_mul_expr = Mul(*c2)
1033
+
1034
+ repl_dict = comm_mul_self.matches(comm_mul_expr, repl_dict, old)
1035
+
1036
+ # If the commutative arguments didn't match and aren't equal, then
1037
+ # then the expression as a whole doesn't match
1038
+ if not repl_dict and c1 != c2:
1039
+ return None
1040
+
1041
+ # Now match the non-commutative arguments, expanding powers to
1042
+ # multiplications
1043
+ nc1 = Mul._matches_expand_pows(nc1)
1044
+ nc2 = Mul._matches_expand_pows(nc2)
1045
+
1046
+ repl_dict = Mul._matches_noncomm(nc1, nc2, repl_dict)
1047
+
1048
+ return repl_dict or None
1049
+
1050
+ @staticmethod
1051
+ def _matches_expand_pows(arg_list):
1052
+ new_args = []
1053
+ for arg in arg_list:
1054
+ if arg.is_Pow and arg.exp > 0:
1055
+ new_args.extend([arg.base] * arg.exp)
1056
+ else:
1057
+ new_args.append(arg)
1058
+ return new_args
1059
+
1060
+ @staticmethod
1061
+ def _matches_noncomm(nodes, targets, repl_dict=None):
1062
+ """Non-commutative multiplication matcher.
1063
+
1064
+ `nodes` is a list of symbols within the matcher multiplication
1065
+ expression, while `targets` is a list of arguments in the
1066
+ multiplication expression being matched against.
1067
+ """
1068
+ if repl_dict is None:
1069
+ repl_dict = {}
1070
+ else:
1071
+ repl_dict = repl_dict.copy()
1072
+
1073
+ # List of possible future states to be considered
1074
+ agenda = []
1075
+ # The current matching state, storing index in nodes and targets
1076
+ state = (0, 0)
1077
+ node_ind, target_ind = state
1078
+ # Mapping between wildcard indices and the index ranges they match
1079
+ wildcard_dict = {}
1080
+
1081
+ while target_ind < len(targets) and node_ind < len(nodes):
1082
+ node = nodes[node_ind]
1083
+
1084
+ if node.is_Wild:
1085
+ Mul._matches_add_wildcard(wildcard_dict, state)
1086
+
1087
+ states_matches = Mul._matches_new_states(wildcard_dict, state,
1088
+ nodes, targets)
1089
+ if states_matches:
1090
+ new_states, new_matches = states_matches
1091
+ agenda.extend(new_states)
1092
+ if new_matches:
1093
+ for match in new_matches:
1094
+ repl_dict[match] = new_matches[match]
1095
+ if not agenda:
1096
+ return None
1097
+ else:
1098
+ state = agenda.pop()
1099
+ node_ind, target_ind = state
1100
+
1101
+ return repl_dict
1102
+
1103
+ @staticmethod
1104
+ def _matches_add_wildcard(dictionary, state):
1105
+ node_ind, target_ind = state
1106
+ if node_ind in dictionary:
1107
+ begin, end = dictionary[node_ind]
1108
+ dictionary[node_ind] = (begin, target_ind)
1109
+ else:
1110
+ dictionary[node_ind] = (target_ind, target_ind)
1111
+
1112
+ @staticmethod
1113
+ def _matches_new_states(dictionary, state, nodes, targets):
1114
+ node_ind, target_ind = state
1115
+ node = nodes[node_ind]
1116
+ target = targets[target_ind]
1117
+
1118
+ # Don't advance at all if we've exhausted the targets but not the nodes
1119
+ if target_ind >= len(targets) - 1 and node_ind < len(nodes) - 1:
1120
+ return None
1121
+
1122
+ if node.is_Wild:
1123
+ match_attempt = Mul._matches_match_wilds(dictionary, node_ind,
1124
+ nodes, targets)
1125
+ if match_attempt:
1126
+ # If the same node has been matched before, don't return
1127
+ # anything if the current match is diverging from the previous
1128
+ # match
1129
+ other_node_inds = Mul._matches_get_other_nodes(dictionary,
1130
+ nodes, node_ind)
1131
+ for ind in other_node_inds:
1132
+ other_begin, other_end = dictionary[ind]
1133
+ curr_begin, curr_end = dictionary[node_ind]
1134
+
1135
+ other_targets = targets[other_begin:other_end + 1]
1136
+ current_targets = targets[curr_begin:curr_end + 1]
1137
+
1138
+ for curr, other in zip(current_targets, other_targets):
1139
+ if curr != other:
1140
+ return None
1141
+
1142
+ # A wildcard node can match more than one target, so only the
1143
+ # target index is advanced
1144
+ new_state = [(node_ind, target_ind + 1)]
1145
+ # Only move on to the next node if there is one
1146
+ if node_ind < len(nodes) - 1:
1147
+ new_state.append((node_ind + 1, target_ind + 1))
1148
+ return new_state, match_attempt
1149
+ else:
1150
+ # If we're not at a wildcard, then make sure we haven't exhausted
1151
+ # nodes but not targets, since in this case one node can only match
1152
+ # one target
1153
+ if node_ind >= len(nodes) - 1 and target_ind < len(targets) - 1:
1154
+ return None
1155
+
1156
+ match_attempt = node.matches(target)
1157
+
1158
+ if match_attempt:
1159
+ return [(node_ind + 1, target_ind + 1)], match_attempt
1160
+ elif node == target:
1161
+ return [(node_ind + 1, target_ind + 1)], None
1162
+ else:
1163
+ return None
1164
+
1165
+ @staticmethod
1166
+ def _matches_match_wilds(dictionary, wildcard_ind, nodes, targets):
1167
+ """Determine matches of a wildcard with sub-expression in `target`."""
1168
+ wildcard = nodes[wildcard_ind]
1169
+ begin, end = dictionary[wildcard_ind]
1170
+ terms = targets[begin:end + 1]
1171
+ # TODO: Should this be self.func?
1172
+ mult = Mul(*terms) if len(terms) > 1 else terms[0]
1173
+ return wildcard.matches(mult)
1174
+
1175
+ @staticmethod
1176
+ def _matches_get_other_nodes(dictionary, nodes, node_ind):
1177
+ """Find other wildcards that may have already been matched."""
1178
+ ind_node = nodes[node_ind]
1179
+ return [ind for ind in dictionary if nodes[ind] == ind_node]
1180
+
1181
+ @staticmethod
1182
+ def _combine_inverse(lhs, rhs):
1183
+ """
1184
+ Returns lhs/rhs, but treats arguments like symbols, so things
1185
+ like oo/oo return 1 (instead of a nan) and ``I`` behaves like
1186
+ a symbol instead of sqrt(-1).
1187
+ """
1188
+ from sympy.simplify.simplify import signsimp
1189
+ from .symbol import Dummy
1190
+ if lhs == rhs:
1191
+ return S.One
1192
+
1193
+ def check(l, r):
1194
+ if l.is_Float and r.is_comparable:
1195
+ # if both objects are added to 0 they will share the same "normalization"
1196
+ # and are more likely to compare the same. Since Add(foo, 0) will not allow
1197
+ # the 0 to pass, we use __add__ directly.
1198
+ return l.__add__(0) == r.evalf().__add__(0)
1199
+ return False
1200
+ if check(lhs, rhs) or check(rhs, lhs):
1201
+ return S.One
1202
+ if any(i.is_Pow or i.is_Mul for i in (lhs, rhs)):
1203
+ # gruntz and limit wants a literal I to not combine
1204
+ # with a power of -1
1205
+ d = Dummy('I')
1206
+ _i = {S.ImaginaryUnit: d}
1207
+ i_ = {d: S.ImaginaryUnit}
1208
+ a = lhs.xreplace(_i).as_powers_dict()
1209
+ b = rhs.xreplace(_i).as_powers_dict()
1210
+ blen = len(b)
1211
+ for bi in tuple(b.keys()):
1212
+ if bi in a:
1213
+ a[bi] -= b.pop(bi)
1214
+ if not a[bi]:
1215
+ a.pop(bi)
1216
+ if len(b) != blen:
1217
+ lhs = Mul(*[k**v for k, v in a.items()]).xreplace(i_)
1218
+ rhs = Mul(*[k**v for k, v in b.items()]).xreplace(i_)
1219
+ rv = lhs/rhs
1220
+ srv = signsimp(rv)
1221
+ return srv if srv.is_Number else rv
1222
+
1223
+ def as_powers_dict(self):
1224
+ d = defaultdict(int)
1225
+ for term in self.args:
1226
+ for b, e in term.as_powers_dict().items():
1227
+ d[b] += e
1228
+ return d
1229
+
1230
+ def as_numer_denom(self):
1231
+ # don't use _from_args to rebuild the numerators and denominators
1232
+ # as the order is not guaranteed to be the same once they have
1233
+ # been separated from each other
1234
+ numers, denoms = list(zip(*[f.as_numer_denom() for f in self.args]))
1235
+ return self.func(*numers), self.func(*denoms)
1236
+
1237
+ def as_base_exp(self):
1238
+ e1 = None
1239
+ bases = []
1240
+ nc = 0
1241
+ for m in self.args:
1242
+ b, e = m.as_base_exp()
1243
+ if not b.is_commutative:
1244
+ nc += 1
1245
+ if e1 is None:
1246
+ e1 = e
1247
+ elif e != e1 or nc > 1:
1248
+ return self, S.One
1249
+ bases.append(b)
1250
+ return self.func(*bases), e1
1251
+
1252
+ def _eval_is_polynomial(self, syms):
1253
+ return all(term._eval_is_polynomial(syms) for term in self.args)
1254
+
1255
+ def _eval_is_rational_function(self, syms):
1256
+ return all(term._eval_is_rational_function(syms) for term in self.args)
1257
+
1258
+ def _eval_is_meromorphic(self, x, a):
1259
+ return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args),
1260
+ quick_exit=True)
1261
+
1262
+ def _eval_is_algebraic_expr(self, syms):
1263
+ return all(term._eval_is_algebraic_expr(syms) for term in self.args)
1264
+
1265
+ _eval_is_commutative = lambda self: _fuzzy_group(
1266
+ a.is_commutative for a in self.args)
1267
+
1268
+ def _eval_is_complex(self):
1269
+ comp = _fuzzy_group(a.is_complex for a in self.args)
1270
+ if comp is False:
1271
+ if any(a.is_infinite for a in self.args):
1272
+ if any(a.is_zero is not False for a in self.args):
1273
+ return None
1274
+ return False
1275
+ return comp
1276
+
1277
+ def _eval_is_zero_infinite_helper(self):
1278
+ #
1279
+ # Helper used by _eval_is_zero and _eval_is_infinite.
1280
+ #
1281
+ # Three-valued logic is tricky so let us reason this carefully. It
1282
+ # would be nice to say that we just check is_zero/is_infinite in all
1283
+ # args but we need to be careful about the case that one arg is zero
1284
+ # and another is infinite like Mul(0, oo) or more importantly a case
1285
+ # where it is not known if the arguments are zero or infinite like
1286
+ # Mul(y, 1/x). If either y or x could be zero then there is a
1287
+ # *possibility* that we have Mul(0, oo) which should give None for both
1288
+ # is_zero and is_infinite.
1289
+ #
1290
+ # We keep track of whether we have seen a zero or infinity but we also
1291
+ # need to keep track of whether we have *possibly* seen one which
1292
+ # would be indicated by None.
1293
+ #
1294
+ # For each argument there is the possibility that is_zero might give
1295
+ # True, False or None and likewise that is_infinite might give True,
1296
+ # False or None, giving 9 combinations. The True cases for is_zero and
1297
+ # is_infinite are mutually exclusive though so there are 3 main cases:
1298
+ #
1299
+ # - is_zero = True
1300
+ # - is_infinite = True
1301
+ # - is_zero and is_infinite are both either False or None
1302
+ #
1303
+ # At the end seen_zero and seen_infinite can be any of 9 combinations
1304
+ # of True/False/None. Unless one is False though we cannot return
1305
+ # anything except None:
1306
+ #
1307
+ # - is_zero=True needs seen_zero=True and seen_infinite=False
1308
+ # - is_zero=False needs seen_zero=False
1309
+ # - is_infinite=True needs seen_infinite=True and seen_zero=False
1310
+ # - is_infinite=False needs seen_infinite=False
1311
+ # - anything else gives both is_zero=None and is_infinite=None
1312
+ #
1313
+ # The loop only sets the flags to True or None and never back to False.
1314
+ # Hence as soon as neither flag is False we exit early returning None.
1315
+ # In particular as soon as we encounter a single arg that has
1316
+ # is_zero=is_infinite=None we exit. This is a common case since it is
1317
+ # the default assumptions for a Symbol and also the case for most
1318
+ # expressions containing such a symbol. The early exit gives a big
1319
+ # speedup for something like Mul(*symbols('x:1000')).is_zero.
1320
+ #
1321
+ seen_zero = seen_infinite = False
1322
+
1323
+ for a in self.args:
1324
+ if a.is_zero:
1325
+ if seen_infinite is not False:
1326
+ return None, None
1327
+ seen_zero = True
1328
+ elif a.is_infinite:
1329
+ if seen_zero is not False:
1330
+ return None, None
1331
+ seen_infinite = True
1332
+ else:
1333
+ if seen_zero is False and a.is_zero is None:
1334
+ if seen_infinite is not False:
1335
+ return None, None
1336
+ seen_zero = None
1337
+ if seen_infinite is False and a.is_infinite is None:
1338
+ if seen_zero is not False:
1339
+ return None, None
1340
+ seen_infinite = None
1341
+
1342
+ return seen_zero, seen_infinite
1343
+
1344
+ def _eval_is_zero(self):
1345
+ # True iff any arg is zero and no arg is infinite but need to handle
1346
+ # three valued logic carefully.
1347
+ seen_zero, seen_infinite = self._eval_is_zero_infinite_helper()
1348
+
1349
+ if seen_zero is False:
1350
+ return False
1351
+ elif seen_zero is True and seen_infinite is False:
1352
+ return True
1353
+ else:
1354
+ return None
1355
+
1356
+ def _eval_is_infinite(self):
1357
+ # True iff any arg is infinite and no arg is zero but need to handle
1358
+ # three valued logic carefully.
1359
+ seen_zero, seen_infinite = self._eval_is_zero_infinite_helper()
1360
+
1361
+ if seen_infinite is True and seen_zero is False:
1362
+ return True
1363
+ elif seen_infinite is False:
1364
+ return False
1365
+ else:
1366
+ return None
1367
+
1368
+ # We do not need to implement _eval_is_finite because the assumptions
1369
+ # system can infer it from finite = not infinite.
1370
+
1371
+ def _eval_is_rational(self):
1372
+ r = _fuzzy_group((a.is_rational for a in self.args), quick_exit=True)
1373
+ if r:
1374
+ return r
1375
+ elif r is False:
1376
+ # All args except one are rational
1377
+ if all(a.is_zero is False for a in self.args):
1378
+ return False
1379
+
1380
+ def _eval_is_algebraic(self):
1381
+ r = _fuzzy_group((a.is_algebraic for a in self.args), quick_exit=True)
1382
+ if r:
1383
+ return r
1384
+ elif r is False:
1385
+ # All args except one are algebraic
1386
+ if all(a.is_zero is False for a in self.args):
1387
+ return False
1388
+
1389
+ # without involving odd/even checks this code would suffice:
1390
+ #_eval_is_integer = lambda self: _fuzzy_group(
1391
+ # (a.is_integer for a in self.args), quick_exit=True)
1392
+ def _eval_is_integer(self):
1393
+ from sympy.ntheory.factor_ import trailing
1394
+ is_rational = self._eval_is_rational()
1395
+ if is_rational is False:
1396
+ return False
1397
+
1398
+ numerators = []
1399
+ denominators = []
1400
+ unknown = False
1401
+ for a in self.args:
1402
+ hit = False
1403
+ if a.is_integer:
1404
+ if abs(a) is not S.One:
1405
+ numerators.append(a)
1406
+ elif a.is_Rational:
1407
+ n, d = a.as_numer_denom()
1408
+ if abs(n) is not S.One:
1409
+ numerators.append(n)
1410
+ if d is not S.One:
1411
+ denominators.append(d)
1412
+ elif a.is_Pow:
1413
+ b, e = a.as_base_exp()
1414
+ if not b.is_integer or not e.is_integer:
1415
+ hit = unknown = True
1416
+ if e.is_negative:
1417
+ denominators.append(2 if a is S.Half else
1418
+ Pow(a, S.NegativeOne))
1419
+ elif not hit:
1420
+ # int b and pos int e: a = b**e is integer
1421
+ assert not e.is_positive
1422
+ # for rational self and e equal to zero: a = b**e is 1
1423
+ assert not e.is_zero
1424
+ return # sign of e unknown -> self.is_integer unknown
1425
+ else:
1426
+ # x**2, 2**x, or x**y with x and y int-unknown -> unknown
1427
+ return
1428
+ else:
1429
+ return
1430
+
1431
+ if not denominators and not unknown:
1432
+ return True
1433
+
1434
+ allodd = lambda x: all(i.is_odd for i in x)
1435
+ alleven = lambda x: all(i.is_even for i in x)
1436
+ anyeven = lambda x: any(i.is_even for i in x)
1437
+
1438
+ from .relational import is_gt
1439
+ if not numerators and denominators and all(
1440
+ is_gt(_, S.One) for _ in denominators):
1441
+ return False
1442
+ elif unknown:
1443
+ return
1444
+ elif allodd(numerators) and anyeven(denominators):
1445
+ return False
1446
+ elif anyeven(numerators) and denominators == [2]:
1447
+ return True
1448
+ elif alleven(numerators) and allodd(denominators
1449
+ ) and (Mul(*denominators, evaluate=False) - 1
1450
+ ).is_positive:
1451
+ return False
1452
+ if len(denominators) == 1:
1453
+ d = denominators[0]
1454
+ if d.is_Integer and d.is_even:
1455
+ # if minimal power of 2 in num vs den is not
1456
+ # negative then we have an integer
1457
+ if (Add(*[i.as_base_exp()[1] for i in
1458
+ numerators if i.is_even]) - trailing(d.p)
1459
+ ).is_nonnegative:
1460
+ return True
1461
+ if len(numerators) == 1:
1462
+ n = numerators[0]
1463
+ if n.is_Integer and n.is_even:
1464
+ # if minimal power of 2 in den vs num is positive
1465
+ # then we have have a non-integer
1466
+ if (Add(*[i.as_base_exp()[1] for i in
1467
+ denominators if i.is_even]) - trailing(n.p)
1468
+ ).is_positive:
1469
+ return False
1470
+
1471
+ def _eval_is_polar(self):
1472
+ has_polar = any(arg.is_polar for arg in self.args)
1473
+ return has_polar and \
1474
+ all(arg.is_polar or arg.is_positive for arg in self.args)
1475
+
1476
+ def _eval_is_extended_real(self):
1477
+ return self._eval_real_imag(True)
1478
+
1479
+ def _eval_real_imag(self, real):
1480
+ zero = False
1481
+ t_not_re_im = None
1482
+
1483
+ for t in self.args:
1484
+ if (t.is_complex or t.is_infinite) is False and t.is_extended_real is False:
1485
+ return False
1486
+ elif t.is_imaginary: # I
1487
+ real = not real
1488
+ elif t.is_extended_real: # 2
1489
+ if not zero:
1490
+ z = t.is_zero
1491
+ if not z and zero is False:
1492
+ zero = z
1493
+ elif z:
1494
+ if all(a.is_finite for a in self.args):
1495
+ return True
1496
+ return
1497
+ elif t.is_extended_real is False:
1498
+ # symbolic or literal like `2 + I` or symbolic imaginary
1499
+ if t_not_re_im:
1500
+ return # complex terms might cancel
1501
+ t_not_re_im = t
1502
+ elif t.is_imaginary is False: # symbolic like `2` or `2 + I`
1503
+ if t_not_re_im:
1504
+ return # complex terms might cancel
1505
+ t_not_re_im = t
1506
+ else:
1507
+ return
1508
+
1509
+ if t_not_re_im:
1510
+ if t_not_re_im.is_extended_real is False:
1511
+ if real: # like 3
1512
+ return zero # 3*(smthng like 2 + I or i) is not real
1513
+ if t_not_re_im.is_imaginary is False: # symbolic 2 or 2 + I
1514
+ if not real: # like I
1515
+ return zero # I*(smthng like 2 or 2 + I) is not real
1516
+ elif zero is False:
1517
+ return real # can't be trumped by 0
1518
+ elif real:
1519
+ return real # doesn't matter what zero is
1520
+
1521
+ def _eval_is_imaginary(self):
1522
+ if all(a.is_zero is False and a.is_finite for a in self.args):
1523
+ return self._eval_real_imag(False)
1524
+
1525
+ def _eval_is_hermitian(self):
1526
+ return self._eval_herm_antiherm(True)
1527
+
1528
+ def _eval_is_antihermitian(self):
1529
+ return self._eval_herm_antiherm(False)
1530
+
1531
+ def _eval_herm_antiherm(self, herm):
1532
+ for t in self.args:
1533
+ if t.is_hermitian is None or t.is_antihermitian is None:
1534
+ return
1535
+ if t.is_hermitian:
1536
+ continue
1537
+ elif t.is_antihermitian:
1538
+ herm = not herm
1539
+ else:
1540
+ return
1541
+
1542
+ if herm is not False:
1543
+ return herm
1544
+
1545
+ is_zero = self._eval_is_zero()
1546
+ if is_zero:
1547
+ return True
1548
+ elif is_zero is False:
1549
+ return herm
1550
+
1551
+ def _eval_is_irrational(self):
1552
+ for t in self.args:
1553
+ a = t.is_irrational
1554
+ if a:
1555
+ others = list(self.args)
1556
+ others.remove(t)
1557
+ if all((x.is_rational and fuzzy_not(x.is_zero)) is True for x in others):
1558
+ return True
1559
+ return
1560
+ if a is None:
1561
+ return
1562
+ if all(x.is_real for x in self.args):
1563
+ return False
1564
+
1565
+ def _eval_is_extended_positive(self):
1566
+ """Return True if self is positive, False if not, and None if it
1567
+ cannot be determined.
1568
+
1569
+ Explanation
1570
+ ===========
1571
+
1572
+ This algorithm is non-recursive and works by keeping track of the
1573
+ sign which changes when a negative or nonpositive is encountered.
1574
+ Whether a nonpositive or nonnegative is seen is also tracked since
1575
+ the presence of these makes it impossible to return True, but
1576
+ possible to return False if the end result is nonpositive. e.g.
1577
+
1578
+ pos * neg * nonpositive -> pos or zero -> None is returned
1579
+ pos * neg * nonnegative -> neg or zero -> False is returned
1580
+ """
1581
+ return self._eval_pos_neg(1)
1582
+
1583
+ def _eval_pos_neg(self, sign):
1584
+ saw_NON = saw_NOT = False
1585
+ for t in self.args:
1586
+ if t.is_extended_positive:
1587
+ continue
1588
+ elif t.is_extended_negative:
1589
+ sign = -sign
1590
+ elif t.is_zero:
1591
+ if all(a.is_finite for a in self.args):
1592
+ return False
1593
+ return
1594
+ elif t.is_extended_nonpositive:
1595
+ sign = -sign
1596
+ saw_NON = True
1597
+ elif t.is_extended_nonnegative:
1598
+ saw_NON = True
1599
+ # FIXME: is_positive/is_negative is False doesn't take account of
1600
+ # Symbol('x', infinite=True, extended_real=True) which has
1601
+ # e.g. is_positive is False but has uncertain sign.
1602
+ elif t.is_positive is False:
1603
+ sign = -sign
1604
+ if saw_NOT:
1605
+ return
1606
+ saw_NOT = True
1607
+ elif t.is_negative is False:
1608
+ if saw_NOT:
1609
+ return
1610
+ saw_NOT = True
1611
+ else:
1612
+ return
1613
+ if sign == 1 and saw_NON is False and saw_NOT is False:
1614
+ return True
1615
+ if sign < 0:
1616
+ return False
1617
+
1618
+ def _eval_is_extended_negative(self):
1619
+ return self._eval_pos_neg(-1)
1620
+
1621
+ def _eval_is_odd(self):
1622
+ is_integer = self._eval_is_integer()
1623
+ if is_integer is not True:
1624
+ return is_integer
1625
+
1626
+ from sympy.simplify.radsimp import fraction
1627
+ n, d = fraction(self)
1628
+ if d.is_Integer and d.is_even:
1629
+ from sympy.ntheory.factor_ import trailing
1630
+ # if minimal power of 2 in num vs den is
1631
+ # positive then we have an even number
1632
+ if (Add(*[i.as_base_exp()[1] for i in
1633
+ Mul.make_args(n) if i.is_even]) - trailing(d.p)
1634
+ ).is_positive:
1635
+ return False
1636
+ return
1637
+ r, acc = True, 1
1638
+ for t in self.args:
1639
+ if abs(t) is S.One:
1640
+ continue
1641
+ if t.is_even:
1642
+ return False
1643
+ if r is False:
1644
+ pass
1645
+ elif acc != 1 and (acc + t).is_odd:
1646
+ r = False
1647
+ elif t.is_even is None:
1648
+ r = None
1649
+ acc = t
1650
+ return r
1651
+
1652
+ def _eval_is_even(self):
1653
+ from sympy.simplify.radsimp import fraction
1654
+ n, d = fraction(self)
1655
+ if n.is_Integer and n.is_even:
1656
+ # if minimal power of 2 in den vs num is not
1657
+ # negative then this is not an integer and
1658
+ # can't be even
1659
+ from sympy.ntheory.factor_ import trailing
1660
+ if (Add(*[i.as_base_exp()[1] for i in
1661
+ Mul.make_args(d) if i.is_even]) - trailing(n.p)
1662
+ ).is_nonnegative:
1663
+ return False
1664
+
1665
+ def _eval_is_composite(self):
1666
+ """
1667
+ Here we count the number of arguments that have a minimum value
1668
+ greater than two.
1669
+ If there are more than one of such a symbol then the result is composite.
1670
+ Else, the result cannot be determined.
1671
+ """
1672
+ number_of_args = 0 # count of symbols with minimum value greater than one
1673
+ for arg in self.args:
1674
+ if not (arg.is_integer and arg.is_positive):
1675
+ return None
1676
+ if (arg-1).is_positive:
1677
+ number_of_args += 1
1678
+
1679
+ if number_of_args > 1:
1680
+ return True
1681
+
1682
+ def _eval_subs(self, old, new):
1683
+ from sympy.functions.elementary.complexes import sign
1684
+ from sympy.ntheory.factor_ import multiplicity
1685
+ from sympy.simplify.powsimp import powdenest
1686
+ from sympy.simplify.radsimp import fraction
1687
+
1688
+ if not old.is_Mul:
1689
+ return None
1690
+
1691
+ # try keep replacement literal so -2*x doesn't replace 4*x
1692
+ if old.args[0].is_Number and old.args[0] < 0:
1693
+ if self.args[0].is_Number:
1694
+ if self.args[0] < 0:
1695
+ return self._subs(-old, -new)
1696
+ return None
1697
+
1698
+ def base_exp(a):
1699
+ # if I and -1 are in a Mul, they get both end up with
1700
+ # a -1 base (see issue 6421); all we want here are the
1701
+ # true Pow or exp separated into base and exponent
1702
+ from sympy.functions.elementary.exponential import exp
1703
+ if a.is_Pow or isinstance(a, exp):
1704
+ return a.as_base_exp()
1705
+ return a, S.One
1706
+
1707
+ def breakup(eq):
1708
+ """break up powers of eq when treated as a Mul:
1709
+ b**(Rational*e) -> b**e, Rational
1710
+ commutatives come back as a dictionary {b**e: Rational}
1711
+ noncommutatives come back as a list [(b**e, Rational)]
1712
+ """
1713
+
1714
+ (c, nc) = (defaultdict(int), [])
1715
+ for a in Mul.make_args(eq):
1716
+ a = powdenest(a)
1717
+ (b, e) = base_exp(a)
1718
+ if e is not S.One:
1719
+ (co, _) = e.as_coeff_mul()
1720
+ b = Pow(b, e/co)
1721
+ e = co
1722
+ if a.is_commutative:
1723
+ c[b] += e
1724
+ else:
1725
+ nc.append([b, e])
1726
+ return (c, nc)
1727
+
1728
+ def rejoin(b, co):
1729
+ """
1730
+ Put rational back with exponent; in general this is not ok, but
1731
+ since we took it from the exponent for analysis, it's ok to put
1732
+ it back.
1733
+ """
1734
+
1735
+ (b, e) = base_exp(b)
1736
+ return Pow(b, e*co)
1737
+
1738
+ def ndiv(a, b):
1739
+ """if b divides a in an extractive way (like 1/4 divides 1/2
1740
+ but not vice versa, and 2/5 does not divide 1/3) then return
1741
+ the integer number of times it divides, else return 0.
1742
+ """
1743
+ if not b.q % a.q or not a.q % b.q:
1744
+ return int(a/b)
1745
+ return 0
1746
+
1747
+ # give Muls in the denominator a chance to be changed (see issue 5651)
1748
+ # rv will be the default return value
1749
+ rv = None
1750
+ n, d = fraction(self)
1751
+ self2 = self
1752
+ if d is not S.One:
1753
+ self2 = n._subs(old, new)/d._subs(old, new)
1754
+ if not self2.is_Mul:
1755
+ return self2._subs(old, new)
1756
+ if self2 != self:
1757
+ rv = self2
1758
+
1759
+ # Now continue with regular substitution.
1760
+
1761
+ # handle the leading coefficient and use it to decide if anything
1762
+ # should even be started; we always know where to find the Rational
1763
+ # so it's a quick test
1764
+
1765
+ co_self = self2.args[0]
1766
+ co_old = old.args[0]
1767
+ co_xmul = None
1768
+ if co_old.is_Rational and co_self.is_Rational:
1769
+ # if coeffs are the same there will be no updating to do
1770
+ # below after breakup() step; so skip (and keep co_xmul=None)
1771
+ if co_old != co_self:
1772
+ co_xmul = co_self.extract_multiplicatively(co_old)
1773
+ elif co_old.is_Rational:
1774
+ return rv
1775
+
1776
+ # break self and old into factors
1777
+
1778
+ (c, nc) = breakup(self2)
1779
+ (old_c, old_nc) = breakup(old)
1780
+
1781
+ # update the coefficients if we had an extraction
1782
+ # e.g. if co_self were 2*(3/35*x)**2 and co_old = 3/5
1783
+ # then co_self in c is replaced by (3/5)**2 and co_residual
1784
+ # is 2*(1/7)**2
1785
+
1786
+ if co_xmul and co_xmul.is_Rational and abs(co_old) != 1:
1787
+ mult = S(multiplicity(abs(co_old), co_self))
1788
+ c.pop(co_self)
1789
+ if co_old in c:
1790
+ c[co_old] += mult
1791
+ else:
1792
+ c[co_old] = mult
1793
+ co_residual = co_self/co_old**mult
1794
+ else:
1795
+ co_residual = 1
1796
+
1797
+ # do quick tests to see if we can't succeed
1798
+
1799
+ ok = True
1800
+ if len(old_nc) > len(nc):
1801
+ # more non-commutative terms
1802
+ ok = False
1803
+ elif len(old_c) > len(c):
1804
+ # more commutative terms
1805
+ ok = False
1806
+ elif {i[0] for i in old_nc}.difference({i[0] for i in nc}):
1807
+ # unmatched non-commutative bases
1808
+ ok = False
1809
+ elif set(old_c).difference(set(c)):
1810
+ # unmatched commutative terms
1811
+ ok = False
1812
+ elif any(sign(c[b]) != sign(old_c[b]) for b in old_c):
1813
+ # differences in sign
1814
+ ok = False
1815
+ if not ok:
1816
+ return rv
1817
+
1818
+ if not old_c:
1819
+ cdid = None
1820
+ else:
1821
+ rat = []
1822
+ for (b, old_e) in old_c.items():
1823
+ c_e = c[b]
1824
+ rat.append(ndiv(c_e, old_e))
1825
+ if not rat[-1]:
1826
+ return rv
1827
+ cdid = min(rat)
1828
+
1829
+ if not old_nc:
1830
+ ncdid = None
1831
+ for i in range(len(nc)):
1832
+ nc[i] = rejoin(*nc[i])
1833
+ else:
1834
+ ncdid = 0 # number of nc replacements we did
1835
+ take = len(old_nc) # how much to look at each time
1836
+ limit = cdid or S.Infinity # max number that we can take
1837
+ failed = [] # failed terms will need subs if other terms pass
1838
+ i = 0
1839
+ while limit and i + take <= len(nc):
1840
+ hit = False
1841
+
1842
+ # the bases must be equivalent in succession, and
1843
+ # the powers must be extractively compatible on the
1844
+ # first and last factor but equal in between.
1845
+
1846
+ rat = []
1847
+ for j in range(take):
1848
+ if nc[i + j][0] != old_nc[j][0]:
1849
+ break
1850
+ elif j == 0:
1851
+ rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
1852
+ elif j == take - 1:
1853
+ rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
1854
+ elif nc[i + j][1] != old_nc[j][1]:
1855
+ break
1856
+ else:
1857
+ rat.append(1)
1858
+ j += 1
1859
+ else:
1860
+ ndo = min(rat)
1861
+ if ndo:
1862
+ if take == 1:
1863
+ if cdid:
1864
+ ndo = min(cdid, ndo)
1865
+ nc[i] = Pow(new, ndo)*rejoin(nc[i][0],
1866
+ nc[i][1] - ndo*old_nc[0][1])
1867
+ else:
1868
+ ndo = 1
1869
+
1870
+ # the left residual
1871
+
1872
+ l = rejoin(nc[i][0], nc[i][1] - ndo*
1873
+ old_nc[0][1])
1874
+
1875
+ # eliminate all middle terms
1876
+
1877
+ mid = new
1878
+
1879
+ # the right residual (which may be the same as the middle if take == 2)
1880
+
1881
+ ir = i + take - 1
1882
+ r = (nc[ir][0], nc[ir][1] - ndo*
1883
+ old_nc[-1][1])
1884
+ if r[1]:
1885
+ if i + take < len(nc):
1886
+ nc[i:i + take] = [l*mid, r]
1887
+ else:
1888
+ r = rejoin(*r)
1889
+ nc[i:i + take] = [l*mid*r]
1890
+ else:
1891
+
1892
+ # there was nothing left on the right
1893
+
1894
+ nc[i:i + take] = [l*mid]
1895
+
1896
+ limit -= ndo
1897
+ ncdid += ndo
1898
+ hit = True
1899
+ if not hit:
1900
+
1901
+ # do the subs on this failing factor
1902
+
1903
+ failed.append(i)
1904
+ i += 1
1905
+ else:
1906
+
1907
+ if not ncdid:
1908
+ return rv
1909
+
1910
+ # although we didn't fail, certain nc terms may have
1911
+ # failed so we rebuild them after attempting a partial
1912
+ # subs on them
1913
+
1914
+ failed.extend(range(i, len(nc)))
1915
+ for i in failed:
1916
+ nc[i] = rejoin(*nc[i]).subs(old, new)
1917
+
1918
+ # rebuild the expression
1919
+
1920
+ if cdid is None:
1921
+ do = ncdid
1922
+ elif ncdid is None:
1923
+ do = cdid
1924
+ else:
1925
+ do = min(ncdid, cdid)
1926
+
1927
+ margs = []
1928
+ for b in c:
1929
+ if b in old_c:
1930
+
1931
+ # calculate the new exponent
1932
+
1933
+ e = c[b] - old_c[b]*do
1934
+ margs.append(rejoin(b, e))
1935
+ else:
1936
+ margs.append(rejoin(b.subs(old, new), c[b]))
1937
+ if cdid and not ncdid:
1938
+
1939
+ # in case we are replacing commutative with non-commutative,
1940
+ # we want the new term to come at the front just like the
1941
+ # rest of this routine
1942
+
1943
+ margs = [Pow(new, cdid)] + margs
1944
+ return co_residual*self2.func(*margs)*self2.func(*nc)
1945
+
1946
+ def _eval_nseries(self, x, n, logx, cdir=0):
1947
+ from .function import PoleError
1948
+ from sympy.functions.elementary.integers import ceiling
1949
+ from sympy.series.order import Order
1950
+
1951
+ def coeff_exp(term, x):
1952
+ lt = term.as_coeff_exponent(x)
1953
+ if lt[0].has(x):
1954
+ try:
1955
+ lt = term.leadterm(x)
1956
+ except ValueError:
1957
+ return term, S.Zero
1958
+ return lt
1959
+
1960
+ ords = []
1961
+
1962
+ try:
1963
+ for t in self.args:
1964
+ coeff, exp = t.leadterm(x)
1965
+ if not coeff.has(x):
1966
+ ords.append((t, exp))
1967
+ else:
1968
+ raise ValueError
1969
+
1970
+ n0 = sum(t[1] for t in ords if t[1].is_number)
1971
+ facs = []
1972
+ for t, m in ords:
1973
+ n1 = ceiling(n - n0 + (m if m.is_number else 0))
1974
+ s = t.nseries(x, n=n1, logx=logx, cdir=cdir)
1975
+ ns = s.getn()
1976
+ if ns is not None:
1977
+ if ns < n1: # less than expected
1978
+ n -= n1 - ns # reduce n
1979
+ facs.append(s)
1980
+
1981
+ except (ValueError, NotImplementedError, TypeError, AttributeError, PoleError):
1982
+ n0 = sympify(sum(t[1] for t in ords if t[1].is_number))
1983
+ if n0.is_nonnegative:
1984
+ n0 = S.Zero
1985
+ facs = [t.nseries(x, n=ceiling(n-n0), logx=logx, cdir=cdir) for t in self.args]
1986
+ from sympy.simplify.powsimp import powsimp
1987
+ res = powsimp(self.func(*facs).expand(), combine='exp', deep=True)
1988
+ if res.has(Order):
1989
+ res += Order(x**n, x)
1990
+ return res
1991
+
1992
+ res = S.Zero
1993
+ ords2 = [Add.make_args(factor) for factor in facs]
1994
+
1995
+ for fac in product(*ords2):
1996
+ ords3 = [coeff_exp(term, x) for term in fac]
1997
+ coeffs, powers = zip(*ords3)
1998
+ power = sum(powers)
1999
+ if (power - n).is_negative:
2000
+ res += Mul(*coeffs)*(x**power)
2001
+
2002
+ def max_degree(e, x):
2003
+ if e is x:
2004
+ return S.One
2005
+ if e.is_Atom:
2006
+ return S.Zero
2007
+ if e.is_Add:
2008
+ return max(max_degree(a, x) for a in e.args)
2009
+ if e.is_Mul:
2010
+ return Add(*[max_degree(a, x) for a in e.args])
2011
+ if e.is_Pow:
2012
+ return max_degree(e.base, x)*e.exp
2013
+ return S.Zero
2014
+
2015
+ if self.is_polynomial(x):
2016
+ from sympy.polys.polyerrors import PolynomialError
2017
+ from sympy.polys.polytools import degree
2018
+ try:
2019
+ if max_degree(self, x) >= n or degree(self, x) != degree(res, x):
2020
+ res += Order(x**n, x)
2021
+ except PolynomialError:
2022
+ pass
2023
+ else:
2024
+ return res
2025
+
2026
+ if res != self:
2027
+ if (self - res).subs(x, 0) == S.Zero and n > 0:
2028
+ lt = self._eval_as_leading_term(x, logx=logx, cdir=cdir)
2029
+ if lt == S.Zero:
2030
+ return res
2031
+ res += Order(x**n, x)
2032
+ return res
2033
+
2034
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
2035
+ return self.func(*[t.as_leading_term(x, logx=logx, cdir=cdir) for t in self.args])
2036
+
2037
+ def _eval_conjugate(self):
2038
+ return self.func(*[t.conjugate() for t in self.args])
2039
+
2040
+ def _eval_transpose(self):
2041
+ return self.func(*[t.transpose() for t in self.args[::-1]])
2042
+
2043
+ def _eval_adjoint(self):
2044
+ return self.func(*[t.adjoint() for t in self.args[::-1]])
2045
+
2046
+ def as_content_primitive(self, radical=False, clear=True):
2047
+ """Return the tuple (R, self/R) where R is the positive Rational
2048
+ extracted from self.
2049
+
2050
+ Examples
2051
+ ========
2052
+
2053
+ >>> from sympy import sqrt
2054
+ >>> (-3*sqrt(2)*(2 - 2*sqrt(2))).as_content_primitive()
2055
+ (6, -sqrt(2)*(1 - sqrt(2)))
2056
+
2057
+ See docstring of Expr.as_content_primitive for more examples.
2058
+ """
2059
+
2060
+ coef = S.One
2061
+ args = []
2062
+ for a in self.args:
2063
+ c, p = a.as_content_primitive(radical=radical, clear=clear)
2064
+ coef *= c
2065
+ if p is not S.One:
2066
+ args.append(p)
2067
+ # don't use self._from_args here to reconstruct args
2068
+ # since there may be identical args now that should be combined
2069
+ # e.g. (2+2*x)*(3+3*x) should be (6, (1 + x)**2) not (6, (1+x)*(1+x))
2070
+ return coef, self.func(*args)
2071
+
2072
+ def as_ordered_factors(self, order=None):
2073
+ """Transform an expression into an ordered list of factors.
2074
+
2075
+ Examples
2076
+ ========
2077
+
2078
+ >>> from sympy import sin, cos
2079
+ >>> from sympy.abc import x, y
2080
+
2081
+ >>> (2*x*y*sin(x)*cos(x)).as_ordered_factors()
2082
+ [2, x, y, sin(x), cos(x)]
2083
+
2084
+ """
2085
+ cpart, ncpart = self.args_cnc()
2086
+ cpart.sort(key=lambda expr: expr.sort_key(order=order))
2087
+ return cpart + ncpart
2088
+
2089
+ @property
2090
+ def _sorted_args(self):
2091
+ return tuple(self.as_ordered_factors())
2092
+
2093
+ mul = AssocOpDispatcher('mul')
2094
+
2095
+
2096
+ def prod(a, start=1):
2097
+ """Return product of elements of a. Start with int 1 so if only
2098
+ ints are included then an int result is returned.
2099
+
2100
+ Examples
2101
+ ========
2102
+
2103
+ >>> from sympy import prod, S
2104
+ >>> prod(range(3))
2105
+ 0
2106
+ >>> type(_) is int
2107
+ True
2108
+ >>> prod([S(2), 3])
2109
+ 6
2110
+ >>> _.is_Integer
2111
+ True
2112
+
2113
+ You can start the product at something other than 1:
2114
+
2115
+ >>> prod([1, 2], 3)
2116
+ 6
2117
+
2118
+ """
2119
+ return reduce(operator.mul, a, start)
2120
+
2121
+
2122
+ def _keep_coeff(coeff, factors, clear=True, sign=False):
2123
+ """Return ``coeff*factors`` unevaluated if necessary.
2124
+
2125
+ If ``clear`` is False, do not keep the coefficient as a factor
2126
+ if it can be distributed on a single factor such that one or
2127
+ more terms will still have integer coefficients.
2128
+
2129
+ If ``sign`` is True, allow a coefficient of -1 to remain factored out.
2130
+
2131
+ Examples
2132
+ ========
2133
+
2134
+ >>> from sympy.core.mul import _keep_coeff
2135
+ >>> from sympy.abc import x, y
2136
+ >>> from sympy import S
2137
+
2138
+ >>> _keep_coeff(S.Half, x + 2)
2139
+ (x + 2)/2
2140
+ >>> _keep_coeff(S.Half, x + 2, clear=False)
2141
+ x/2 + 1
2142
+ >>> _keep_coeff(S.Half, (x + 2)*y, clear=False)
2143
+ y*(x + 2)/2
2144
+ >>> _keep_coeff(S(-1), x + y)
2145
+ -x - y
2146
+ >>> _keep_coeff(S(-1), x + y, sign=True)
2147
+ -(x + y)
2148
+ """
2149
+ if not coeff.is_Number:
2150
+ if factors.is_Number:
2151
+ factors, coeff = coeff, factors
2152
+ else:
2153
+ return coeff*factors
2154
+ if factors is S.One:
2155
+ return coeff
2156
+ if coeff is S.One:
2157
+ return factors
2158
+ elif coeff is S.NegativeOne and not sign:
2159
+ return -factors
2160
+ elif factors.is_Add:
2161
+ if not clear and coeff.is_Rational and coeff.q != 1:
2162
+ args = [i.as_coeff_Mul() for i in factors.args]
2163
+ args = [(_keep_coeff(c, coeff), m) for c, m in args]
2164
+ if any(c.is_Integer for c, _ in args):
2165
+ return Add._from_args([Mul._from_args(
2166
+ i[1:] if i[0] == 1 else i) for i in args])
2167
+ return Mul(coeff, factors, evaluate=False)
2168
+ elif factors.is_Mul:
2169
+ margs = list(factors.args)
2170
+ if margs[0].is_Number:
2171
+ margs[0] *= coeff
2172
+ if margs[0] == 1:
2173
+ margs.pop(0)
2174
+ else:
2175
+ margs.insert(0, coeff)
2176
+ return Mul._from_args(margs)
2177
+ else:
2178
+ m = coeff*factors
2179
+ if m.is_Number and not factors.is_Number:
2180
+ m = Mul._from_args((coeff, factors))
2181
+ return m
2182
+
2183
+ def expand_2arg(e):
2184
+ def do(e):
2185
+ if e.is_Mul:
2186
+ c, r = e.as_coeff_Mul()
2187
+ if c.is_Number and r.is_Add:
2188
+ return _unevaluated_Add(*[c*ri for ri in r.args])
2189
+ return e
2190
+ return bottom_up(e, do)
2191
+
2192
+
2193
+ from .numbers import Rational
2194
+ from .power import Pow
2195
+ from .add import Add, _unevaluated_Add
env-llmeval/lib/python3.10/site-packages/sympy/core/numbers.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/sympy/core/operations.py ADDED
@@ -0,0 +1,722 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from operator import attrgetter
3
+ from collections import defaultdict
4
+
5
+ from sympy.utilities.exceptions import sympy_deprecation_warning
6
+
7
+ from .sympify import _sympify as _sympify_, sympify
8
+ from .basic import Basic
9
+ from .cache import cacheit
10
+ from .sorting import ordered
11
+ from .logic import fuzzy_and
12
+ from .parameters import global_parameters
13
+ from sympy.utilities.iterables import sift
14
+ from sympy.multipledispatch.dispatcher import (Dispatcher,
15
+ ambiguity_register_error_ignore_dup,
16
+ str_signature, RaiseNotImplementedError)
17
+
18
+
19
+ class AssocOp(Basic):
20
+ """ Associative operations, can separate noncommutative and
21
+ commutative parts.
22
+
23
+ (a op b) op c == a op (b op c) == a op b op c.
24
+
25
+ Base class for Add and Mul.
26
+
27
+ This is an abstract base class, concrete derived classes must define
28
+ the attribute `identity`.
29
+
30
+ .. deprecated:: 1.7
31
+
32
+ Using arguments that aren't subclasses of :class:`~.Expr` in core
33
+ operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
34
+ deprecated. See :ref:`non-expr-args-deprecated` for details.
35
+
36
+ Parameters
37
+ ==========
38
+
39
+ *args :
40
+ Arguments which are operated
41
+
42
+ evaluate : bool, optional
43
+ Evaluate the operation. If not passed, refer to ``global_parameters.evaluate``.
44
+ """
45
+
46
+ # for performance reason, we don't let is_commutative go to assumptions,
47
+ # and keep it right here
48
+ __slots__: tuple[str, ...] = ('is_commutative',)
49
+
50
+ _args_type: type[Basic] | None = None
51
+
52
+ @cacheit
53
+ def __new__(cls, *args, evaluate=None, _sympify=True):
54
+ # Allow faster processing by passing ``_sympify=False``, if all arguments
55
+ # are already sympified.
56
+ if _sympify:
57
+ args = list(map(_sympify_, args))
58
+
59
+ # Disallow non-Expr args in Add/Mul
60
+ typ = cls._args_type
61
+ if typ is not None:
62
+ from .relational import Relational
63
+ if any(isinstance(arg, Relational) for arg in args):
64
+ raise TypeError("Relational cannot be used in %s" % cls.__name__)
65
+
66
+ # This should raise TypeError once deprecation period is over:
67
+ for arg in args:
68
+ if not isinstance(arg, typ):
69
+ sympy_deprecation_warning(
70
+ f"""
71
+
72
+ Using non-Expr arguments in {cls.__name__} is deprecated (in this case, one of
73
+ the arguments has type {type(arg).__name__!r}).
74
+
75
+ If you really did intend to use a multiplication or addition operation with
76
+ this object, use the * or + operator instead.
77
+
78
+ """,
79
+ deprecated_since_version="1.7",
80
+ active_deprecations_target="non-expr-args-deprecated",
81
+ stacklevel=4,
82
+ )
83
+
84
+ if evaluate is None:
85
+ evaluate = global_parameters.evaluate
86
+ if not evaluate:
87
+ obj = cls._from_args(args)
88
+ obj = cls._exec_constructor_postprocessors(obj)
89
+ return obj
90
+
91
+ args = [a for a in args if a is not cls.identity]
92
+
93
+ if len(args) == 0:
94
+ return cls.identity
95
+ if len(args) == 1:
96
+ return args[0]
97
+
98
+ c_part, nc_part, order_symbols = cls.flatten(args)
99
+ is_commutative = not nc_part
100
+ obj = cls._from_args(c_part + nc_part, is_commutative)
101
+ obj = cls._exec_constructor_postprocessors(obj)
102
+
103
+ if order_symbols is not None:
104
+ from sympy.series.order import Order
105
+ return Order(obj, *order_symbols)
106
+ return obj
107
+
108
+ @classmethod
109
+ def _from_args(cls, args, is_commutative=None):
110
+ """Create new instance with already-processed args.
111
+ If the args are not in canonical order, then a non-canonical
112
+ result will be returned, so use with caution. The order of
113
+ args may change if the sign of the args is changed."""
114
+ if len(args) == 0:
115
+ return cls.identity
116
+ elif len(args) == 1:
117
+ return args[0]
118
+
119
+ obj = super().__new__(cls, *args)
120
+ if is_commutative is None:
121
+ is_commutative = fuzzy_and(a.is_commutative for a in args)
122
+ obj.is_commutative = is_commutative
123
+ return obj
124
+
125
+ def _new_rawargs(self, *args, reeval=True, **kwargs):
126
+ """Create new instance of own class with args exactly as provided by
127
+ caller but returning the self class identity if args is empty.
128
+
129
+ Examples
130
+ ========
131
+
132
+ This is handy when we want to optimize things, e.g.
133
+
134
+ >>> from sympy import Mul, S
135
+ >>> from sympy.abc import x, y
136
+ >>> e = Mul(3, x, y)
137
+ >>> e.args
138
+ (3, x, y)
139
+ >>> Mul(*e.args[1:])
140
+ x*y
141
+ >>> e._new_rawargs(*e.args[1:]) # the same as above, but faster
142
+ x*y
143
+
144
+ Note: use this with caution. There is no checking of arguments at
145
+ all. This is best used when you are rebuilding an Add or Mul after
146
+ simply removing one or more args. If, for example, modifications,
147
+ result in extra 1s being inserted they will show up in the result:
148
+
149
+ >>> m = (x*y)._new_rawargs(S.One, x); m
150
+ 1*x
151
+ >>> m == x
152
+ False
153
+ >>> m.is_Mul
154
+ True
155
+
156
+ Another issue to be aware of is that the commutativity of the result
157
+ is based on the commutativity of self. If you are rebuilding the
158
+ terms that came from a commutative object then there will be no
159
+ problem, but if self was non-commutative then what you are
160
+ rebuilding may now be commutative.
161
+
162
+ Although this routine tries to do as little as possible with the
163
+ input, getting the commutativity right is important, so this level
164
+ of safety is enforced: commutativity will always be recomputed if
165
+ self is non-commutative and kwarg `reeval=False` has not been
166
+ passed.
167
+ """
168
+ if reeval and self.is_commutative is False:
169
+ is_commutative = None
170
+ else:
171
+ is_commutative = self.is_commutative
172
+ return self._from_args(args, is_commutative)
173
+
174
+ @classmethod
175
+ def flatten(cls, seq):
176
+ """Return seq so that none of the elements are of type `cls`. This is
177
+ the vanilla routine that will be used if a class derived from AssocOp
178
+ does not define its own flatten routine."""
179
+ # apply associativity, no commutativity property is used
180
+ new_seq = []
181
+ while seq:
182
+ o = seq.pop()
183
+ if o.__class__ is cls: # classes must match exactly
184
+ seq.extend(o.args)
185
+ else:
186
+ new_seq.append(o)
187
+ new_seq.reverse()
188
+
189
+ # c_part, nc_part, order_symbols
190
+ return [], new_seq, None
191
+
192
+ def _matches_commutative(self, expr, repl_dict=None, old=False):
193
+ """
194
+ Matches Add/Mul "pattern" to an expression "expr".
195
+
196
+ repl_dict ... a dictionary of (wild: expression) pairs, that get
197
+ returned with the results
198
+
199
+ This function is the main workhorse for Add/Mul.
200
+
201
+ Examples
202
+ ========
203
+
204
+ >>> from sympy import symbols, Wild, sin
205
+ >>> a = Wild("a")
206
+ >>> b = Wild("b")
207
+ >>> c = Wild("c")
208
+ >>> x, y, z = symbols("x y z")
209
+ >>> (a+sin(b)*c)._matches_commutative(x+sin(y)*z)
210
+ {a_: x, b_: y, c_: z}
211
+
212
+ In the example above, "a+sin(b)*c" is the pattern, and "x+sin(y)*z" is
213
+ the expression.
214
+
215
+ The repl_dict contains parts that were already matched. For example
216
+ here:
217
+
218
+ >>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z, repl_dict={a: x})
219
+ {a_: x, b_: y, c_: z}
220
+
221
+ the only function of the repl_dict is to return it in the
222
+ result, e.g. if you omit it:
223
+
224
+ >>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z)
225
+ {b_: y, c_: z}
226
+
227
+ the "a: x" is not returned in the result, but otherwise it is
228
+ equivalent.
229
+
230
+ """
231
+ from .function import _coeff_isneg
232
+ # make sure expr is Expr if pattern is Expr
233
+ from .expr import Expr
234
+ if isinstance(self, Expr) and not isinstance(expr, Expr):
235
+ return None
236
+
237
+ if repl_dict is None:
238
+ repl_dict = {}
239
+
240
+ # handle simple patterns
241
+ if self == expr:
242
+ return repl_dict
243
+
244
+ d = self._matches_simple(expr, repl_dict)
245
+ if d is not None:
246
+ return d
247
+
248
+ # eliminate exact part from pattern: (2+a+w1+w2).matches(expr) -> (w1+w2).matches(expr-a-2)
249
+ from .function import WildFunction
250
+ from .symbol import Wild
251
+ wild_part, exact_part = sift(self.args, lambda p:
252
+ p.has(Wild, WildFunction) and not expr.has(p),
253
+ binary=True)
254
+ if not exact_part:
255
+ wild_part = list(ordered(wild_part))
256
+ if self.is_Add:
257
+ # in addition to normal ordered keys, impose
258
+ # sorting on Muls with leading Number to put
259
+ # them in order
260
+ wild_part = sorted(wild_part, key=lambda x:
261
+ x.args[0] if x.is_Mul and x.args[0].is_Number else
262
+ 0)
263
+ else:
264
+ exact = self._new_rawargs(*exact_part)
265
+ free = expr.free_symbols
266
+ if free and (exact.free_symbols - free):
267
+ # there are symbols in the exact part that are not
268
+ # in the expr; but if there are no free symbols, let
269
+ # the matching continue
270
+ return None
271
+ newexpr = self._combine_inverse(expr, exact)
272
+ if not old and (expr.is_Add or expr.is_Mul):
273
+ check = newexpr
274
+ if _coeff_isneg(check):
275
+ check = -check
276
+ if check.count_ops() > expr.count_ops():
277
+ return None
278
+ newpattern = self._new_rawargs(*wild_part)
279
+ return newpattern.matches(newexpr, repl_dict)
280
+
281
+ # now to real work ;)
282
+ i = 0
283
+ saw = set()
284
+ while expr not in saw:
285
+ saw.add(expr)
286
+ args = tuple(ordered(self.make_args(expr)))
287
+ if self.is_Add and expr.is_Add:
288
+ # in addition to normal ordered keys, impose
289
+ # sorting on Muls with leading Number to put
290
+ # them in order
291
+ args = tuple(sorted(args, key=lambda x:
292
+ x.args[0] if x.is_Mul and x.args[0].is_Number else
293
+ 0))
294
+ expr_list = (self.identity,) + args
295
+ for last_op in reversed(expr_list):
296
+ for w in reversed(wild_part):
297
+ d1 = w.matches(last_op, repl_dict)
298
+ if d1 is not None:
299
+ d2 = self.xreplace(d1).matches(expr, d1)
300
+ if d2 is not None:
301
+ return d2
302
+
303
+ if i == 0:
304
+ if self.is_Mul:
305
+ # make e**i look like Mul
306
+ if expr.is_Pow and expr.exp.is_Integer:
307
+ from .mul import Mul
308
+ if expr.exp > 0:
309
+ expr = Mul(*[expr.base, expr.base**(expr.exp - 1)], evaluate=False)
310
+ else:
311
+ expr = Mul(*[1/expr.base, expr.base**(expr.exp + 1)], evaluate=False)
312
+ i += 1
313
+ continue
314
+
315
+ elif self.is_Add:
316
+ # make i*e look like Add
317
+ c, e = expr.as_coeff_Mul()
318
+ if abs(c) > 1:
319
+ from .add import Add
320
+ if c > 0:
321
+ expr = Add(*[e, (c - 1)*e], evaluate=False)
322
+ else:
323
+ expr = Add(*[-e, (c + 1)*e], evaluate=False)
324
+ i += 1
325
+ continue
326
+
327
+ # try collection on non-Wild symbols
328
+ from sympy.simplify.radsimp import collect
329
+ was = expr
330
+ did = set()
331
+ for w in reversed(wild_part):
332
+ c, w = w.as_coeff_mul(Wild)
333
+ free = c.free_symbols - did
334
+ if free:
335
+ did.update(free)
336
+ expr = collect(expr, free)
337
+ if expr != was:
338
+ i += 0
339
+ continue
340
+
341
+ break # if we didn't continue, there is nothing more to do
342
+
343
+ return
344
+
345
+ def _has_matcher(self):
346
+ """Helper for .has() that checks for containment of
347
+ subexpressions within an expr by using sets of args
348
+ of similar nodes, e.g. x + 1 in x + y + 1 checks
349
+ to see that {x, 1} & {x, y, 1} == {x, 1}
350
+ """
351
+ def _ncsplit(expr):
352
+ # this is not the same as args_cnc because here
353
+ # we don't assume expr is a Mul -- hence deal with args --
354
+ # and always return a set.
355
+ cpart, ncpart = sift(expr.args,
356
+ lambda arg: arg.is_commutative is True, binary=True)
357
+ return set(cpart), ncpart
358
+
359
+ c, nc = _ncsplit(self)
360
+ cls = self.__class__
361
+
362
+ def is_in(expr):
363
+ if isinstance(expr, cls):
364
+ if expr == self:
365
+ return True
366
+ _c, _nc = _ncsplit(expr)
367
+ if (c & _c) == c:
368
+ if not nc:
369
+ return True
370
+ elif len(nc) <= len(_nc):
371
+ for i in range(len(_nc) - len(nc) + 1):
372
+ if _nc[i:i + len(nc)] == nc:
373
+ return True
374
+ return False
375
+ return is_in
376
+
377
+ def _eval_evalf(self, prec):
378
+ """
379
+ Evaluate the parts of self that are numbers; if the whole thing
380
+ was a number with no functions it would have been evaluated, but
381
+ it wasn't so we must judiciously extract the numbers and reconstruct
382
+ the object. This is *not* simply replacing numbers with evaluated
383
+ numbers. Numbers should be handled in the largest pure-number
384
+ expression as possible. So the code below separates ``self`` into
385
+ number and non-number parts and evaluates the number parts and
386
+ walks the args of the non-number part recursively (doing the same
387
+ thing).
388
+ """
389
+ from .add import Add
390
+ from .mul import Mul
391
+ from .symbol import Symbol
392
+ from .function import AppliedUndef
393
+ if isinstance(self, (Mul, Add)):
394
+ x, tail = self.as_independent(Symbol, AppliedUndef)
395
+ # if x is an AssocOp Function then the _evalf below will
396
+ # call _eval_evalf (here) so we must break the recursion
397
+ if not (tail is self.identity or
398
+ isinstance(x, AssocOp) and x.is_Function or
399
+ x is self.identity and isinstance(tail, AssocOp)):
400
+ # here, we have a number so we just call to _evalf with prec;
401
+ # prec is not the same as n, it is the binary precision so
402
+ # that's why we don't call to evalf.
403
+ x = x._evalf(prec) if x is not self.identity else self.identity
404
+ args = []
405
+ tail_args = tuple(self.func.make_args(tail))
406
+ for a in tail_args:
407
+ # here we call to _eval_evalf since we don't know what we
408
+ # are dealing with and all other _eval_evalf routines should
409
+ # be doing the same thing (i.e. taking binary prec and
410
+ # finding the evalf-able args)
411
+ newa = a._eval_evalf(prec)
412
+ if newa is None:
413
+ args.append(a)
414
+ else:
415
+ args.append(newa)
416
+ return self.func(x, *args)
417
+
418
+ # this is the same as above, but there were no pure-number args to
419
+ # deal with
420
+ args = []
421
+ for a in self.args:
422
+ newa = a._eval_evalf(prec)
423
+ if newa is None:
424
+ args.append(a)
425
+ else:
426
+ args.append(newa)
427
+ return self.func(*args)
428
+
429
+ @classmethod
430
+ def make_args(cls, expr):
431
+ """
432
+ Return a sequence of elements `args` such that cls(*args) == expr
433
+
434
+ Examples
435
+ ========
436
+
437
+ >>> from sympy import Symbol, Mul, Add
438
+ >>> x, y = map(Symbol, 'xy')
439
+
440
+ >>> Mul.make_args(x*y)
441
+ (x, y)
442
+ >>> Add.make_args(x*y)
443
+ (x*y,)
444
+ >>> set(Add.make_args(x*y + y)) == set([y, x*y])
445
+ True
446
+
447
+ """
448
+ if isinstance(expr, cls):
449
+ return expr.args
450
+ else:
451
+ return (sympify(expr),)
452
+
453
+ def doit(self, **hints):
454
+ if hints.get('deep', True):
455
+ terms = [term.doit(**hints) for term in self.args]
456
+ else:
457
+ terms = self.args
458
+ return self.func(*terms, evaluate=True)
459
+
460
+ class ShortCircuit(Exception):
461
+ pass
462
+
463
+
464
+ class LatticeOp(AssocOp):
465
+ """
466
+ Join/meet operations of an algebraic lattice[1].
467
+
468
+ Explanation
469
+ ===========
470
+
471
+ These binary operations are associative (op(op(a, b), c) = op(a, op(b, c))),
472
+ commutative (op(a, b) = op(b, a)) and idempotent (op(a, a) = op(a) = a).
473
+ Common examples are AND, OR, Union, Intersection, max or min. They have an
474
+ identity element (op(identity, a) = a) and an absorbing element
475
+ conventionally called zero (op(zero, a) = zero).
476
+
477
+ This is an abstract base class, concrete derived classes must declare
478
+ attributes zero and identity. All defining properties are then respected.
479
+
480
+ Examples
481
+ ========
482
+
483
+ >>> from sympy import Integer
484
+ >>> from sympy.core.operations import LatticeOp
485
+ >>> class my_join(LatticeOp):
486
+ ... zero = Integer(0)
487
+ ... identity = Integer(1)
488
+ >>> my_join(2, 3) == my_join(3, 2)
489
+ True
490
+ >>> my_join(2, my_join(3, 4)) == my_join(2, 3, 4)
491
+ True
492
+ >>> my_join(0, 1, 4, 2, 3, 4)
493
+ 0
494
+ >>> my_join(1, 2)
495
+ 2
496
+
497
+ References
498
+ ==========
499
+
500
+ .. [1] https://en.wikipedia.org/wiki/Lattice_%28order%29
501
+ """
502
+
503
+ is_commutative = True
504
+
505
+ def __new__(cls, *args, **options):
506
+ args = (_sympify_(arg) for arg in args)
507
+
508
+ try:
509
+ # /!\ args is a generator and _new_args_filter
510
+ # must be careful to handle as such; this
511
+ # is done so short-circuiting can be done
512
+ # without having to sympify all values
513
+ _args = frozenset(cls._new_args_filter(args))
514
+ except ShortCircuit:
515
+ return sympify(cls.zero)
516
+ if not _args:
517
+ return sympify(cls.identity)
518
+ elif len(_args) == 1:
519
+ return set(_args).pop()
520
+ else:
521
+ # XXX in almost every other case for __new__, *_args is
522
+ # passed along, but the expectation here is for _args
523
+ obj = super(AssocOp, cls).__new__(cls, *ordered(_args))
524
+ obj._argset = _args
525
+ return obj
526
+
527
+ @classmethod
528
+ def _new_args_filter(cls, arg_sequence, call_cls=None):
529
+ """Generator filtering args"""
530
+ ncls = call_cls or cls
531
+ for arg in arg_sequence:
532
+ if arg == ncls.zero:
533
+ raise ShortCircuit(arg)
534
+ elif arg == ncls.identity:
535
+ continue
536
+ elif arg.func == ncls:
537
+ yield from arg.args
538
+ else:
539
+ yield arg
540
+
541
+ @classmethod
542
+ def make_args(cls, expr):
543
+ """
544
+ Return a set of args such that cls(*arg_set) == expr.
545
+ """
546
+ if isinstance(expr, cls):
547
+ return expr._argset
548
+ else:
549
+ return frozenset([sympify(expr)])
550
+
551
+ @staticmethod
552
+ def _compare_pretty(a, b):
553
+ return (str(a) > str(b)) - (str(a) < str(b))
554
+
555
+
556
+ class AssocOpDispatcher:
557
+ """
558
+ Handler dispatcher for associative operators
559
+
560
+ .. notes::
561
+ This approach is experimental, and can be replaced or deleted in the future.
562
+ See https://github.com/sympy/sympy/pull/19463.
563
+
564
+ Explanation
565
+ ===========
566
+
567
+ If arguments of different types are passed, the classes which handle the operation for each type
568
+ are collected. Then, a class which performs the operation is selected by recursive binary dispatching.
569
+ Dispatching relation can be registered by ``register_handlerclass`` method.
570
+
571
+ Priority registration is unordered. You cannot make ``A*B`` and ``B*A`` refer to
572
+ different handler classes. All logic dealing with the order of arguments must be implemented
573
+ in the handler class.
574
+
575
+ Examples
576
+ ========
577
+
578
+ >>> from sympy import Add, Expr, Symbol
579
+ >>> from sympy.core.add import add
580
+
581
+ >>> class NewExpr(Expr):
582
+ ... @property
583
+ ... def _add_handler(self):
584
+ ... return NewAdd
585
+ >>> class NewAdd(NewExpr, Add):
586
+ ... pass
587
+ >>> add.register_handlerclass((Add, NewAdd), NewAdd)
588
+
589
+ >>> a, b = Symbol('a'), NewExpr()
590
+ >>> add(a, b) == NewAdd(a, b)
591
+ True
592
+
593
+ """
594
+ def __init__(self, name, doc=None):
595
+ self.name = name
596
+ self.doc = doc
597
+ self.handlerattr = "_%s_handler" % name
598
+ self._handlergetter = attrgetter(self.handlerattr)
599
+ self._dispatcher = Dispatcher(name)
600
+
601
+ def __repr__(self):
602
+ return "<dispatched %s>" % self.name
603
+
604
+ def register_handlerclass(self, classes, typ, on_ambiguity=ambiguity_register_error_ignore_dup):
605
+ """
606
+ Register the handler class for two classes, in both straight and reversed order.
607
+
608
+ Paramteters
609
+ ===========
610
+
611
+ classes : tuple of two types
612
+ Classes who are compared with each other.
613
+
614
+ typ:
615
+ Class which is registered to represent *cls1* and *cls2*.
616
+ Handler method of *self* must be implemented in this class.
617
+ """
618
+ if not len(classes) == 2:
619
+ raise RuntimeError(
620
+ "Only binary dispatch is supported, but got %s types: <%s>." % (
621
+ len(classes), str_signature(classes)
622
+ ))
623
+ if len(set(classes)) == 1:
624
+ raise RuntimeError(
625
+ "Duplicate types <%s> cannot be dispatched." % str_signature(classes)
626
+ )
627
+ self._dispatcher.add(tuple(classes), typ, on_ambiguity=on_ambiguity)
628
+ self._dispatcher.add(tuple(reversed(classes)), typ, on_ambiguity=on_ambiguity)
629
+
630
+ @cacheit
631
+ def __call__(self, *args, _sympify=True, **kwargs):
632
+ """
633
+ Parameters
634
+ ==========
635
+
636
+ *args :
637
+ Arguments which are operated
638
+ """
639
+ if _sympify:
640
+ args = tuple(map(_sympify_, args))
641
+ handlers = frozenset(map(self._handlergetter, args))
642
+
643
+ # no need to sympify again
644
+ return self.dispatch(handlers)(*args, _sympify=False, **kwargs)
645
+
646
+ @cacheit
647
+ def dispatch(self, handlers):
648
+ """
649
+ Select the handler class, and return its handler method.
650
+ """
651
+
652
+ # Quick exit for the case where all handlers are same
653
+ if len(handlers) == 1:
654
+ h, = handlers
655
+ if not isinstance(h, type):
656
+ raise RuntimeError("Handler {!r} is not a type.".format(h))
657
+ return h
658
+
659
+ # Recursively select with registered binary priority
660
+ for i, typ in enumerate(handlers):
661
+
662
+ if not isinstance(typ, type):
663
+ raise RuntimeError("Handler {!r} is not a type.".format(typ))
664
+
665
+ if i == 0:
666
+ handler = typ
667
+ else:
668
+ prev_handler = handler
669
+ handler = self._dispatcher.dispatch(prev_handler, typ)
670
+
671
+ if not isinstance(handler, type):
672
+ raise RuntimeError(
673
+ "Dispatcher for {!r} and {!r} must return a type, but got {!r}".format(
674
+ prev_handler, typ, handler
675
+ ))
676
+
677
+ # return handler class
678
+ return handler
679
+
680
+ @property
681
+ def __doc__(self):
682
+ docs = [
683
+ "Multiply dispatched associative operator: %s" % self.name,
684
+ "Note that support for this is experimental, see the docs for :class:`AssocOpDispatcher` for details"
685
+ ]
686
+
687
+ if self.doc:
688
+ docs.append(self.doc)
689
+
690
+ s = "Registered handler classes\n"
691
+ s += '=' * len(s)
692
+ docs.append(s)
693
+
694
+ amb_sigs = []
695
+
696
+ typ_sigs = defaultdict(list)
697
+ for sigs in self._dispatcher.ordering[::-1]:
698
+ key = self._dispatcher.funcs[sigs]
699
+ typ_sigs[key].append(sigs)
700
+
701
+ for typ, sigs in typ_sigs.items():
702
+
703
+ sigs_str = ', '.join('<%s>' % str_signature(sig) for sig in sigs)
704
+
705
+ if isinstance(typ, RaiseNotImplementedError):
706
+ amb_sigs.append(sigs_str)
707
+ continue
708
+
709
+ s = 'Inputs: %s\n' % sigs_str
710
+ s += '-' * len(s) + '\n'
711
+ s += typ.__name__
712
+ docs.append(s)
713
+
714
+ if amb_sigs:
715
+ s = "Ambiguous handler classes\n"
716
+ s += '=' * len(s)
717
+ docs.append(s)
718
+
719
+ s = '\n'.join(amb_sigs)
720
+ docs.append(s)
721
+
722
+ return '\n\n'.join(docs)
env-llmeval/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
env-llmeval/lib/python3.10/site-packages/sympy/core/random.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ When you need to use random numbers in SymPy library code, import from here
3
+ so there is only one generator working for SymPy. Imports from here should
4
+ behave the same as if they were being imported from Python's random module.
5
+ But only the routines currently used in SymPy are included here. To use others
6
+ import ``rng`` and access the method directly. For example, to capture the
7
+ current state of the generator use ``rng.getstate()``.
8
+
9
+ There is intentionally no Random to import from here. If you want
10
+ to control the state of the generator, import ``seed`` and call it
11
+ with or without an argument to set the state.
12
+
13
+ Examples
14
+ ========
15
+
16
+ >>> from sympy.core.random import random, seed
17
+ >>> assert random() < 1
18
+ >>> seed(1); a = random()
19
+ >>> b = random()
20
+ >>> seed(1); c = random()
21
+ >>> assert a == c
22
+ >>> assert a != b # remote possibility this will fail
23
+
24
+ """
25
+ from sympy.utilities.iterables import is_sequence
26
+ from sympy.utilities.misc import as_int
27
+
28
+ import random as _random
29
+ rng = _random.Random()
30
+
31
+ choice = rng.choice
32
+ random = rng.random
33
+ randint = rng.randint
34
+ randrange = rng.randrange
35
+ sample = rng.sample
36
+ # seed = rng.seed
37
+ shuffle = rng.shuffle
38
+ uniform = rng.uniform
39
+
40
+ _assumptions_rng = _random.Random()
41
+ _assumptions_shuffle = _assumptions_rng.shuffle
42
+
43
+
44
+ def seed(a=None, version=2):
45
+ rng.seed(a=a, version=version)
46
+ _assumptions_rng.seed(a=a, version=version)
47
+
48
+
49
+ def random_complex_number(a=2, b=-1, c=3, d=1, rational=False, tolerance=None):
50
+ """
51
+ Return a random complex number.
52
+
53
+ To reduce chance of hitting branch cuts or anything, we guarantee
54
+ b <= Im z <= d, a <= Re z <= c
55
+
56
+ When rational is True, a rational approximation to a random number
57
+ is obtained within specified tolerance, if any.
58
+ """
59
+ from sympy.core.numbers import I
60
+ from sympy.simplify.simplify import nsimplify
61
+ A, B = uniform(a, c), uniform(b, d)
62
+ if not rational:
63
+ return A + I*B
64
+ return (nsimplify(A, rational=True, tolerance=tolerance) +
65
+ I*nsimplify(B, rational=True, tolerance=tolerance))
66
+
67
+
68
+ def verify_numerically(f, g, z=None, tol=1.0e-6, a=2, b=-1, c=3, d=1):
69
+ """
70
+ Test numerically that f and g agree when evaluated in the argument z.
71
+
72
+ If z is None, all symbols will be tested. This routine does not test
73
+ whether there are Floats present with precision higher than 15 digits
74
+ so if there are, your results may not be what you expect due to round-
75
+ off errors.
76
+
77
+ Examples
78
+ ========
79
+
80
+ >>> from sympy import sin, cos
81
+ >>> from sympy.abc import x
82
+ >>> from sympy.core.random import verify_numerically as tn
83
+ >>> tn(sin(x)**2 + cos(x)**2, 1, x)
84
+ True
85
+ """
86
+ from sympy.core.symbol import Symbol
87
+ from sympy.core.sympify import sympify
88
+ from sympy.core.numbers import comp
89
+ f, g = (sympify(i) for i in (f, g))
90
+ if z is None:
91
+ z = f.free_symbols | g.free_symbols
92
+ elif isinstance(z, Symbol):
93
+ z = [z]
94
+ reps = list(zip(z, [random_complex_number(a, b, c, d) for _ in z]))
95
+ z1 = f.subs(reps).n()
96
+ z2 = g.subs(reps).n()
97
+ return comp(z1, z2, tol)
98
+
99
+
100
+ def test_derivative_numerically(f, z, tol=1.0e-6, a=2, b=-1, c=3, d=1):
101
+ """
102
+ Test numerically that the symbolically computed derivative of f
103
+ with respect to z is correct.
104
+
105
+ This routine does not test whether there are Floats present with
106
+ precision higher than 15 digits so if there are, your results may
107
+ not be what you expect due to round-off errors.
108
+
109
+ Examples
110
+ ========
111
+
112
+ >>> from sympy import sin
113
+ >>> from sympy.abc import x
114
+ >>> from sympy.core.random import test_derivative_numerically as td
115
+ >>> td(sin(x), x)
116
+ True
117
+ """
118
+ from sympy.core.numbers import comp
119
+ from sympy.core.function import Derivative
120
+ z0 = random_complex_number(a, b, c, d)
121
+ f1 = f.diff(z).subs(z, z0)
122
+ f2 = Derivative(f, z).doit_numerically(z0)
123
+ return comp(f1.n(), f2.n(), tol)
124
+
125
+
126
+ def _randrange(seed=None):
127
+ """Return a randrange generator.
128
+
129
+ ``seed`` can be
130
+
131
+ * None - return randomly seeded generator
132
+ * int - return a generator seeded with the int
133
+ * list - the values to be returned will be taken from the list
134
+ in the order given; the provided list is not modified.
135
+
136
+ Examples
137
+ ========
138
+
139
+ >>> from sympy.core.random import _randrange
140
+ >>> rr = _randrange()
141
+ >>> rr(1000) # doctest: +SKIP
142
+ 999
143
+ >>> rr = _randrange(3)
144
+ >>> rr(1000) # doctest: +SKIP
145
+ 238
146
+ >>> rr = _randrange([0, 5, 1, 3, 4])
147
+ >>> rr(3), rr(3)
148
+ (0, 1)
149
+ """
150
+ if seed is None:
151
+ return randrange
152
+ elif isinstance(seed, int):
153
+ rng.seed(seed)
154
+ return randrange
155
+ elif is_sequence(seed):
156
+ seed = list(seed) # make a copy
157
+ seed.reverse()
158
+
159
+ def give(a, b=None, seq=seed):
160
+ if b is None:
161
+ a, b = 0, a
162
+ a, b = as_int(a), as_int(b)
163
+ w = b - a
164
+ if w < 1:
165
+ raise ValueError('_randrange got empty range')
166
+ try:
167
+ x = seq.pop()
168
+ except IndexError:
169
+ raise ValueError('_randrange sequence was too short')
170
+ if a <= x < b:
171
+ return x
172
+ else:
173
+ return give(a, b, seq)
174
+ return give
175
+ else:
176
+ raise ValueError('_randrange got an unexpected seed')
177
+
178
+
179
+ def _randint(seed=None):
180
+ """Return a randint generator.
181
+
182
+ ``seed`` can be
183
+
184
+ * None - return randomly seeded generator
185
+ * int - return a generator seeded with the int
186
+ * list - the values to be returned will be taken from the list
187
+ in the order given; the provided list is not modified.
188
+
189
+ Examples
190
+ ========
191
+
192
+ >>> from sympy.core.random import _randint
193
+ >>> ri = _randint()
194
+ >>> ri(1, 1000) # doctest: +SKIP
195
+ 999
196
+ >>> ri = _randint(3)
197
+ >>> ri(1, 1000) # doctest: +SKIP
198
+ 238
199
+ >>> ri = _randint([0, 5, 1, 2, 4])
200
+ >>> ri(1, 3), ri(1, 3)
201
+ (1, 2)
202
+ """
203
+ if seed is None:
204
+ return randint
205
+ elif isinstance(seed, int):
206
+ rng.seed(seed)
207
+ return randint
208
+ elif is_sequence(seed):
209
+ seed = list(seed) # make a copy
210
+ seed.reverse()
211
+
212
+ def give(a, b, seq=seed):
213
+ a, b = as_int(a), as_int(b)
214
+ w = b - a
215
+ if w < 0:
216
+ raise ValueError('_randint got empty range')
217
+ try:
218
+ x = seq.pop()
219
+ except IndexError:
220
+ raise ValueError('_randint sequence was too short')
221
+ if a <= x <= b:
222
+ return x
223
+ else:
224
+ return give(a, b, seq)
225
+ return give
226
+ else:
227
+ raise ValueError('_randint got an unexpected seed')
env-llmeval/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
env-llmeval/lib/python3.10/site-packages/sympy/core/singleton.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Singleton mechanism"""
2
+
3
+
4
+ from .core import Registry
5
+ from .sympify import sympify
6
+
7
+
8
+ class SingletonRegistry(Registry):
9
+ """
10
+ The registry for the singleton classes (accessible as ``S``).
11
+
12
+ Explanation
13
+ ===========
14
+
15
+ This class serves as two separate things.
16
+
17
+ The first thing it is is the ``SingletonRegistry``. Several classes in
18
+ SymPy appear so often that they are singletonized, that is, using some
19
+ metaprogramming they are made so that they can only be instantiated once
20
+ (see the :class:`sympy.core.singleton.Singleton` class for details). For
21
+ instance, every time you create ``Integer(0)``, this will return the same
22
+ instance, :class:`sympy.core.numbers.Zero`. All singleton instances are
23
+ attributes of the ``S`` object, so ``Integer(0)`` can also be accessed as
24
+ ``S.Zero``.
25
+
26
+ Singletonization offers two advantages: it saves memory, and it allows
27
+ fast comparison. It saves memory because no matter how many times the
28
+ singletonized objects appear in expressions in memory, they all point to
29
+ the same single instance in memory. The fast comparison comes from the
30
+ fact that you can use ``is`` to compare exact instances in Python
31
+ (usually, you need to use ``==`` to compare things). ``is`` compares
32
+ objects by memory address, and is very fast.
33
+
34
+ Examples
35
+ ========
36
+
37
+ >>> from sympy import S, Integer
38
+ >>> a = Integer(0)
39
+ >>> a is S.Zero
40
+ True
41
+
42
+ For the most part, the fact that certain objects are singletonized is an
43
+ implementation detail that users should not need to worry about. In SymPy
44
+ library code, ``is`` comparison is often used for performance purposes
45
+ The primary advantage of ``S`` for end users is the convenient access to
46
+ certain instances that are otherwise difficult to type, like ``S.Half``
47
+ (instead of ``Rational(1, 2)``).
48
+
49
+ When using ``is`` comparison, make sure the argument is sympified. For
50
+ instance,
51
+
52
+ >>> x = 0
53
+ >>> x is S.Zero
54
+ False
55
+
56
+ This problem is not an issue when using ``==``, which is recommended for
57
+ most use-cases:
58
+
59
+ >>> 0 == S.Zero
60
+ True
61
+
62
+ The second thing ``S`` is is a shortcut for
63
+ :func:`sympy.core.sympify.sympify`. :func:`sympy.core.sympify.sympify` is
64
+ the function that converts Python objects such as ``int(1)`` into SymPy
65
+ objects such as ``Integer(1)``. It also converts the string form of an
66
+ expression into a SymPy expression, like ``sympify("x**2")`` ->
67
+ ``Symbol("x")**2``. ``S(1)`` is the same thing as ``sympify(1)``
68
+ (basically, ``S.__call__`` has been defined to call ``sympify``).
69
+
70
+ This is for convenience, since ``S`` is a single letter. It's mostly
71
+ useful for defining rational numbers. Consider an expression like ``x +
72
+ 1/2``. If you enter this directly in Python, it will evaluate the ``1/2``
73
+ and give ``0.5``, because both arguments are ints (see also
74
+ :ref:`tutorial-gotchas-final-notes`). However, in SymPy, you usually want
75
+ the quotient of two integers to give an exact rational number. The way
76
+ Python's evaluation works, at least one side of an operator needs to be a
77
+ SymPy object for the SymPy evaluation to take over. You could write this
78
+ as ``x + Rational(1, 2)``, but this is a lot more typing. A shorter
79
+ version is ``x + S(1)/2``. Since ``S(1)`` returns ``Integer(1)``, the
80
+ division will return a ``Rational`` type, since it will call
81
+ ``Integer.__truediv__``, which knows how to return a ``Rational``.
82
+
83
+ """
84
+ __slots__ = ()
85
+
86
+ # Also allow things like S(5)
87
+ __call__ = staticmethod(sympify)
88
+
89
+ def __init__(self):
90
+ self._classes_to_install = {}
91
+ # Dict of classes that have been registered, but that have not have been
92
+ # installed as an attribute of this SingletonRegistry.
93
+ # Installation automatically happens at the first attempt to access the
94
+ # attribute.
95
+ # The purpose of this is to allow registration during class
96
+ # initialization during import, but not trigger object creation until
97
+ # actual use (which should not happen until after all imports are
98
+ # finished).
99
+
100
+ def register(self, cls):
101
+ # Make sure a duplicate class overwrites the old one
102
+ if hasattr(self, cls.__name__):
103
+ delattr(self, cls.__name__)
104
+ self._classes_to_install[cls.__name__] = cls
105
+
106
+ def __getattr__(self, name):
107
+ """Python calls __getattr__ if no attribute of that name was installed
108
+ yet.
109
+
110
+ Explanation
111
+ ===========
112
+
113
+ This __getattr__ checks whether a class with the requested name was
114
+ already registered but not installed; if no, raises an AttributeError.
115
+ Otherwise, retrieves the class, calculates its singleton value, installs
116
+ it as an attribute of the given name, and unregisters the class."""
117
+ if name not in self._classes_to_install:
118
+ raise AttributeError(
119
+ "Attribute '%s' was not installed on SymPy registry %s" % (
120
+ name, self))
121
+ class_to_install = self._classes_to_install[name]
122
+ value_to_install = class_to_install()
123
+ self.__setattr__(name, value_to_install)
124
+ del self._classes_to_install[name]
125
+ return value_to_install
126
+
127
+ def __repr__(self):
128
+ return "S"
129
+
130
+ S = SingletonRegistry()
131
+
132
+
133
+ class Singleton(type):
134
+ """
135
+ Metaclass for singleton classes.
136
+
137
+ Explanation
138
+ ===========
139
+
140
+ A singleton class has only one instance which is returned every time the
141
+ class is instantiated. Additionally, this instance can be accessed through
142
+ the global registry object ``S`` as ``S.<class_name>``.
143
+
144
+ Examples
145
+ ========
146
+
147
+ >>> from sympy import S, Basic
148
+ >>> from sympy.core.singleton import Singleton
149
+ >>> class MySingleton(Basic, metaclass=Singleton):
150
+ ... pass
151
+ >>> Basic() is Basic()
152
+ False
153
+ >>> MySingleton() is MySingleton()
154
+ True
155
+ >>> S.MySingleton is MySingleton()
156
+ True
157
+
158
+ Notes
159
+ =====
160
+
161
+ Instance creation is delayed until the first time the value is accessed.
162
+ (SymPy versions before 1.0 would create the instance during class
163
+ creation time, which would be prone to import cycles.)
164
+ """
165
+ def __init__(cls, *args, **kwargs):
166
+ cls._instance = obj = Basic.__new__(cls)
167
+ cls.__new__ = lambda cls: obj
168
+ cls.__getnewargs__ = lambda obj: ()
169
+ cls.__getstate__ = lambda obj: None
170
+ S.register(cls)
171
+
172
+
173
+ # Delayed to avoid cyclic import
174
+ from .basic import Basic
env-llmeval/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
env-llmeval/lib/python3.10/site-packages/sympy/core/sympify.py ADDED
@@ -0,0 +1,634 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sympify -- convert objects SymPy internal format"""
2
+
3
+ from __future__ import annotations
4
+ from typing import Any, Callable
5
+
6
+ from inspect import getmro
7
+ import string
8
+ from sympy.core.random import choice
9
+
10
+ from .parameters import global_parameters
11
+
12
+ from sympy.utilities.exceptions import sympy_deprecation_warning
13
+ from sympy.utilities.iterables import iterable
14
+
15
+
16
+ class SympifyError(ValueError):
17
+ def __init__(self, expr, base_exc=None):
18
+ self.expr = expr
19
+ self.base_exc = base_exc
20
+
21
+ def __str__(self):
22
+ if self.base_exc is None:
23
+ return "SympifyError: %r" % (self.expr,)
24
+
25
+ return ("Sympify of expression '%s' failed, because of exception being "
26
+ "raised:\n%s: %s" % (self.expr, self.base_exc.__class__.__name__,
27
+ str(self.base_exc)))
28
+
29
+
30
+ converter: dict[type[Any], Callable[[Any], Basic]] = {}
31
+
32
+ #holds the conversions defined in SymPy itself, i.e. non-user defined conversions
33
+ _sympy_converter: dict[type[Any], Callable[[Any], Basic]] = {}
34
+
35
+ #alias for clearer use in the library
36
+ _external_converter = converter
37
+
38
+ class CantSympify:
39
+ """
40
+ Mix in this trait to a class to disallow sympification of its instances.
41
+
42
+ Examples
43
+ ========
44
+
45
+ >>> from sympy import sympify
46
+ >>> from sympy.core.sympify import CantSympify
47
+
48
+ >>> class Something(dict):
49
+ ... pass
50
+ ...
51
+ >>> sympify(Something())
52
+ {}
53
+
54
+ >>> class Something(dict, CantSympify):
55
+ ... pass
56
+ ...
57
+ >>> sympify(Something())
58
+ Traceback (most recent call last):
59
+ ...
60
+ SympifyError: SympifyError: {}
61
+
62
+ """
63
+
64
+ __slots__ = ()
65
+
66
+
67
+ def _is_numpy_instance(a):
68
+ """
69
+ Checks if an object is an instance of a type from the numpy module.
70
+ """
71
+ # This check avoids unnecessarily importing NumPy. We check the whole
72
+ # __mro__ in case any base type is a numpy type.
73
+ return any(type_.__module__ == 'numpy'
74
+ for type_ in type(a).__mro__)
75
+
76
+
77
+ def _convert_numpy_types(a, **sympify_args):
78
+ """
79
+ Converts a numpy datatype input to an appropriate SymPy type.
80
+ """
81
+ import numpy as np
82
+ if not isinstance(a, np.floating):
83
+ if np.iscomplex(a):
84
+ return _sympy_converter[complex](a.item())
85
+ else:
86
+ return sympify(a.item(), **sympify_args)
87
+ else:
88
+ try:
89
+ from .numbers import Float
90
+ prec = np.finfo(a).nmant + 1
91
+ # E.g. double precision means prec=53 but nmant=52
92
+ # Leading bit of mantissa is always 1, so is not stored
93
+ a = str(list(np.reshape(np.asarray(a),
94
+ (1, np.size(a)))[0]))[1:-1]
95
+ return Float(a, precision=prec)
96
+ except NotImplementedError:
97
+ raise SympifyError('Translation for numpy float : %s '
98
+ 'is not implemented' % a)
99
+
100
+
101
+ def sympify(a, locals=None, convert_xor=True, strict=False, rational=False,
102
+ evaluate=None):
103
+ """
104
+ Converts an arbitrary expression to a type that can be used inside SymPy.
105
+
106
+ Explanation
107
+ ===========
108
+
109
+ It will convert Python ints into instances of :class:`~.Integer`, floats
110
+ into instances of :class:`~.Float`, etc. It is also able to coerce
111
+ symbolic expressions which inherit from :class:`~.Basic`. This can be
112
+ useful in cooperation with SAGE.
113
+
114
+ .. warning::
115
+ Note that this function uses ``eval``, and thus shouldn't be used on
116
+ unsanitized input.
117
+
118
+ If the argument is already a type that SymPy understands, it will do
119
+ nothing but return that value. This can be used at the beginning of a
120
+ function to ensure you are working with the correct type.
121
+
122
+ Examples
123
+ ========
124
+
125
+ >>> from sympy import sympify
126
+
127
+ >>> sympify(2).is_integer
128
+ True
129
+ >>> sympify(2).is_real
130
+ True
131
+
132
+ >>> sympify(2.0).is_real
133
+ True
134
+ >>> sympify("2.0").is_real
135
+ True
136
+ >>> sympify("2e-45").is_real
137
+ True
138
+
139
+ If the expression could not be converted, a SympifyError is raised.
140
+
141
+ >>> sympify("x***2")
142
+ Traceback (most recent call last):
143
+ ...
144
+ SympifyError: SympifyError: "could not parse 'x***2'"
145
+
146
+ Locals
147
+ ------
148
+
149
+ The sympification happens with access to everything that is loaded
150
+ by ``from sympy import *``; anything used in a string that is not
151
+ defined by that import will be converted to a symbol. In the following,
152
+ the ``bitcount`` function is treated as a symbol and the ``O`` is
153
+ interpreted as the :class:`~.Order` object (used with series) and it raises
154
+ an error when used improperly:
155
+
156
+ >>> s = 'bitcount(42)'
157
+ >>> sympify(s)
158
+ bitcount(42)
159
+ >>> sympify("O(x)")
160
+ O(x)
161
+ >>> sympify("O + 1")
162
+ Traceback (most recent call last):
163
+ ...
164
+ TypeError: unbound method...
165
+
166
+ In order to have ``bitcount`` be recognized it can be imported into a
167
+ namespace dictionary and passed as locals:
168
+
169
+ >>> ns = {}
170
+ >>> exec('from sympy.core.evalf import bitcount', ns)
171
+ >>> sympify(s, locals=ns)
172
+ 6
173
+
174
+ In order to have the ``O`` interpreted as a Symbol, identify it as such
175
+ in the namespace dictionary. This can be done in a variety of ways; all
176
+ three of the following are possibilities:
177
+
178
+ >>> from sympy import Symbol
179
+ >>> ns["O"] = Symbol("O") # method 1
180
+ >>> exec('from sympy.abc import O', ns) # method 2
181
+ >>> ns.update(dict(O=Symbol("O"))) # method 3
182
+ >>> sympify("O + 1", locals=ns)
183
+ O + 1
184
+
185
+ If you want *all* single-letter and Greek-letter variables to be symbols
186
+ then you can use the clashing-symbols dictionaries that have been defined
187
+ there as private variables: ``_clash1`` (single-letter variables),
188
+ ``_clash2`` (the multi-letter Greek names) or ``_clash`` (both single and
189
+ multi-letter names that are defined in ``abc``).
190
+
191
+ >>> from sympy.abc import _clash1
192
+ >>> set(_clash1) # if this fails, see issue #23903
193
+ {'E', 'I', 'N', 'O', 'Q', 'S'}
194
+ >>> sympify('I & Q', _clash1)
195
+ I & Q
196
+
197
+ Strict
198
+ ------
199
+
200
+ If the option ``strict`` is set to ``True``, only the types for which an
201
+ explicit conversion has been defined are converted. In the other
202
+ cases, a SympifyError is raised.
203
+
204
+ >>> print(sympify(None))
205
+ None
206
+ >>> sympify(None, strict=True)
207
+ Traceback (most recent call last):
208
+ ...
209
+ SympifyError: SympifyError: None
210
+
211
+ .. deprecated:: 1.6
212
+
213
+ ``sympify(obj)`` automatically falls back to ``str(obj)`` when all
214
+ other conversion methods fail, but this is deprecated. ``strict=True``
215
+ will disable this deprecated behavior. See
216
+ :ref:`deprecated-sympify-string-fallback`.
217
+
218
+ Evaluation
219
+ ----------
220
+
221
+ If the option ``evaluate`` is set to ``False``, then arithmetic and
222
+ operators will be converted into their SymPy equivalents and the
223
+ ``evaluate=False`` option will be added. Nested ``Add`` or ``Mul`` will
224
+ be denested first. This is done via an AST transformation that replaces
225
+ operators with their SymPy equivalents, so if an operand redefines any
226
+ of those operations, the redefined operators will not be used. If
227
+ argument a is not a string, the mathematical expression is evaluated
228
+ before being passed to sympify, so adding ``evaluate=False`` will still
229
+ return the evaluated result of expression.
230
+
231
+ >>> sympify('2**2 / 3 + 5')
232
+ 19/3
233
+ >>> sympify('2**2 / 3 + 5', evaluate=False)
234
+ 2**2/3 + 5
235
+ >>> sympify('4/2+7', evaluate=True)
236
+ 9
237
+ >>> sympify('4/2+7', evaluate=False)
238
+ 4/2 + 7
239
+ >>> sympify(4/2+7, evaluate=False)
240
+ 9.00000000000000
241
+
242
+ Extending
243
+ ---------
244
+
245
+ To extend ``sympify`` to convert custom objects (not derived from ``Basic``),
246
+ just define a ``_sympy_`` method to your class. You can do that even to
247
+ classes that you do not own by subclassing or adding the method at runtime.
248
+
249
+ >>> from sympy import Matrix
250
+ >>> class MyList1(object):
251
+ ... def __iter__(self):
252
+ ... yield 1
253
+ ... yield 2
254
+ ... return
255
+ ... def __getitem__(self, i): return list(self)[i]
256
+ ... def _sympy_(self): return Matrix(self)
257
+ >>> sympify(MyList1())
258
+ Matrix([
259
+ [1],
260
+ [2]])
261
+
262
+ If you do not have control over the class definition you could also use the
263
+ ``converter`` global dictionary. The key is the class and the value is a
264
+ function that takes a single argument and returns the desired SymPy
265
+ object, e.g. ``converter[MyList] = lambda x: Matrix(x)``.
266
+
267
+ >>> class MyList2(object): # XXX Do not do this if you control the class!
268
+ ... def __iter__(self): # Use _sympy_!
269
+ ... yield 1
270
+ ... yield 2
271
+ ... return
272
+ ... def __getitem__(self, i): return list(self)[i]
273
+ >>> from sympy.core.sympify import converter
274
+ >>> converter[MyList2] = lambda x: Matrix(x)
275
+ >>> sympify(MyList2())
276
+ Matrix([
277
+ [1],
278
+ [2]])
279
+
280
+ Notes
281
+ =====
282
+
283
+ The keywords ``rational`` and ``convert_xor`` are only used
284
+ when the input is a string.
285
+
286
+ convert_xor
287
+ -----------
288
+
289
+ >>> sympify('x^y',convert_xor=True)
290
+ x**y
291
+ >>> sympify('x^y',convert_xor=False)
292
+ x ^ y
293
+
294
+ rational
295
+ --------
296
+
297
+ >>> sympify('0.1',rational=False)
298
+ 0.1
299
+ >>> sympify('0.1',rational=True)
300
+ 1/10
301
+
302
+ Sometimes autosimplification during sympification results in expressions
303
+ that are very different in structure than what was entered. Until such
304
+ autosimplification is no longer done, the ``kernS`` function might be of
305
+ some use. In the example below you can see how an expression reduces to
306
+ $-1$ by autosimplification, but does not do so when ``kernS`` is used.
307
+
308
+ >>> from sympy.core.sympify import kernS
309
+ >>> from sympy.abc import x
310
+ >>> -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1
311
+ -1
312
+ >>> s = '-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1'
313
+ >>> sympify(s)
314
+ -1
315
+ >>> kernS(s)
316
+ -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1
317
+
318
+ Parameters
319
+ ==========
320
+
321
+ a :
322
+ - any object defined in SymPy
323
+ - standard numeric Python types: ``int``, ``long``, ``float``, ``Decimal``
324
+ - strings (like ``"0.09"``, ``"2e-19"`` or ``'sin(x)'``)
325
+ - booleans, including ``None`` (will leave ``None`` unchanged)
326
+ - dicts, lists, sets or tuples containing any of the above
327
+
328
+ convert_xor : bool, optional
329
+ If true, treats ``^`` as exponentiation.
330
+ If False, treats ``^`` as XOR itself.
331
+ Used only when input is a string.
332
+
333
+ locals : any object defined in SymPy, optional
334
+ In order to have strings be recognized it can be imported
335
+ into a namespace dictionary and passed as locals.
336
+
337
+ strict : bool, optional
338
+ If the option strict is set to ``True``, only the types for which
339
+ an explicit conversion has been defined are converted. In the
340
+ other cases, a SympifyError is raised.
341
+
342
+ rational : bool, optional
343
+ If ``True``, converts floats into :class:`~.Rational`.
344
+ If ``False``, it lets floats remain as it is.
345
+ Used only when input is a string.
346
+
347
+ evaluate : bool, optional
348
+ If False, then arithmetic and operators will be converted into
349
+ their SymPy equivalents. If True the expression will be evaluated
350
+ and the result will be returned.
351
+
352
+ """
353
+ # XXX: If a is a Basic subclass rather than instance (e.g. sin rather than
354
+ # sin(x)) then a.__sympy__ will be the property. Only on the instance will
355
+ # a.__sympy__ give the *value* of the property (True). Since sympify(sin)
356
+ # was used for a long time we allow it to pass. However if strict=True as
357
+ # is the case in internal calls to _sympify then we only allow
358
+ # is_sympy=True.
359
+ #
360
+ # https://github.com/sympy/sympy/issues/20124
361
+ is_sympy = getattr(a, '__sympy__', None)
362
+ if is_sympy is True:
363
+ return a
364
+ elif is_sympy is not None:
365
+ if not strict:
366
+ return a
367
+ else:
368
+ raise SympifyError(a)
369
+
370
+ if isinstance(a, CantSympify):
371
+ raise SympifyError(a)
372
+
373
+ cls = getattr(a, "__class__", None)
374
+
375
+ #Check if there exists a converter for any of the types in the mro
376
+ for superclass in getmro(cls):
377
+ #First check for user defined converters
378
+ conv = _external_converter.get(superclass)
379
+ if conv is None:
380
+ #if none exists, check for SymPy defined converters
381
+ conv = _sympy_converter.get(superclass)
382
+ if conv is not None:
383
+ return conv(a)
384
+
385
+ if cls is type(None):
386
+ if strict:
387
+ raise SympifyError(a)
388
+ else:
389
+ return a
390
+
391
+ if evaluate is None:
392
+ evaluate = global_parameters.evaluate
393
+
394
+ # Support for basic numpy datatypes
395
+ if _is_numpy_instance(a):
396
+ import numpy as np
397
+ if np.isscalar(a):
398
+ return _convert_numpy_types(a, locals=locals,
399
+ convert_xor=convert_xor, strict=strict, rational=rational,
400
+ evaluate=evaluate)
401
+
402
+ _sympy_ = getattr(a, "_sympy_", None)
403
+ if _sympy_ is not None:
404
+ try:
405
+ return a._sympy_()
406
+ # XXX: Catches AttributeError: 'SymPyConverter' object has no
407
+ # attribute 'tuple'
408
+ # This is probably a bug somewhere but for now we catch it here.
409
+ except AttributeError:
410
+ pass
411
+
412
+ if not strict:
413
+ # Put numpy array conversion _before_ float/int, see
414
+ # <https://github.com/sympy/sympy/issues/13924>.
415
+ flat = getattr(a, "flat", None)
416
+ if flat is not None:
417
+ shape = getattr(a, "shape", None)
418
+ if shape is not None:
419
+ from sympy.tensor.array import Array
420
+ return Array(a.flat, a.shape) # works with e.g. NumPy arrays
421
+
422
+ if not isinstance(a, str):
423
+ if _is_numpy_instance(a):
424
+ import numpy as np
425
+ assert not isinstance(a, np.number)
426
+ if isinstance(a, np.ndarray):
427
+ # Scalar arrays (those with zero dimensions) have sympify
428
+ # called on the scalar element.
429
+ if a.ndim == 0:
430
+ try:
431
+ return sympify(a.item(),
432
+ locals=locals,
433
+ convert_xor=convert_xor,
434
+ strict=strict,
435
+ rational=rational,
436
+ evaluate=evaluate)
437
+ except SympifyError:
438
+ pass
439
+ else:
440
+ # float and int can coerce size-one numpy arrays to their lone
441
+ # element. See issue https://github.com/numpy/numpy/issues/10404.
442
+ for coerce in (float, int):
443
+ try:
444
+ return sympify(coerce(a))
445
+ except (TypeError, ValueError, AttributeError, SympifyError):
446
+ continue
447
+
448
+ if strict:
449
+ raise SympifyError(a)
450
+
451
+ if iterable(a):
452
+ try:
453
+ return type(a)([sympify(x, locals=locals, convert_xor=convert_xor,
454
+ rational=rational, evaluate=evaluate) for x in a])
455
+ except TypeError:
456
+ # Not all iterables are rebuildable with their type.
457
+ pass
458
+
459
+ if not isinstance(a, str):
460
+ try:
461
+ a = str(a)
462
+ except Exception as exc:
463
+ raise SympifyError(a, exc)
464
+ sympy_deprecation_warning(
465
+ f"""
466
+ The string fallback in sympify() is deprecated.
467
+
468
+ To explicitly convert the string form of an object, use
469
+ sympify(str(obj)). To add define sympify behavior on custom
470
+ objects, use sympy.core.sympify.converter or define obj._sympy_
471
+ (see the sympify() docstring).
472
+
473
+ sympify() performed the string fallback resulting in the following string:
474
+
475
+ {a!r}
476
+ """,
477
+ deprecated_since_version='1.6',
478
+ active_deprecations_target="deprecated-sympify-string-fallback",
479
+ )
480
+
481
+ from sympy.parsing.sympy_parser import (parse_expr, TokenError,
482
+ standard_transformations)
483
+ from sympy.parsing.sympy_parser import convert_xor as t_convert_xor
484
+ from sympy.parsing.sympy_parser import rationalize as t_rationalize
485
+
486
+ transformations = standard_transformations
487
+
488
+ if rational:
489
+ transformations += (t_rationalize,)
490
+ if convert_xor:
491
+ transformations += (t_convert_xor,)
492
+
493
+ try:
494
+ a = a.replace('\n', '')
495
+ expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
496
+ except (TokenError, SyntaxError) as exc:
497
+ raise SympifyError('could not parse %r' % a, exc)
498
+
499
+ return expr
500
+
501
+
502
+ def _sympify(a):
503
+ """
504
+ Short version of :func:`~.sympify` for internal usage for ``__add__`` and
505
+ ``__eq__`` methods where it is ok to allow some things (like Python
506
+ integers and floats) in the expression. This excludes things (like strings)
507
+ that are unwise to allow into such an expression.
508
+
509
+ >>> from sympy import Integer
510
+ >>> Integer(1) == 1
511
+ True
512
+
513
+ >>> Integer(1) == '1'
514
+ False
515
+
516
+ >>> from sympy.abc import x
517
+ >>> x + 1
518
+ x + 1
519
+
520
+ >>> x + '1'
521
+ Traceback (most recent call last):
522
+ ...
523
+ TypeError: unsupported operand type(s) for +: 'Symbol' and 'str'
524
+
525
+ see: sympify
526
+
527
+ """
528
+ return sympify(a, strict=True)
529
+
530
+
531
+ def kernS(s):
532
+ """Use a hack to try keep autosimplification from distributing a
533
+ a number into an Add; this modification does not
534
+ prevent the 2-arg Mul from becoming an Add, however.
535
+
536
+ Examples
537
+ ========
538
+
539
+ >>> from sympy.core.sympify import kernS
540
+ >>> from sympy.abc import x, y
541
+
542
+ The 2-arg Mul distributes a number (or minus sign) across the terms
543
+ of an expression, but kernS will prevent that:
544
+
545
+ >>> 2*(x + y), -(x + 1)
546
+ (2*x + 2*y, -x - 1)
547
+ >>> kernS('2*(x + y)')
548
+ 2*(x + y)
549
+ >>> kernS('-(x + 1)')
550
+ -(x + 1)
551
+
552
+ If use of the hack fails, the un-hacked string will be passed to sympify...
553
+ and you get what you get.
554
+
555
+ XXX This hack should not be necessary once issue 4596 has been resolved.
556
+ """
557
+ hit = False
558
+ quoted = '"' in s or "'" in s
559
+ if '(' in s and not quoted:
560
+ if s.count('(') != s.count(")"):
561
+ raise SympifyError('unmatched left parenthesis')
562
+
563
+ # strip all space from s
564
+ s = ''.join(s.split())
565
+ olds = s
566
+ # now use space to represent a symbol that
567
+ # will
568
+ # step 1. turn potential 2-arg Muls into 3-arg versions
569
+ # 1a. *( -> * *(
570
+ s = s.replace('*(', '* *(')
571
+ # 1b. close up exponentials
572
+ s = s.replace('** *', '**')
573
+ # 2. handle the implied multiplication of a negated
574
+ # parenthesized expression in two steps
575
+ # 2a: -(...) --> -( *(...)
576
+ target = '-( *('
577
+ s = s.replace('-(', target)
578
+ # 2b: double the matching closing parenthesis
579
+ # -( *(...) --> -( *(...))
580
+ i = nest = 0
581
+ assert target.endswith('(') # assumption below
582
+ while True:
583
+ j = s.find(target, i)
584
+ if j == -1:
585
+ break
586
+ j += len(target) - 1
587
+ for j in range(j, len(s)):
588
+ if s[j] == "(":
589
+ nest += 1
590
+ elif s[j] == ")":
591
+ nest -= 1
592
+ if nest == 0:
593
+ break
594
+ s = s[:j] + ")" + s[j:]
595
+ i = j + 2 # the first char after 2nd )
596
+ if ' ' in s:
597
+ # get a unique kern
598
+ kern = '_'
599
+ while kern in s:
600
+ kern += choice(string.ascii_letters + string.digits)
601
+ s = s.replace(' ', kern)
602
+ hit = kern in s
603
+ else:
604
+ hit = False
605
+
606
+ for i in range(2):
607
+ try:
608
+ expr = sympify(s)
609
+ break
610
+ except TypeError: # the kern might cause unknown errors...
611
+ if hit:
612
+ s = olds # maybe it didn't like the kern; use un-kerned s
613
+ hit = False
614
+ continue
615
+ expr = sympify(s) # let original error raise
616
+
617
+ if not hit:
618
+ return expr
619
+
620
+ from .symbol import Symbol
621
+ rep = {Symbol(kern): 1}
622
+ def _clear(expr):
623
+ if isinstance(expr, (list, tuple, set)):
624
+ return type(expr)([_clear(e) for e in expr])
625
+ if hasattr(expr, 'subs'):
626
+ return expr.subs(rep, hack2=True)
627
+ return expr
628
+ expr = _clear(expr)
629
+ # hope that kern is not there anymore
630
+ return expr
631
+
632
+
633
+ # Avoid circular import
634
+ from .basic import Basic
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_args.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_arit.py ADDED
@@ -0,0 +1,2463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.add import Add
2
+ from sympy.core.basic import Basic
3
+ from sympy.core.mod import Mod
4
+ from sympy.core.mul import Mul
5
+ from sympy.core.numbers import (Float, I, Integer, Rational, comp, nan,
6
+ oo, pi, zoo)
7
+ from sympy.core.power import Pow
8
+ from sympy.core.singleton import S
9
+ from sympy.core.symbol import (Dummy, Symbol, symbols)
10
+ from sympy.core.sympify import sympify
11
+ from sympy.functions.combinatorial.factorials import factorial
12
+ from sympy.functions.elementary.complexes import (im, re, sign)
13
+ from sympy.functions.elementary.exponential import (exp, log)
14
+ from sympy.functions.elementary.integers import floor
15
+ from sympy.functions.elementary.miscellaneous import (Max, sqrt)
16
+ from sympy.functions.elementary.trigonometric import (atan, cos, sin)
17
+ from sympy.polys.polytools import Poly
18
+ from sympy.sets.sets import FiniteSet
19
+
20
+ from sympy.core.parameters import distribute, evaluate
21
+ from sympy.core.expr import unchanged
22
+ from sympy.utilities.iterables import permutations
23
+ from sympy.testing.pytest import XFAIL, raises, warns
24
+ from sympy.utilities.exceptions import SymPyDeprecationWarning
25
+ from sympy.core.random import verify_numerically
26
+ from sympy.functions.elementary.trigonometric import asin
27
+
28
+ from itertools import product
29
+
30
+ a, c, x, y, z = symbols('a,c,x,y,z')
31
+ b = Symbol("b", positive=True)
32
+
33
+
34
+ def same_and_same_prec(a, b):
35
+ # stricter matching for Floats
36
+ return a == b and a._prec == b._prec
37
+
38
+
39
+ def test_bug1():
40
+ assert re(x) != x
41
+ x.series(x, 0, 1)
42
+ assert re(x) != x
43
+
44
+
45
+ def test_Symbol():
46
+ e = a*b
47
+ assert e == a*b
48
+ assert a*b*b == a*b**2
49
+ assert a*b*b + c == c + a*b**2
50
+ assert a*b*b - c == -c + a*b**2
51
+
52
+ x = Symbol('x', complex=True, real=False)
53
+ assert x.is_imaginary is None # could be I or 1 + I
54
+ x = Symbol('x', complex=True, imaginary=False)
55
+ assert x.is_real is None # could be 1 or 1 + I
56
+ x = Symbol('x', real=True)
57
+ assert x.is_complex
58
+ x = Symbol('x', imaginary=True)
59
+ assert x.is_complex
60
+ x = Symbol('x', real=False, imaginary=False)
61
+ assert x.is_complex is None # might be a non-number
62
+
63
+
64
+ def test_arit0():
65
+ p = Rational(5)
66
+ e = a*b
67
+ assert e == a*b
68
+ e = a*b + b*a
69
+ assert e == 2*a*b
70
+ e = a*b + b*a + a*b + p*b*a
71
+ assert e == 8*a*b
72
+ e = a*b + b*a + a*b + p*b*a + a
73
+ assert e == a + 8*a*b
74
+ e = a + a
75
+ assert e == 2*a
76
+ e = a + b + a
77
+ assert e == b + 2*a
78
+ e = a + b*b + a + b*b
79
+ assert e == 2*a + 2*b**2
80
+ e = a + Rational(2) + b*b + a + b*b + p
81
+ assert e == 7 + 2*a + 2*b**2
82
+ e = (a + b*b + a + b*b)*p
83
+ assert e == 5*(2*a + 2*b**2)
84
+ e = (a*b*c + c*b*a + b*a*c)*p
85
+ assert e == 15*a*b*c
86
+ e = (a*b*c + c*b*a + b*a*c)*p - Rational(15)*a*b*c
87
+ assert e == Rational(0)
88
+ e = Rational(50)*(a - a)
89
+ assert e == Rational(0)
90
+ e = b*a - b - a*b + b
91
+ assert e == Rational(0)
92
+ e = a*b + c**p
93
+ assert e == a*b + c**5
94
+ e = a/b
95
+ assert e == a*b**(-1)
96
+ e = a*2*2
97
+ assert e == 4*a
98
+ e = 2 + a*2/2
99
+ assert e == 2 + a
100
+ e = 2 - a - 2
101
+ assert e == -a
102
+ e = 2*a*2
103
+ assert e == 4*a
104
+ e = 2/a/2
105
+ assert e == a**(-1)
106
+ e = 2**a**2
107
+ assert e == 2**(a**2)
108
+ e = -(1 + a)
109
+ assert e == -1 - a
110
+ e = S.Half*(1 + a)
111
+ assert e == S.Half + a/2
112
+
113
+
114
+ def test_div():
115
+ e = a/b
116
+ assert e == a*b**(-1)
117
+ e = a/b + c/2
118
+ assert e == a*b**(-1) + Rational(1)/2*c
119
+ e = (1 - b)/(b - 1)
120
+ assert e == (1 + -b)*((-1) + b)**(-1)
121
+
122
+
123
+ def test_pow_arit():
124
+ n1 = Rational(1)
125
+ n2 = Rational(2)
126
+ n5 = Rational(5)
127
+ e = a*a
128
+ assert e == a**2
129
+ e = a*a*a
130
+ assert e == a**3
131
+ e = a*a*a*a**Rational(6)
132
+ assert e == a**9
133
+ e = a*a*a*a**Rational(6) - a**Rational(9)
134
+ assert e == Rational(0)
135
+ e = a**(b - b)
136
+ assert e == Rational(1)
137
+ e = (a + Rational(1) - a)**b
138
+ assert e == Rational(1)
139
+
140
+ e = (a + b + c)**n2
141
+ assert e == (a + b + c)**2
142
+ assert e.expand() == 2*b*c + 2*a*c + 2*a*b + a**2 + c**2 + b**2
143
+
144
+ e = (a + b)**n2
145
+ assert e == (a + b)**2
146
+ assert e.expand() == 2*a*b + a**2 + b**2
147
+
148
+ e = (a + b)**(n1/n2)
149
+ assert e == sqrt(a + b)
150
+ assert e.expand() == sqrt(a + b)
151
+
152
+ n = n5**(n1/n2)
153
+ assert n == sqrt(5)
154
+ e = n*a*b - n*b*a
155
+ assert e == Rational(0)
156
+ e = n*a*b + n*b*a
157
+ assert e == 2*a*b*sqrt(5)
158
+ assert e.diff(a) == 2*b*sqrt(5)
159
+ assert e.diff(a) == 2*b*sqrt(5)
160
+ e = a/b**2
161
+ assert e == a*b**(-2)
162
+
163
+ assert sqrt(2*(1 + sqrt(2))) == (2*(1 + 2**S.Half))**S.Half
164
+
165
+ x = Symbol('x')
166
+ y = Symbol('y')
167
+
168
+ assert ((x*y)**3).expand() == y**3 * x**3
169
+ assert ((x*y)**-3).expand() == y**-3 * x**-3
170
+
171
+ assert (x**5*(3*x)**(3)).expand() == 27 * x**8
172
+ assert (x**5*(-3*x)**(3)).expand() == -27 * x**8
173
+ assert (x**5*(3*x)**(-3)).expand() == x**2 * Rational(1, 27)
174
+ assert (x**5*(-3*x)**(-3)).expand() == x**2 * Rational(-1, 27)
175
+
176
+ # expand_power_exp
177
+ _x = Symbol('x', zero=False)
178
+ _y = Symbol('y', zero=False)
179
+ assert (_x**(y**(x + exp(x + y)) + z)).expand(deep=False) == \
180
+ _x**z*_x**(y**(x + exp(x + y)))
181
+ assert (_x**(_y**(x + exp(x + y)) + z)).expand() == \
182
+ _x**z*_x**(_y**x*_y**(exp(x)*exp(y)))
183
+
184
+ n = Symbol('n', even=False)
185
+ k = Symbol('k', even=True)
186
+ o = Symbol('o', odd=True)
187
+
188
+ assert unchanged(Pow, -1, x)
189
+ assert unchanged(Pow, -1, n)
190
+ assert (-2)**k == 2**k
191
+ assert (-1)**k == 1
192
+ assert (-1)**o == -1
193
+
194
+
195
+ def test_pow2():
196
+ # x**(2*y) is always (x**y)**2 but is only (x**2)**y if
197
+ # x.is_positive or y.is_integer
198
+ # let x = 1 to see why the following are not true.
199
+ assert (-x)**Rational(2, 3) != x**Rational(2, 3)
200
+ assert (-x)**Rational(5, 7) != -x**Rational(5, 7)
201
+ assert ((-x)**2)**Rational(1, 3) != ((-x)**Rational(1, 3))**2
202
+ assert sqrt(x**2) != x
203
+
204
+
205
+ def test_pow3():
206
+ assert sqrt(2)**3 == 2 * sqrt(2)
207
+ assert sqrt(2)**3 == sqrt(8)
208
+
209
+
210
+ def test_mod_pow():
211
+ for s, t, u, v in [(4, 13, 497, 445), (4, -3, 497, 365),
212
+ (3.2, 2.1, 1.9, 0.1031015682350942), (S(3)/2, 5, S(5)/6, S(3)/32)]:
213
+ assert pow(S(s), t, u) == v
214
+ assert pow(S(s), S(t), u) == v
215
+ assert pow(S(s), t, S(u)) == v
216
+ assert pow(S(s), S(t), S(u)) == v
217
+ assert pow(S(2), S(10000000000), S(3)) == 1
218
+ assert pow(x, y, z) == x**y%z
219
+ raises(TypeError, lambda: pow(S(4), "13", 497))
220
+ raises(TypeError, lambda: pow(S(4), 13, "497"))
221
+
222
+
223
+ def test_pow_E():
224
+ assert 2**(y/log(2)) == S.Exp1**y
225
+ assert 2**(y/log(2)/3) == S.Exp1**(y/3)
226
+ assert 3**(1/log(-3)) != S.Exp1
227
+ assert (3 + 2*I)**(1/(log(-3 - 2*I) + I*pi)) == S.Exp1
228
+ assert (4 + 2*I)**(1/(log(-4 - 2*I) + I*pi)) == S.Exp1
229
+ assert (3 + 2*I)**(1/(log(-3 - 2*I, 3)/2 + I*pi/log(3)/2)) == 9
230
+ assert (3 + 2*I)**(1/(log(3 + 2*I, 3)/2)) == 9
231
+ # every time tests are run they will affirm with a different random
232
+ # value that this identity holds
233
+ while 1:
234
+ b = x._random()
235
+ r, i = b.as_real_imag()
236
+ if i:
237
+ break
238
+ assert verify_numerically(b**(1/(log(-b) + sign(i)*I*pi).n()), S.Exp1)
239
+
240
+
241
+ def test_pow_issue_3516():
242
+ assert 4**Rational(1, 4) == sqrt(2)
243
+
244
+
245
+ def test_pow_im():
246
+ for m in (-2, -1, 2):
247
+ for d in (3, 4, 5):
248
+ b = m*I
249
+ for i in range(1, 4*d + 1):
250
+ e = Rational(i, d)
251
+ assert (b**e - b.n()**e.n()).n(2, chop=1e-10) == 0
252
+
253
+ e = Rational(7, 3)
254
+ assert (2*x*I)**e == 4*2**Rational(1, 3)*(I*x)**e # same as Wolfram Alpha
255
+ im = symbols('im', imaginary=True)
256
+ assert (2*im*I)**e == 4*2**Rational(1, 3)*(I*im)**e
257
+
258
+ args = [I, I, I, I, 2]
259
+ e = Rational(1, 3)
260
+ ans = 2**e
261
+ assert Mul(*args, evaluate=False)**e == ans
262
+ assert Mul(*args)**e == ans
263
+ args = [I, I, I, 2]
264
+ e = Rational(1, 3)
265
+ ans = 2**e*(-I)**e
266
+ assert Mul(*args, evaluate=False)**e == ans
267
+ assert Mul(*args)**e == ans
268
+ args.append(-3)
269
+ ans = (6*I)**e
270
+ assert Mul(*args, evaluate=False)**e == ans
271
+ assert Mul(*args)**e == ans
272
+ args.append(-1)
273
+ ans = (-6*I)**e
274
+ assert Mul(*args, evaluate=False)**e == ans
275
+ assert Mul(*args)**e == ans
276
+
277
+ args = [I, I, 2]
278
+ e = Rational(1, 3)
279
+ ans = (-2)**e
280
+ assert Mul(*args, evaluate=False)**e == ans
281
+ assert Mul(*args)**e == ans
282
+ args.append(-3)
283
+ ans = (6)**e
284
+ assert Mul(*args, evaluate=False)**e == ans
285
+ assert Mul(*args)**e == ans
286
+ args.append(-1)
287
+ ans = (-6)**e
288
+ assert Mul(*args, evaluate=False)**e == ans
289
+ assert Mul(*args)**e == ans
290
+ assert Mul(Pow(-1, Rational(3, 2), evaluate=False), I, I) == I
291
+ assert Mul(I*Pow(I, S.Half, evaluate=False)) == sqrt(I)*I
292
+
293
+
294
+ def test_real_mul():
295
+ assert Float(0) * pi * x == 0
296
+ assert set((Float(1) * pi * x).args) == {Float(1), pi, x}
297
+
298
+
299
+ def test_ncmul():
300
+ A = Symbol("A", commutative=False)
301
+ B = Symbol("B", commutative=False)
302
+ C = Symbol("C", commutative=False)
303
+ assert A*B != B*A
304
+ assert A*B*C != C*B*A
305
+ assert A*b*B*3*C == 3*b*A*B*C
306
+ assert A*b*B*3*C != 3*b*B*A*C
307
+ assert A*b*B*3*C == 3*A*B*C*b
308
+
309
+ assert A + B == B + A
310
+ assert (A + B)*C != C*(A + B)
311
+
312
+ assert C*(A + B)*C != C*C*(A + B)
313
+
314
+ assert A*A == A**2
315
+ assert (A + B)*(A + B) == (A + B)**2
316
+
317
+ assert A**-1 * A == 1
318
+ assert A/A == 1
319
+ assert A/(A**2) == 1/A
320
+
321
+ assert A/(1 + A) == A/(1 + A)
322
+
323
+ assert set((A + B + 2*(A + B)).args) == \
324
+ {A, B, 2*(A + B)}
325
+
326
+
327
+ def test_mul_add_identity():
328
+ m = Mul(1, 2)
329
+ assert isinstance(m, Rational) and m.p == 2 and m.q == 1
330
+ m = Mul(1, 2, evaluate=False)
331
+ assert isinstance(m, Mul) and m.args == (1, 2)
332
+ m = Mul(0, 1)
333
+ assert m is S.Zero
334
+ m = Mul(0, 1, evaluate=False)
335
+ assert isinstance(m, Mul) and m.args == (0, 1)
336
+ m = Add(0, 1)
337
+ assert m is S.One
338
+ m = Add(0, 1, evaluate=False)
339
+ assert isinstance(m, Add) and m.args == (0, 1)
340
+
341
+
342
+ def test_ncpow():
343
+ x = Symbol('x', commutative=False)
344
+ y = Symbol('y', commutative=False)
345
+ z = Symbol('z', commutative=False)
346
+ a = Symbol('a')
347
+ b = Symbol('b')
348
+ c = Symbol('c')
349
+
350
+ assert (x**2)*(y**2) != (y**2)*(x**2)
351
+ assert (x**-2)*y != y*(x**2)
352
+ assert 2**x*2**y != 2**(x + y)
353
+ assert 2**x*2**y*2**z != 2**(x + y + z)
354
+ assert 2**x*2**(2*x) == 2**(3*x)
355
+ assert 2**x*2**(2*x)*2**x == 2**(4*x)
356
+ assert exp(x)*exp(y) != exp(y)*exp(x)
357
+ assert exp(x)*exp(y)*exp(z) != exp(y)*exp(x)*exp(z)
358
+ assert exp(x)*exp(y)*exp(z) != exp(x + y + z)
359
+ assert x**a*x**b != x**(a + b)
360
+ assert x**a*x**b*x**c != x**(a + b + c)
361
+ assert x**3*x**4 == x**7
362
+ assert x**3*x**4*x**2 == x**9
363
+ assert x**a*x**(4*a) == x**(5*a)
364
+ assert x**a*x**(4*a)*x**a == x**(6*a)
365
+
366
+
367
+ def test_powerbug():
368
+ x = Symbol("x")
369
+ assert x**1 != (-x)**1
370
+ assert x**2 == (-x)**2
371
+ assert x**3 != (-x)**3
372
+ assert x**4 == (-x)**4
373
+ assert x**5 != (-x)**5
374
+ assert x**6 == (-x)**6
375
+
376
+ assert x**128 == (-x)**128
377
+ assert x**129 != (-x)**129
378
+
379
+ assert (2*x)**2 == (-2*x)**2
380
+
381
+
382
+ def test_Mul_doesnt_expand_exp():
383
+ x = Symbol('x')
384
+ y = Symbol('y')
385
+ assert unchanged(Mul, exp(x), exp(y))
386
+ assert unchanged(Mul, 2**x, 2**y)
387
+ assert x**2*x**3 == x**5
388
+ assert 2**x*3**x == 6**x
389
+ assert x**(y)*x**(2*y) == x**(3*y)
390
+ assert sqrt(2)*sqrt(2) == 2
391
+ assert 2**x*2**(2*x) == 2**(3*x)
392
+ assert sqrt(2)*2**Rational(1, 4)*5**Rational(3, 4) == 10**Rational(3, 4)
393
+ assert (x**(-log(5)/log(3))*x)/(x*x**( - log(5)/log(3))) == sympify(1)
394
+
395
+
396
+ def test_Mul_is_integer():
397
+ k = Symbol('k', integer=True)
398
+ n = Symbol('n', integer=True)
399
+ nr = Symbol('nr', rational=False)
400
+ ir = Symbol('ir', irrational=True)
401
+ nz = Symbol('nz', integer=True, zero=False)
402
+ e = Symbol('e', even=True)
403
+ o = Symbol('o', odd=True)
404
+ i2 = Symbol('2', prime=True, even=True)
405
+
406
+ assert (k/3).is_integer is None
407
+ assert (nz/3).is_integer is None
408
+ assert (nr/3).is_integer is False
409
+ assert (ir/3).is_integer is False
410
+ assert (x*k*n).is_integer is None
411
+ assert (e/2).is_integer is True
412
+ assert (e**2/2).is_integer is True
413
+ assert (2/k).is_integer is None
414
+ assert (2/k**2).is_integer is None
415
+ assert ((-1)**k*n).is_integer is True
416
+ assert (3*k*e/2).is_integer is True
417
+ assert (2*k*e/3).is_integer is None
418
+ assert (e/o).is_integer is None
419
+ assert (o/e).is_integer is False
420
+ assert (o/i2).is_integer is False
421
+ assert Mul(k, 1/k, evaluate=False).is_integer is None
422
+ assert Mul(2., S.Half, evaluate=False).is_integer is None
423
+ assert (2*sqrt(k)).is_integer is None
424
+ assert (2*k**n).is_integer is None
425
+
426
+ s = 2**2**2**Pow(2, 1000, evaluate=False)
427
+ m = Mul(s, s, evaluate=False)
428
+ assert m.is_integer
429
+
430
+ # broken in 1.6 and before, see #20161
431
+ xq = Symbol('xq', rational=True)
432
+ yq = Symbol('yq', rational=True)
433
+ assert (xq*yq).is_integer is None
434
+ e_20161 = Mul(-1,Mul(1,Pow(2,-1,evaluate=False),evaluate=False),evaluate=False)
435
+ assert e_20161.is_integer is not True # expand(e_20161) -> -1/2, but no need to see that in the assumption without evaluation
436
+
437
+
438
+ def test_Add_Mul_is_integer():
439
+ x = Symbol('x')
440
+
441
+ k = Symbol('k', integer=True)
442
+ n = Symbol('n', integer=True)
443
+ nk = Symbol('nk', integer=False)
444
+ nr = Symbol('nr', rational=False)
445
+ nz = Symbol('nz', integer=True, zero=False)
446
+
447
+ assert (-nk).is_integer is None
448
+ assert (-nr).is_integer is False
449
+ assert (2*k).is_integer is True
450
+ assert (-k).is_integer is True
451
+
452
+ assert (k + nk).is_integer is False
453
+ assert (k + n).is_integer is True
454
+ assert (k + x).is_integer is None
455
+ assert (k + n*x).is_integer is None
456
+ assert (k + n/3).is_integer is None
457
+ assert (k + nz/3).is_integer is None
458
+ assert (k + nr/3).is_integer is False
459
+
460
+ assert ((1 + sqrt(3))*(-sqrt(3) + 1)).is_integer is not False
461
+ assert (1 + (1 + sqrt(3))*(-sqrt(3) + 1)).is_integer is not False
462
+
463
+
464
+ def test_Add_Mul_is_finite():
465
+ x = Symbol('x', extended_real=True, finite=False)
466
+
467
+ assert sin(x).is_finite is True
468
+ assert (x*sin(x)).is_finite is None
469
+ assert (x*atan(x)).is_finite is False
470
+ assert (1024*sin(x)).is_finite is True
471
+ assert (sin(x)*exp(x)).is_finite is None
472
+ assert (sin(x)*cos(x)).is_finite is True
473
+ assert (x*sin(x)*exp(x)).is_finite is None
474
+
475
+ assert (sin(x) - 67).is_finite is True
476
+ assert (sin(x) + exp(x)).is_finite is not True
477
+ assert (1 + x).is_finite is False
478
+ assert (1 + x**2 + (1 + x)*(1 - x)).is_finite is None
479
+ assert (sqrt(2)*(1 + x)).is_finite is False
480
+ assert (sqrt(2)*(1 + x)*(1 - x)).is_finite is False
481
+
482
+
483
+ def test_Mul_is_even_odd():
484
+ x = Symbol('x', integer=True)
485
+ y = Symbol('y', integer=True)
486
+
487
+ k = Symbol('k', odd=True)
488
+ n = Symbol('n', odd=True)
489
+ m = Symbol('m', even=True)
490
+
491
+ assert (2*x).is_even is True
492
+ assert (2*x).is_odd is False
493
+
494
+ assert (3*x).is_even is None
495
+ assert (3*x).is_odd is None
496
+
497
+ assert (k/3).is_integer is None
498
+ assert (k/3).is_even is None
499
+ assert (k/3).is_odd is None
500
+
501
+ assert (2*n).is_even is True
502
+ assert (2*n).is_odd is False
503
+
504
+ assert (2*m).is_even is True
505
+ assert (2*m).is_odd is False
506
+
507
+ assert (-n).is_even is False
508
+ assert (-n).is_odd is True
509
+
510
+ assert (k*n).is_even is False
511
+ assert (k*n).is_odd is True
512
+
513
+ assert (k*m).is_even is True
514
+ assert (k*m).is_odd is False
515
+
516
+ assert (k*n*m).is_even is True
517
+ assert (k*n*m).is_odd is False
518
+
519
+ assert (k*m*x).is_even is True
520
+ assert (k*m*x).is_odd is False
521
+
522
+ # issue 6791:
523
+ assert (x/2).is_integer is None
524
+ assert (k/2).is_integer is False
525
+ assert (m/2).is_integer is True
526
+
527
+ assert (x*y).is_even is None
528
+ assert (x*x).is_even is None
529
+ assert (x*(x + k)).is_even is True
530
+ assert (x*(x + m)).is_even is None
531
+
532
+ assert (x*y).is_odd is None
533
+ assert (x*x).is_odd is None
534
+ assert (x*(x + k)).is_odd is False
535
+ assert (x*(x + m)).is_odd is None
536
+
537
+ # issue 8648
538
+ assert (m**2/2).is_even
539
+ assert (m**2/3).is_even is False
540
+ assert (2/m**2).is_odd is False
541
+ assert (2/m).is_odd is None
542
+
543
+
544
+ @XFAIL
545
+ def test_evenness_in_ternary_integer_product_with_odd():
546
+ # Tests that oddness inference is independent of term ordering.
547
+ # Term ordering at the point of testing depends on SymPy's symbol order, so
548
+ # we try to force a different order by modifying symbol names.
549
+ x = Symbol('x', integer=True)
550
+ y = Symbol('y', integer=True)
551
+ k = Symbol('k', odd=True)
552
+ assert (x*y*(y + k)).is_even is True
553
+ assert (y*x*(x + k)).is_even is True
554
+
555
+
556
+ def test_evenness_in_ternary_integer_product_with_even():
557
+ x = Symbol('x', integer=True)
558
+ y = Symbol('y', integer=True)
559
+ m = Symbol('m', even=True)
560
+ assert (x*y*(y + m)).is_even is None
561
+
562
+
563
+ @XFAIL
564
+ def test_oddness_in_ternary_integer_product_with_odd():
565
+ # Tests that oddness inference is independent of term ordering.
566
+ # Term ordering at the point of testing depends on SymPy's symbol order, so
567
+ # we try to force a different order by modifying symbol names.
568
+ x = Symbol('x', integer=True)
569
+ y = Symbol('y', integer=True)
570
+ k = Symbol('k', odd=True)
571
+ assert (x*y*(y + k)).is_odd is False
572
+ assert (y*x*(x + k)).is_odd is False
573
+
574
+
575
+ def test_oddness_in_ternary_integer_product_with_even():
576
+ x = Symbol('x', integer=True)
577
+ y = Symbol('y', integer=True)
578
+ m = Symbol('m', even=True)
579
+ assert (x*y*(y + m)).is_odd is None
580
+
581
+
582
+ def test_Mul_is_rational():
583
+ x = Symbol('x')
584
+ n = Symbol('n', integer=True)
585
+ m = Symbol('m', integer=True, nonzero=True)
586
+
587
+ assert (n/m).is_rational is True
588
+ assert (x/pi).is_rational is None
589
+ assert (x/n).is_rational is None
590
+ assert (m/pi).is_rational is False
591
+
592
+ r = Symbol('r', rational=True)
593
+ assert (pi*r).is_rational is None
594
+
595
+ # issue 8008
596
+ z = Symbol('z', zero=True)
597
+ i = Symbol('i', imaginary=True)
598
+ assert (z*i).is_rational is True
599
+ bi = Symbol('i', imaginary=True, finite=True)
600
+ assert (z*bi).is_zero is True
601
+
602
+
603
+ def test_Add_is_rational():
604
+ x = Symbol('x')
605
+ n = Symbol('n', rational=True)
606
+ m = Symbol('m', rational=True)
607
+
608
+ assert (n + m).is_rational is True
609
+ assert (x + pi).is_rational is None
610
+ assert (x + n).is_rational is None
611
+ assert (n + pi).is_rational is False
612
+
613
+
614
+ def test_Add_is_even_odd():
615
+ x = Symbol('x', integer=True)
616
+
617
+ k = Symbol('k', odd=True)
618
+ n = Symbol('n', odd=True)
619
+ m = Symbol('m', even=True)
620
+
621
+ assert (k + 7).is_even is True
622
+ assert (k + 7).is_odd is False
623
+
624
+ assert (-k + 7).is_even is True
625
+ assert (-k + 7).is_odd is False
626
+
627
+ assert (k - 12).is_even is False
628
+ assert (k - 12).is_odd is True
629
+
630
+ assert (-k - 12).is_even is False
631
+ assert (-k - 12).is_odd is True
632
+
633
+ assert (k + n).is_even is True
634
+ assert (k + n).is_odd is False
635
+
636
+ assert (k + m).is_even is False
637
+ assert (k + m).is_odd is True
638
+
639
+ assert (k + n + m).is_even is True
640
+ assert (k + n + m).is_odd is False
641
+
642
+ assert (k + n + x + m).is_even is None
643
+ assert (k + n + x + m).is_odd is None
644
+
645
+
646
+ def test_Mul_is_negative_positive():
647
+ x = Symbol('x', real=True)
648
+ y = Symbol('y', extended_real=False, complex=True)
649
+ z = Symbol('z', zero=True)
650
+
651
+ e = 2*z
652
+ assert e.is_Mul and e.is_positive is False and e.is_negative is False
653
+
654
+ neg = Symbol('neg', negative=True)
655
+ pos = Symbol('pos', positive=True)
656
+ nneg = Symbol('nneg', nonnegative=True)
657
+ npos = Symbol('npos', nonpositive=True)
658
+
659
+ assert neg.is_negative is True
660
+ assert (-neg).is_negative is False
661
+ assert (2*neg).is_negative is True
662
+
663
+ assert (2*pos)._eval_is_extended_negative() is False
664
+ assert (2*pos).is_negative is False
665
+
666
+ assert pos.is_negative is False
667
+ assert (-pos).is_negative is True
668
+ assert (2*pos).is_negative is False
669
+
670
+ assert (pos*neg).is_negative is True
671
+ assert (2*pos*neg).is_negative is True
672
+ assert (-pos*neg).is_negative is False
673
+ assert (pos*neg*y).is_negative is False # y.is_real=F; !real -> !neg
674
+
675
+ assert nneg.is_negative is False
676
+ assert (-nneg).is_negative is None
677
+ assert (2*nneg).is_negative is False
678
+
679
+ assert npos.is_negative is None
680
+ assert (-npos).is_negative is False
681
+ assert (2*npos).is_negative is None
682
+
683
+ assert (nneg*npos).is_negative is None
684
+
685
+ assert (neg*nneg).is_negative is None
686
+ assert (neg*npos).is_negative is False
687
+
688
+ assert (pos*nneg).is_negative is False
689
+ assert (pos*npos).is_negative is None
690
+
691
+ assert (npos*neg*nneg).is_negative is False
692
+ assert (npos*pos*nneg).is_negative is None
693
+
694
+ assert (-npos*neg*nneg).is_negative is None
695
+ assert (-npos*pos*nneg).is_negative is False
696
+
697
+ assert (17*npos*neg*nneg).is_negative is False
698
+ assert (17*npos*pos*nneg).is_negative is None
699
+
700
+ assert (neg*npos*pos*nneg).is_negative is False
701
+
702
+ assert (x*neg).is_negative is None
703
+ assert (nneg*npos*pos*x*neg).is_negative is None
704
+
705
+ assert neg.is_positive is False
706
+ assert (-neg).is_positive is True
707
+ assert (2*neg).is_positive is False
708
+
709
+ assert pos.is_positive is True
710
+ assert (-pos).is_positive is False
711
+ assert (2*pos).is_positive is True
712
+
713
+ assert (pos*neg).is_positive is False
714
+ assert (2*pos*neg).is_positive is False
715
+ assert (-pos*neg).is_positive is True
716
+ assert (-pos*neg*y).is_positive is False # y.is_real=F; !real -> !neg
717
+
718
+ assert nneg.is_positive is None
719
+ assert (-nneg).is_positive is False
720
+ assert (2*nneg).is_positive is None
721
+
722
+ assert npos.is_positive is False
723
+ assert (-npos).is_positive is None
724
+ assert (2*npos).is_positive is False
725
+
726
+ assert (nneg*npos).is_positive is False
727
+
728
+ assert (neg*nneg).is_positive is False
729
+ assert (neg*npos).is_positive is None
730
+
731
+ assert (pos*nneg).is_positive is None
732
+ assert (pos*npos).is_positive is False
733
+
734
+ assert (npos*neg*nneg).is_positive is None
735
+ assert (npos*pos*nneg).is_positive is False
736
+
737
+ assert (-npos*neg*nneg).is_positive is False
738
+ assert (-npos*pos*nneg).is_positive is None
739
+
740
+ assert (17*npos*neg*nneg).is_positive is None
741
+ assert (17*npos*pos*nneg).is_positive is False
742
+
743
+ assert (neg*npos*pos*nneg).is_positive is None
744
+
745
+ assert (x*neg).is_positive is None
746
+ assert (nneg*npos*pos*x*neg).is_positive is None
747
+
748
+
749
+ def test_Mul_is_negative_positive_2():
750
+ a = Symbol('a', nonnegative=True)
751
+ b = Symbol('b', nonnegative=True)
752
+ c = Symbol('c', nonpositive=True)
753
+ d = Symbol('d', nonpositive=True)
754
+
755
+ assert (a*b).is_nonnegative is True
756
+ assert (a*b).is_negative is False
757
+ assert (a*b).is_zero is None
758
+ assert (a*b).is_positive is None
759
+
760
+ assert (c*d).is_nonnegative is True
761
+ assert (c*d).is_negative is False
762
+ assert (c*d).is_zero is None
763
+ assert (c*d).is_positive is None
764
+
765
+ assert (a*c).is_nonpositive is True
766
+ assert (a*c).is_positive is False
767
+ assert (a*c).is_zero is None
768
+ assert (a*c).is_negative is None
769
+
770
+
771
+ def test_Mul_is_nonpositive_nonnegative():
772
+ x = Symbol('x', real=True)
773
+
774
+ k = Symbol('k', negative=True)
775
+ n = Symbol('n', positive=True)
776
+ u = Symbol('u', nonnegative=True)
777
+ v = Symbol('v', nonpositive=True)
778
+
779
+ assert k.is_nonpositive is True
780
+ assert (-k).is_nonpositive is False
781
+ assert (2*k).is_nonpositive is True
782
+
783
+ assert n.is_nonpositive is False
784
+ assert (-n).is_nonpositive is True
785
+ assert (2*n).is_nonpositive is False
786
+
787
+ assert (n*k).is_nonpositive is True
788
+ assert (2*n*k).is_nonpositive is True
789
+ assert (-n*k).is_nonpositive is False
790
+
791
+ assert u.is_nonpositive is None
792
+ assert (-u).is_nonpositive is True
793
+ assert (2*u).is_nonpositive is None
794
+
795
+ assert v.is_nonpositive is True
796
+ assert (-v).is_nonpositive is None
797
+ assert (2*v).is_nonpositive is True
798
+
799
+ assert (u*v).is_nonpositive is True
800
+
801
+ assert (k*u).is_nonpositive is True
802
+ assert (k*v).is_nonpositive is None
803
+
804
+ assert (n*u).is_nonpositive is None
805
+ assert (n*v).is_nonpositive is True
806
+
807
+ assert (v*k*u).is_nonpositive is None
808
+ assert (v*n*u).is_nonpositive is True
809
+
810
+ assert (-v*k*u).is_nonpositive is True
811
+ assert (-v*n*u).is_nonpositive is None
812
+
813
+ assert (17*v*k*u).is_nonpositive is None
814
+ assert (17*v*n*u).is_nonpositive is True
815
+
816
+ assert (k*v*n*u).is_nonpositive is None
817
+
818
+ assert (x*k).is_nonpositive is None
819
+ assert (u*v*n*x*k).is_nonpositive is None
820
+
821
+ assert k.is_nonnegative is False
822
+ assert (-k).is_nonnegative is True
823
+ assert (2*k).is_nonnegative is False
824
+
825
+ assert n.is_nonnegative is True
826
+ assert (-n).is_nonnegative is False
827
+ assert (2*n).is_nonnegative is True
828
+
829
+ assert (n*k).is_nonnegative is False
830
+ assert (2*n*k).is_nonnegative is False
831
+ assert (-n*k).is_nonnegative is True
832
+
833
+ assert u.is_nonnegative is True
834
+ assert (-u).is_nonnegative is None
835
+ assert (2*u).is_nonnegative is True
836
+
837
+ assert v.is_nonnegative is None
838
+ assert (-v).is_nonnegative is True
839
+ assert (2*v).is_nonnegative is None
840
+
841
+ assert (u*v).is_nonnegative is None
842
+
843
+ assert (k*u).is_nonnegative is None
844
+ assert (k*v).is_nonnegative is True
845
+
846
+ assert (n*u).is_nonnegative is True
847
+ assert (n*v).is_nonnegative is None
848
+
849
+ assert (v*k*u).is_nonnegative is True
850
+ assert (v*n*u).is_nonnegative is None
851
+
852
+ assert (-v*k*u).is_nonnegative is None
853
+ assert (-v*n*u).is_nonnegative is True
854
+
855
+ assert (17*v*k*u).is_nonnegative is True
856
+ assert (17*v*n*u).is_nonnegative is None
857
+
858
+ assert (k*v*n*u).is_nonnegative is True
859
+
860
+ assert (x*k).is_nonnegative is None
861
+ assert (u*v*n*x*k).is_nonnegative is None
862
+
863
+
864
+ def test_Add_is_negative_positive():
865
+ x = Symbol('x', real=True)
866
+
867
+ k = Symbol('k', negative=True)
868
+ n = Symbol('n', positive=True)
869
+ u = Symbol('u', nonnegative=True)
870
+ v = Symbol('v', nonpositive=True)
871
+
872
+ assert (k - 2).is_negative is True
873
+ assert (k + 17).is_negative is None
874
+ assert (-k - 5).is_negative is None
875
+ assert (-k + 123).is_negative is False
876
+
877
+ assert (k - n).is_negative is True
878
+ assert (k + n).is_negative is None
879
+ assert (-k - n).is_negative is None
880
+ assert (-k + n).is_negative is False
881
+
882
+ assert (k - n - 2).is_negative is True
883
+ assert (k + n + 17).is_negative is None
884
+ assert (-k - n - 5).is_negative is None
885
+ assert (-k + n + 123).is_negative is False
886
+
887
+ assert (-2*k + 123*n + 17).is_negative is False
888
+
889
+ assert (k + u).is_negative is None
890
+ assert (k + v).is_negative is True
891
+ assert (n + u).is_negative is False
892
+ assert (n + v).is_negative is None
893
+
894
+ assert (u - v).is_negative is False
895
+ assert (u + v).is_negative is None
896
+ assert (-u - v).is_negative is None
897
+ assert (-u + v).is_negative is None
898
+
899
+ assert (u - v + n + 2).is_negative is False
900
+ assert (u + v + n + 2).is_negative is None
901
+ assert (-u - v + n + 2).is_negative is None
902
+ assert (-u + v + n + 2).is_negative is None
903
+
904
+ assert (k + x).is_negative is None
905
+ assert (k + x - n).is_negative is None
906
+
907
+ assert (k - 2).is_positive is False
908
+ assert (k + 17).is_positive is None
909
+ assert (-k - 5).is_positive is None
910
+ assert (-k + 123).is_positive is True
911
+
912
+ assert (k - n).is_positive is False
913
+ assert (k + n).is_positive is None
914
+ assert (-k - n).is_positive is None
915
+ assert (-k + n).is_positive is True
916
+
917
+ assert (k - n - 2).is_positive is False
918
+ assert (k + n + 17).is_positive is None
919
+ assert (-k - n - 5).is_positive is None
920
+ assert (-k + n + 123).is_positive is True
921
+
922
+ assert (-2*k + 123*n + 17).is_positive is True
923
+
924
+ assert (k + u).is_positive is None
925
+ assert (k + v).is_positive is False
926
+ assert (n + u).is_positive is True
927
+ assert (n + v).is_positive is None
928
+
929
+ assert (u - v).is_positive is None
930
+ assert (u + v).is_positive is None
931
+ assert (-u - v).is_positive is None
932
+ assert (-u + v).is_positive is False
933
+
934
+ assert (u - v - n - 2).is_positive is None
935
+ assert (u + v - n - 2).is_positive is None
936
+ assert (-u - v - n - 2).is_positive is None
937
+ assert (-u + v - n - 2).is_positive is False
938
+
939
+ assert (n + x).is_positive is None
940
+ assert (n + x - k).is_positive is None
941
+
942
+ z = (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2)
943
+ assert z.is_zero
944
+ z = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3))
945
+ assert z.is_zero
946
+
947
+
948
+ def test_Add_is_nonpositive_nonnegative():
949
+ x = Symbol('x', real=True)
950
+
951
+ k = Symbol('k', negative=True)
952
+ n = Symbol('n', positive=True)
953
+ u = Symbol('u', nonnegative=True)
954
+ v = Symbol('v', nonpositive=True)
955
+
956
+ assert (u - 2).is_nonpositive is None
957
+ assert (u + 17).is_nonpositive is False
958
+ assert (-u - 5).is_nonpositive is True
959
+ assert (-u + 123).is_nonpositive is None
960
+
961
+ assert (u - v).is_nonpositive is None
962
+ assert (u + v).is_nonpositive is None
963
+ assert (-u - v).is_nonpositive is None
964
+ assert (-u + v).is_nonpositive is True
965
+
966
+ assert (u - v - 2).is_nonpositive is None
967
+ assert (u + v + 17).is_nonpositive is None
968
+ assert (-u - v - 5).is_nonpositive is None
969
+ assert (-u + v - 123).is_nonpositive is True
970
+
971
+ assert (-2*u + 123*v - 17).is_nonpositive is True
972
+
973
+ assert (k + u).is_nonpositive is None
974
+ assert (k + v).is_nonpositive is True
975
+ assert (n + u).is_nonpositive is False
976
+ assert (n + v).is_nonpositive is None
977
+
978
+ assert (k - n).is_nonpositive is True
979
+ assert (k + n).is_nonpositive is None
980
+ assert (-k - n).is_nonpositive is None
981
+ assert (-k + n).is_nonpositive is False
982
+
983
+ assert (k - n + u + 2).is_nonpositive is None
984
+ assert (k + n + u + 2).is_nonpositive is None
985
+ assert (-k - n + u + 2).is_nonpositive is None
986
+ assert (-k + n + u + 2).is_nonpositive is False
987
+
988
+ assert (u + x).is_nonpositive is None
989
+ assert (v - x - n).is_nonpositive is None
990
+
991
+ assert (u - 2).is_nonnegative is None
992
+ assert (u + 17).is_nonnegative is True
993
+ assert (-u - 5).is_nonnegative is False
994
+ assert (-u + 123).is_nonnegative is None
995
+
996
+ assert (u - v).is_nonnegative is True
997
+ assert (u + v).is_nonnegative is None
998
+ assert (-u - v).is_nonnegative is None
999
+ assert (-u + v).is_nonnegative is None
1000
+
1001
+ assert (u - v + 2).is_nonnegative is True
1002
+ assert (u + v + 17).is_nonnegative is None
1003
+ assert (-u - v - 5).is_nonnegative is None
1004
+ assert (-u + v - 123).is_nonnegative is False
1005
+
1006
+ assert (2*u - 123*v + 17).is_nonnegative is True
1007
+
1008
+ assert (k + u).is_nonnegative is None
1009
+ assert (k + v).is_nonnegative is False
1010
+ assert (n + u).is_nonnegative is True
1011
+ assert (n + v).is_nonnegative is None
1012
+
1013
+ assert (k - n).is_nonnegative is False
1014
+ assert (k + n).is_nonnegative is None
1015
+ assert (-k - n).is_nonnegative is None
1016
+ assert (-k + n).is_nonnegative is True
1017
+
1018
+ assert (k - n - u - 2).is_nonnegative is False
1019
+ assert (k + n - u - 2).is_nonnegative is None
1020
+ assert (-k - n - u - 2).is_nonnegative is None
1021
+ assert (-k + n - u - 2).is_nonnegative is None
1022
+
1023
+ assert (u - x).is_nonnegative is None
1024
+ assert (v + x + n).is_nonnegative is None
1025
+
1026
+
1027
+ def test_Pow_is_integer():
1028
+ x = Symbol('x')
1029
+
1030
+ k = Symbol('k', integer=True)
1031
+ n = Symbol('n', integer=True, nonnegative=True)
1032
+ m = Symbol('m', integer=True, positive=True)
1033
+
1034
+ assert (k**2).is_integer is True
1035
+ assert (k**(-2)).is_integer is None
1036
+ assert ((m + 1)**(-2)).is_integer is False
1037
+ assert (m**(-1)).is_integer is None # issue 8580
1038
+
1039
+ assert (2**k).is_integer is None
1040
+ assert (2**(-k)).is_integer is None
1041
+
1042
+ assert (2**n).is_integer is True
1043
+ assert (2**(-n)).is_integer is None
1044
+
1045
+ assert (2**m).is_integer is True
1046
+ assert (2**(-m)).is_integer is False
1047
+
1048
+ assert (x**2).is_integer is None
1049
+ assert (2**x).is_integer is None
1050
+
1051
+ assert (k**n).is_integer is True
1052
+ assert (k**(-n)).is_integer is None
1053
+
1054
+ assert (k**x).is_integer is None
1055
+ assert (x**k).is_integer is None
1056
+
1057
+ assert (k**(n*m)).is_integer is True
1058
+ assert (k**(-n*m)).is_integer is None
1059
+
1060
+ assert sqrt(3).is_integer is False
1061
+ assert sqrt(.3).is_integer is False
1062
+ assert Pow(3, 2, evaluate=False).is_integer is True
1063
+ assert Pow(3, 0, evaluate=False).is_integer is True
1064
+ assert Pow(3, -2, evaluate=False).is_integer is False
1065
+ assert Pow(S.Half, 3, evaluate=False).is_integer is False
1066
+ # decided by re-evaluating
1067
+ assert Pow(3, S.Half, evaluate=False).is_integer is False
1068
+ assert Pow(3, S.Half, evaluate=False).is_integer is False
1069
+ assert Pow(4, S.Half, evaluate=False).is_integer is True
1070
+ assert Pow(S.Half, -2, evaluate=False).is_integer is True
1071
+
1072
+ assert ((-1)**k).is_integer
1073
+
1074
+ # issue 8641
1075
+ x = Symbol('x', real=True, integer=False)
1076
+ assert (x**2).is_integer is None
1077
+
1078
+ # issue 10458
1079
+ x = Symbol('x', positive=True)
1080
+ assert (1/(x + 1)).is_integer is False
1081
+ assert (1/(-x - 1)).is_integer is False
1082
+ assert (-1/(x + 1)).is_integer is False
1083
+ # issue 23287
1084
+ assert (x**2/2).is_integer is None
1085
+
1086
+ # issue 8648-like
1087
+ k = Symbol('k', even=True)
1088
+ assert (k**3/2).is_integer
1089
+ assert (k**3/8).is_integer
1090
+ assert (k**3/16).is_integer is None
1091
+ assert (2/k).is_integer is None
1092
+ assert (2/k**2).is_integer is False
1093
+ o = Symbol('o', odd=True)
1094
+ assert (k/o).is_integer is None
1095
+ o = Symbol('o', odd=True, prime=True)
1096
+ assert (k/o).is_integer is False
1097
+
1098
+
1099
+ def test_Pow_is_real():
1100
+ x = Symbol('x', real=True)
1101
+ y = Symbol('y', positive=True)
1102
+
1103
+ assert (x**2).is_real is True
1104
+ assert (x**3).is_real is True
1105
+ assert (x**x).is_real is None
1106
+ assert (y**x).is_real is True
1107
+
1108
+ assert (x**Rational(1, 3)).is_real is None
1109
+ assert (y**Rational(1, 3)).is_real is True
1110
+
1111
+ assert sqrt(-1 - sqrt(2)).is_real is False
1112
+
1113
+ i = Symbol('i', imaginary=True)
1114
+ assert (i**i).is_real is None
1115
+ assert (I**i).is_extended_real is True
1116
+ assert ((-I)**i).is_extended_real is True
1117
+ assert (2**i).is_real is None # (2**(pi/log(2) * I)) is real, 2**I is not
1118
+ assert (2**I).is_real is False
1119
+ assert (2**-I).is_real is False
1120
+ assert (i**2).is_extended_real is True
1121
+ assert (i**3).is_extended_real is False
1122
+ assert (i**x).is_real is None # could be (-I)**(2/3)
1123
+ e = Symbol('e', even=True)
1124
+ o = Symbol('o', odd=True)
1125
+ k = Symbol('k', integer=True)
1126
+ assert (i**e).is_extended_real is True
1127
+ assert (i**o).is_extended_real is False
1128
+ assert (i**k).is_real is None
1129
+ assert (i**(4*k)).is_extended_real is True
1130
+
1131
+ x = Symbol("x", nonnegative=True)
1132
+ y = Symbol("y", nonnegative=True)
1133
+ assert im(x**y).expand(complex=True) is S.Zero
1134
+ assert (x**y).is_real is True
1135
+ i = Symbol('i', imaginary=True)
1136
+ assert (exp(i)**I).is_extended_real is True
1137
+ assert log(exp(i)).is_imaginary is None # i could be 2*pi*I
1138
+ c = Symbol('c', complex=True)
1139
+ assert log(c).is_real is None # c could be 0 or 2, too
1140
+ assert log(exp(c)).is_real is None # log(0), log(E), ...
1141
+ n = Symbol('n', negative=False)
1142
+ assert log(n).is_real is None
1143
+ n = Symbol('n', nonnegative=True)
1144
+ assert log(n).is_real is None
1145
+
1146
+ assert sqrt(-I).is_real is False # issue 7843
1147
+
1148
+ i = Symbol('i', integer=True)
1149
+ assert (1/(i-1)).is_real is None
1150
+ assert (1/(i-1)).is_extended_real is None
1151
+
1152
+ # test issue 20715
1153
+ from sympy.core.parameters import evaluate
1154
+ x = S(-1)
1155
+ with evaluate(False):
1156
+ assert x.is_negative is True
1157
+
1158
+ f = Pow(x, -1)
1159
+ with evaluate(False):
1160
+ assert f.is_imaginary is False
1161
+
1162
+
1163
+ def test_real_Pow():
1164
+ k = Symbol('k', integer=True, nonzero=True)
1165
+ assert (k**(I*pi/log(k))).is_real
1166
+
1167
+
1168
+ def test_Pow_is_finite():
1169
+ xe = Symbol('xe', extended_real=True)
1170
+ xr = Symbol('xr', real=True)
1171
+ p = Symbol('p', positive=True)
1172
+ n = Symbol('n', negative=True)
1173
+ i = Symbol('i', integer=True)
1174
+
1175
+ assert (xe**2).is_finite is None # xe could be oo
1176
+ assert (xr**2).is_finite is True
1177
+
1178
+ assert (xe**xe).is_finite is None
1179
+ assert (xr**xe).is_finite is None
1180
+ assert (xe**xr).is_finite is None
1181
+ # FIXME: The line below should be True rather than None
1182
+ # assert (xr**xr).is_finite is True
1183
+ assert (xr**xr).is_finite is None
1184
+
1185
+ assert (p**xe).is_finite is None
1186
+ assert (p**xr).is_finite is True
1187
+
1188
+ assert (n**xe).is_finite is None
1189
+ assert (n**xr).is_finite is True
1190
+
1191
+ assert (sin(xe)**2).is_finite is True
1192
+ assert (sin(xr)**2).is_finite is True
1193
+
1194
+ assert (sin(xe)**xe).is_finite is None # xe, xr could be -pi
1195
+ assert (sin(xr)**xr).is_finite is None
1196
+
1197
+ # FIXME: Should the line below be True rather than None?
1198
+ assert (sin(xe)**exp(xe)).is_finite is None
1199
+ assert (sin(xr)**exp(xr)).is_finite is True
1200
+
1201
+ assert (1/sin(xe)).is_finite is None # if zero, no, otherwise yes
1202
+ assert (1/sin(xr)).is_finite is None
1203
+
1204
+ assert (1/exp(xe)).is_finite is None # xe could be -oo
1205
+ assert (1/exp(xr)).is_finite is True
1206
+
1207
+ assert (1/S.Pi).is_finite is True
1208
+
1209
+ assert (1/(i-1)).is_finite is None
1210
+
1211
+
1212
+ def test_Pow_is_even_odd():
1213
+ x = Symbol('x')
1214
+
1215
+ k = Symbol('k', even=True)
1216
+ n = Symbol('n', odd=True)
1217
+ m = Symbol('m', integer=True, nonnegative=True)
1218
+ p = Symbol('p', integer=True, positive=True)
1219
+
1220
+ assert ((-1)**n).is_odd
1221
+ assert ((-1)**k).is_odd
1222
+ assert ((-1)**(m - p)).is_odd
1223
+
1224
+ assert (k**2).is_even is True
1225
+ assert (n**2).is_even is False
1226
+ assert (2**k).is_even is None
1227
+ assert (x**2).is_even is None
1228
+
1229
+ assert (k**m).is_even is None
1230
+ assert (n**m).is_even is False
1231
+
1232
+ assert (k**p).is_even is True
1233
+ assert (n**p).is_even is False
1234
+
1235
+ assert (m**k).is_even is None
1236
+ assert (p**k).is_even is None
1237
+
1238
+ assert (m**n).is_even is None
1239
+ assert (p**n).is_even is None
1240
+
1241
+ assert (k**x).is_even is None
1242
+ assert (n**x).is_even is None
1243
+
1244
+ assert (k**2).is_odd is False
1245
+ assert (n**2).is_odd is True
1246
+ assert (3**k).is_odd is None
1247
+
1248
+ assert (k**m).is_odd is None
1249
+ assert (n**m).is_odd is True
1250
+
1251
+ assert (k**p).is_odd is False
1252
+ assert (n**p).is_odd is True
1253
+
1254
+ assert (m**k).is_odd is None
1255
+ assert (p**k).is_odd is None
1256
+
1257
+ assert (m**n).is_odd is None
1258
+ assert (p**n).is_odd is None
1259
+
1260
+ assert (k**x).is_odd is None
1261
+ assert (n**x).is_odd is None
1262
+
1263
+
1264
+ def test_Pow_is_negative_positive():
1265
+ r = Symbol('r', real=True)
1266
+
1267
+ k = Symbol('k', integer=True, positive=True)
1268
+ n = Symbol('n', even=True)
1269
+ m = Symbol('m', odd=True)
1270
+
1271
+ x = Symbol('x')
1272
+
1273
+ assert (2**r).is_positive is True
1274
+ assert ((-2)**r).is_positive is None
1275
+ assert ((-2)**n).is_positive is True
1276
+ assert ((-2)**m).is_positive is False
1277
+
1278
+ assert (k**2).is_positive is True
1279
+ assert (k**(-2)).is_positive is True
1280
+
1281
+ assert (k**r).is_positive is True
1282
+ assert ((-k)**r).is_positive is None
1283
+ assert ((-k)**n).is_positive is True
1284
+ assert ((-k)**m).is_positive is False
1285
+
1286
+ assert (2**r).is_negative is False
1287
+ assert ((-2)**r).is_negative is None
1288
+ assert ((-2)**n).is_negative is False
1289
+ assert ((-2)**m).is_negative is True
1290
+
1291
+ assert (k**2).is_negative is False
1292
+ assert (k**(-2)).is_negative is False
1293
+
1294
+ assert (k**r).is_negative is False
1295
+ assert ((-k)**r).is_negative is None
1296
+ assert ((-k)**n).is_negative is False
1297
+ assert ((-k)**m).is_negative is True
1298
+
1299
+ assert (2**x).is_positive is None
1300
+ assert (2**x).is_negative is None
1301
+
1302
+
1303
+ def test_Pow_is_zero():
1304
+ z = Symbol('z', zero=True)
1305
+ e = z**2
1306
+ assert e.is_zero
1307
+ assert e.is_positive is False
1308
+ assert e.is_negative is False
1309
+
1310
+ assert Pow(0, 0, evaluate=False).is_zero is False
1311
+ assert Pow(0, 3, evaluate=False).is_zero
1312
+ assert Pow(0, oo, evaluate=False).is_zero
1313
+ assert Pow(0, -3, evaluate=False).is_zero is False
1314
+ assert Pow(0, -oo, evaluate=False).is_zero is False
1315
+ assert Pow(2, 2, evaluate=False).is_zero is False
1316
+
1317
+ a = Symbol('a', zero=False)
1318
+ assert Pow(a, 3).is_zero is False # issue 7965
1319
+
1320
+ assert Pow(2, oo, evaluate=False).is_zero is False
1321
+ assert Pow(2, -oo, evaluate=False).is_zero
1322
+ assert Pow(S.Half, oo, evaluate=False).is_zero
1323
+ assert Pow(S.Half, -oo, evaluate=False).is_zero is False
1324
+
1325
+ # All combinations of real/complex base/exponent
1326
+ h = S.Half
1327
+ T = True
1328
+ F = False
1329
+ N = None
1330
+
1331
+ pow_iszero = [
1332
+ ['**', 0, h, 1, 2, -h, -1,-2,-2*I,-I/2,I/2,1+I,oo,-oo,zoo],
1333
+ [ 0, F, T, T, T, F, F, F, F, F, F, N, T, F, N],
1334
+ [ h, F, F, F, F, F, F, F, F, F, F, F, T, F, N],
1335
+ [ 1, F, F, F, F, F, F, F, F, F, F, F, F, F, N],
1336
+ [ 2, F, F, F, F, F, F, F, F, F, F, F, F, T, N],
1337
+ [ -h, F, F, F, F, F, F, F, F, F, F, F, T, F, N],
1338
+ [ -1, F, F, F, F, F, F, F, F, F, F, F, F, F, N],
1339
+ [ -2, F, F, F, F, F, F, F, F, F, F, F, F, T, N],
1340
+ [-2*I, F, F, F, F, F, F, F, F, F, F, F, F, T, N],
1341
+ [-I/2, F, F, F, F, F, F, F, F, F, F, F, T, F, N],
1342
+ [ I/2, F, F, F, F, F, F, F, F, F, F, F, T, F, N],
1343
+ [ 1+I, F, F, F, F, F, F, F, F, F, F, F, F, T, N],
1344
+ [ oo, F, F, F, F, T, T, T, F, F, F, F, F, T, N],
1345
+ [ -oo, F, F, F, F, T, T, T, F, F, F, F, F, T, N],
1346
+ [ zoo, F, F, F, F, T, T, T, N, N, N, N, F, T, N]
1347
+ ]
1348
+
1349
+ def test_table(table):
1350
+ n = len(table[0])
1351
+ for row in range(1, n):
1352
+ base = table[row][0]
1353
+ for col in range(1, n):
1354
+ exp = table[0][col]
1355
+ is_zero = table[row][col]
1356
+ # The actual test here:
1357
+ assert Pow(base, exp, evaluate=False).is_zero is is_zero
1358
+
1359
+ test_table(pow_iszero)
1360
+
1361
+ # A zero symbol...
1362
+ zo, zo2 = symbols('zo, zo2', zero=True)
1363
+
1364
+ # All combinations of finite symbols
1365
+ zf, zf2 = symbols('zf, zf2', finite=True)
1366
+ wf, wf2 = symbols('wf, wf2', nonzero=True)
1367
+ xf, xf2 = symbols('xf, xf2', real=True)
1368
+ yf, yf2 = symbols('yf, yf2', nonzero=True)
1369
+ af, af2 = symbols('af, af2', positive=True)
1370
+ bf, bf2 = symbols('bf, bf2', nonnegative=True)
1371
+ cf, cf2 = symbols('cf, cf2', negative=True)
1372
+ df, df2 = symbols('df, df2', nonpositive=True)
1373
+
1374
+ # Without finiteness:
1375
+ zi, zi2 = symbols('zi, zi2')
1376
+ wi, wi2 = symbols('wi, wi2', zero=False)
1377
+ xi, xi2 = symbols('xi, xi2', extended_real=True)
1378
+ yi, yi2 = symbols('yi, yi2', zero=False, extended_real=True)
1379
+ ai, ai2 = symbols('ai, ai2', extended_positive=True)
1380
+ bi, bi2 = symbols('bi, bi2', extended_nonnegative=True)
1381
+ ci, ci2 = symbols('ci, ci2', extended_negative=True)
1382
+ di, di2 = symbols('di, di2', extended_nonpositive=True)
1383
+
1384
+ pow_iszero_sym = [
1385
+ ['**',zo,wf,yf,af,cf,zf,xf,bf,df,zi,wi,xi,yi,ai,bi,ci,di],
1386
+ [ zo2, F, N, N, T, F, N, N, N, F, N, N, N, N, T, N, F, F],
1387
+ [ wf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N],
1388
+ [ yf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N],
1389
+ [ af2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N],
1390
+ [ cf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N],
1391
+ [ zf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N],
1392
+ [ xf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N],
1393
+ [ bf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N],
1394
+ [ df2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N],
1395
+ [ zi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N],
1396
+ [ wi2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N],
1397
+ [ xi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N],
1398
+ [ yi2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N],
1399
+ [ ai2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N],
1400
+ [ bi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N],
1401
+ [ ci2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N],
1402
+ [ di2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N]
1403
+ ]
1404
+
1405
+ test_table(pow_iszero_sym)
1406
+
1407
+ # In some cases (x**x).is_zero is different from (x**y).is_zero even if y
1408
+ # has the same assumptions as x.
1409
+ assert (zo ** zo).is_zero is False
1410
+ assert (wf ** wf).is_zero is False
1411
+ assert (yf ** yf).is_zero is False
1412
+ assert (af ** af).is_zero is False
1413
+ assert (cf ** cf).is_zero is False
1414
+ assert (zf ** zf).is_zero is None
1415
+ assert (xf ** xf).is_zero is None
1416
+ assert (bf ** bf).is_zero is False # None in table
1417
+ assert (df ** df).is_zero is None
1418
+ assert (zi ** zi).is_zero is None
1419
+ assert (wi ** wi).is_zero is None
1420
+ assert (xi ** xi).is_zero is None
1421
+ assert (yi ** yi).is_zero is None
1422
+ assert (ai ** ai).is_zero is False # None in table
1423
+ assert (bi ** bi).is_zero is False # None in table
1424
+ assert (ci ** ci).is_zero is None
1425
+ assert (di ** di).is_zero is None
1426
+
1427
+
1428
+ def test_Pow_is_nonpositive_nonnegative():
1429
+ x = Symbol('x', real=True)
1430
+
1431
+ k = Symbol('k', integer=True, nonnegative=True)
1432
+ l = Symbol('l', integer=True, positive=True)
1433
+ n = Symbol('n', even=True)
1434
+ m = Symbol('m', odd=True)
1435
+
1436
+ assert (x**(4*k)).is_nonnegative is True
1437
+ assert (2**x).is_nonnegative is True
1438
+ assert ((-2)**x).is_nonnegative is None
1439
+ assert ((-2)**n).is_nonnegative is True
1440
+ assert ((-2)**m).is_nonnegative is False
1441
+
1442
+ assert (k**2).is_nonnegative is True
1443
+ assert (k**(-2)).is_nonnegative is None
1444
+ assert (k**k).is_nonnegative is True
1445
+
1446
+ assert (k**x).is_nonnegative is None # NOTE (0**x).is_real = U
1447
+ assert (l**x).is_nonnegative is True
1448
+ assert (l**x).is_positive is True
1449
+ assert ((-k)**x).is_nonnegative is None
1450
+
1451
+ assert ((-k)**m).is_nonnegative is None
1452
+
1453
+ assert (2**x).is_nonpositive is False
1454
+ assert ((-2)**x).is_nonpositive is None
1455
+ assert ((-2)**n).is_nonpositive is False
1456
+ assert ((-2)**m).is_nonpositive is True
1457
+
1458
+ assert (k**2).is_nonpositive is None
1459
+ assert (k**(-2)).is_nonpositive is None
1460
+
1461
+ assert (k**x).is_nonpositive is None
1462
+ assert ((-k)**x).is_nonpositive is None
1463
+ assert ((-k)**n).is_nonpositive is None
1464
+
1465
+
1466
+ assert (x**2).is_nonnegative is True
1467
+ i = symbols('i', imaginary=True)
1468
+ assert (i**2).is_nonpositive is True
1469
+ assert (i**4).is_nonpositive is False
1470
+ assert (i**3).is_nonpositive is False
1471
+ assert (I**i).is_nonnegative is True
1472
+ assert (exp(I)**i).is_nonnegative is True
1473
+
1474
+ assert ((-l)**n).is_nonnegative is True
1475
+ assert ((-l)**m).is_nonpositive is True
1476
+ assert ((-k)**n).is_nonnegative is None
1477
+ assert ((-k)**m).is_nonpositive is None
1478
+
1479
+
1480
+ def test_Mul_is_imaginary_real():
1481
+ r = Symbol('r', real=True)
1482
+ p = Symbol('p', positive=True)
1483
+ i1 = Symbol('i1', imaginary=True)
1484
+ i2 = Symbol('i2', imaginary=True)
1485
+ x = Symbol('x')
1486
+
1487
+ assert I.is_imaginary is True
1488
+ assert I.is_real is False
1489
+ assert (-I).is_imaginary is True
1490
+ assert (-I).is_real is False
1491
+ assert (3*I).is_imaginary is True
1492
+ assert (3*I).is_real is False
1493
+ assert (I*I).is_imaginary is False
1494
+ assert (I*I).is_real is True
1495
+
1496
+ e = (p + p*I)
1497
+ j = Symbol('j', integer=True, zero=False)
1498
+ assert (e**j).is_real is None
1499
+ assert (e**(2*j)).is_real is None
1500
+ assert (e**j).is_imaginary is None
1501
+ assert (e**(2*j)).is_imaginary is None
1502
+
1503
+ assert (e**-1).is_imaginary is False
1504
+ assert (e**2).is_imaginary
1505
+ assert (e**3).is_imaginary is False
1506
+ assert (e**4).is_imaginary is False
1507
+ assert (e**5).is_imaginary is False
1508
+ assert (e**-1).is_real is False
1509
+ assert (e**2).is_real is False
1510
+ assert (e**3).is_real is False
1511
+ assert (e**4).is_real is True
1512
+ assert (e**5).is_real is False
1513
+ assert (e**3).is_complex
1514
+
1515
+ assert (r*i1).is_imaginary is None
1516
+ assert (r*i1).is_real is None
1517
+
1518
+ assert (x*i1).is_imaginary is None
1519
+ assert (x*i1).is_real is None
1520
+
1521
+ assert (i1*i2).is_imaginary is False
1522
+ assert (i1*i2).is_real is True
1523
+
1524
+ assert (r*i1*i2).is_imaginary is False
1525
+ assert (r*i1*i2).is_real is True
1526
+
1527
+ # Github's issue 5874:
1528
+ nr = Symbol('nr', real=False, complex=True) # e.g. I or 1 + I
1529
+ a = Symbol('a', real=True, nonzero=True)
1530
+ b = Symbol('b', real=True)
1531
+ assert (i1*nr).is_real is None
1532
+ assert (a*nr).is_real is False
1533
+ assert (b*nr).is_real is None
1534
+
1535
+ ni = Symbol('ni', imaginary=False, complex=True) # e.g. 2 or 1 + I
1536
+ a = Symbol('a', real=True, nonzero=True)
1537
+ b = Symbol('b', real=True)
1538
+ assert (i1*ni).is_real is False
1539
+ assert (a*ni).is_real is None
1540
+ assert (b*ni).is_real is None
1541
+
1542
+
1543
+ def test_Mul_hermitian_antihermitian():
1544
+ xz, yz = symbols('xz, yz', zero=True, antihermitian=True)
1545
+ xf, yf = symbols('xf, yf', hermitian=False, antihermitian=False, finite=True)
1546
+ xh, yh = symbols('xh, yh', hermitian=True, antihermitian=False, nonzero=True)
1547
+ xa, ya = symbols('xa, ya', hermitian=False, antihermitian=True, zero=False, finite=True)
1548
+ assert (xz*xh).is_hermitian is True
1549
+ assert (xz*xh).is_antihermitian is True
1550
+ assert (xz*xa).is_hermitian is True
1551
+ assert (xz*xa).is_antihermitian is True
1552
+ assert (xf*yf).is_hermitian is None
1553
+ assert (xf*yf).is_antihermitian is None
1554
+ assert (xh*yh).is_hermitian is True
1555
+ assert (xh*yh).is_antihermitian is False
1556
+ assert (xh*ya).is_hermitian is False
1557
+ assert (xh*ya).is_antihermitian is True
1558
+ assert (xa*ya).is_hermitian is True
1559
+ assert (xa*ya).is_antihermitian is False
1560
+
1561
+ a = Symbol('a', hermitian=True, zero=False)
1562
+ b = Symbol('b', hermitian=True)
1563
+ c = Symbol('c', hermitian=False)
1564
+ d = Symbol('d', antihermitian=True)
1565
+ e1 = Mul(a, b, c, evaluate=False)
1566
+ e2 = Mul(b, a, c, evaluate=False)
1567
+ e3 = Mul(a, b, c, d, evaluate=False)
1568
+ e4 = Mul(b, a, c, d, evaluate=False)
1569
+ e5 = Mul(a, c, evaluate=False)
1570
+ e6 = Mul(a, c, d, evaluate=False)
1571
+ assert e1.is_hermitian is None
1572
+ assert e2.is_hermitian is None
1573
+ assert e1.is_antihermitian is None
1574
+ assert e2.is_antihermitian is None
1575
+ assert e3.is_antihermitian is None
1576
+ assert e4.is_antihermitian is None
1577
+ assert e5.is_antihermitian is None
1578
+ assert e6.is_antihermitian is None
1579
+
1580
+
1581
+ def test_Add_is_comparable():
1582
+ assert (x + y).is_comparable is False
1583
+ assert (x + 1).is_comparable is False
1584
+ assert (Rational(1, 3) - sqrt(8)).is_comparable is True
1585
+
1586
+
1587
+ def test_Mul_is_comparable():
1588
+ assert (x*y).is_comparable is False
1589
+ assert (x*2).is_comparable is False
1590
+ assert (sqrt(2)*Rational(1, 3)).is_comparable is True
1591
+
1592
+
1593
+ def test_Pow_is_comparable():
1594
+ assert (x**y).is_comparable is False
1595
+ assert (x**2).is_comparable is False
1596
+ assert (sqrt(Rational(1, 3))).is_comparable is True
1597
+
1598
+
1599
+ def test_Add_is_positive_2():
1600
+ e = Rational(1, 3) - sqrt(8)
1601
+ assert e.is_positive is False
1602
+ assert e.is_negative is True
1603
+
1604
+ e = pi - 1
1605
+ assert e.is_positive is True
1606
+ assert e.is_negative is False
1607
+
1608
+
1609
+ def test_Add_is_irrational():
1610
+ i = Symbol('i', irrational=True)
1611
+
1612
+ assert i.is_irrational is True
1613
+ assert i.is_rational is False
1614
+
1615
+ assert (i + 1).is_irrational is True
1616
+ assert (i + 1).is_rational is False
1617
+
1618
+
1619
+ def test_Mul_is_irrational():
1620
+ expr = Mul(1, 2, 3, evaluate=False)
1621
+ assert expr.is_irrational is False
1622
+ expr = Mul(1, I, I, evaluate=False)
1623
+ assert expr.is_rational is None # I * I = -1 but *no evaluation allowed*
1624
+ # sqrt(2) * I * I = -sqrt(2) is irrational but
1625
+ # this can't be determined without evaluating the
1626
+ # expression and the eval_is routines shouldn't do that
1627
+ expr = Mul(sqrt(2), I, I, evaluate=False)
1628
+ assert expr.is_irrational is None
1629
+
1630
+
1631
+ def test_issue_3531():
1632
+ # https://github.com/sympy/sympy/issues/3531
1633
+ # https://github.com/sympy/sympy/pull/18116
1634
+ class MightyNumeric(tuple):
1635
+ def __rtruediv__(self, other):
1636
+ return "something"
1637
+
1638
+ assert sympify(1)/MightyNumeric((1, 2)) == "something"
1639
+
1640
+
1641
+ def test_issue_3531b():
1642
+ class Foo:
1643
+ def __init__(self):
1644
+ self.field = 1.0
1645
+
1646
+ def __mul__(self, other):
1647
+ self.field = self.field * other
1648
+
1649
+ def __rmul__(self, other):
1650
+ self.field = other * self.field
1651
+ f = Foo()
1652
+ x = Symbol("x")
1653
+ assert f*x == x*f
1654
+
1655
+
1656
+ def test_bug3():
1657
+ a = Symbol("a")
1658
+ b = Symbol("b", positive=True)
1659
+ e = 2*a + b
1660
+ f = b + 2*a
1661
+ assert e == f
1662
+
1663
+
1664
+ def test_suppressed_evaluation():
1665
+ a = Add(0, 3, 2, evaluate=False)
1666
+ b = Mul(1, 3, 2, evaluate=False)
1667
+ c = Pow(3, 2, evaluate=False)
1668
+ assert a != 6
1669
+ assert a.func is Add
1670
+ assert a.args == (0, 3, 2)
1671
+ assert b != 6
1672
+ assert b.func is Mul
1673
+ assert b.args == (1, 3, 2)
1674
+ assert c != 9
1675
+ assert c.func is Pow
1676
+ assert c.args == (3, 2)
1677
+
1678
+
1679
+ def test_AssocOp_doit():
1680
+ a = Add(x,x, evaluate=False)
1681
+ b = Mul(y,y, evaluate=False)
1682
+ c = Add(b,b, evaluate=False)
1683
+ d = Mul(a,a, evaluate=False)
1684
+ assert c.doit(deep=False).func == Mul
1685
+ assert c.doit(deep=False).args == (2,y,y)
1686
+ assert c.doit().func == Mul
1687
+ assert c.doit().args == (2, Pow(y,2))
1688
+ assert d.doit(deep=False).func == Pow
1689
+ assert d.doit(deep=False).args == (a, 2*S.One)
1690
+ assert d.doit().func == Mul
1691
+ assert d.doit().args == (4*S.One, Pow(x,2))
1692
+
1693
+
1694
+ def test_Add_Mul_Expr_args():
1695
+ nonexpr = [Basic(), Poly(x, x), FiniteSet(x)]
1696
+ for typ in [Add, Mul]:
1697
+ for obj in nonexpr:
1698
+ # The cache can mess with the stacklevel check
1699
+ with warns(SymPyDeprecationWarning, test_stacklevel=False):
1700
+ typ(obj, 1)
1701
+
1702
+
1703
+ def test_Add_as_coeff_mul():
1704
+ # issue 5524. These should all be (1, self)
1705
+ assert (x + 1).as_coeff_mul() == (1, (x + 1,))
1706
+ assert (x + 2).as_coeff_mul() == (1, (x + 2,))
1707
+ assert (x + 3).as_coeff_mul() == (1, (x + 3,))
1708
+
1709
+ assert (x - 1).as_coeff_mul() == (1, (x - 1,))
1710
+ assert (x - 2).as_coeff_mul() == (1, (x - 2,))
1711
+ assert (x - 3).as_coeff_mul() == (1, (x - 3,))
1712
+
1713
+ n = Symbol('n', integer=True)
1714
+ assert (n + 1).as_coeff_mul() == (1, (n + 1,))
1715
+ assert (n + 2).as_coeff_mul() == (1, (n + 2,))
1716
+ assert (n + 3).as_coeff_mul() == (1, (n + 3,))
1717
+
1718
+ assert (n - 1).as_coeff_mul() == (1, (n - 1,))
1719
+ assert (n - 2).as_coeff_mul() == (1, (n - 2,))
1720
+ assert (n - 3).as_coeff_mul() == (1, (n - 3,))
1721
+
1722
+
1723
+ def test_Pow_as_coeff_mul_doesnt_expand():
1724
+ assert exp(x + y).as_coeff_mul() == (1, (exp(x + y),))
1725
+ assert exp(x + exp(x + y)) != exp(x + exp(x)*exp(y))
1726
+
1727
+ def test_issue_24751():
1728
+ expr = Add(-2, -3, evaluate=False)
1729
+ expr1 = Add(-1, expr, evaluate=False)
1730
+ assert int(expr1) == int((-3 - 2) - 1)
1731
+
1732
+
1733
+ def test_issue_3514_18626():
1734
+ assert sqrt(S.Half) * sqrt(6) == 2 * sqrt(3)/2
1735
+ assert S.Half*sqrt(6)*sqrt(2) == sqrt(3)
1736
+ assert sqrt(6)/2*sqrt(2) == sqrt(3)
1737
+ assert sqrt(6)*sqrt(2)/2 == sqrt(3)
1738
+ assert sqrt(8)**Rational(2, 3) == 2
1739
+
1740
+
1741
+ def test_make_args():
1742
+ assert Add.make_args(x) == (x,)
1743
+ assert Mul.make_args(x) == (x,)
1744
+
1745
+ assert Add.make_args(x*y*z) == (x*y*z,)
1746
+ assert Mul.make_args(x*y*z) == (x*y*z).args
1747
+
1748
+ assert Add.make_args(x + y + z) == (x + y + z).args
1749
+ assert Mul.make_args(x + y + z) == (x + y + z,)
1750
+
1751
+ assert Add.make_args((x + y)**z) == ((x + y)**z,)
1752
+ assert Mul.make_args((x + y)**z) == ((x + y)**z,)
1753
+
1754
+
1755
+ def test_issue_5126():
1756
+ assert (-2)**x*(-3)**x != 6**x
1757
+ i = Symbol('i', integer=1)
1758
+ assert (-2)**i*(-3)**i == 6**i
1759
+
1760
+
1761
+ def test_Rational_as_content_primitive():
1762
+ c, p = S.One, S.Zero
1763
+ assert (c*p).as_content_primitive() == (c, p)
1764
+ c, p = S.Half, S.One
1765
+ assert (c*p).as_content_primitive() == (c, p)
1766
+
1767
+
1768
+ def test_Add_as_content_primitive():
1769
+ assert (x + 2).as_content_primitive() == (1, x + 2)
1770
+
1771
+ assert (3*x + 2).as_content_primitive() == (1, 3*x + 2)
1772
+ assert (3*x + 3).as_content_primitive() == (3, x + 1)
1773
+ assert (3*x + 6).as_content_primitive() == (3, x + 2)
1774
+
1775
+ assert (3*x + 2*y).as_content_primitive() == (1, 3*x + 2*y)
1776
+ assert (3*x + 3*y).as_content_primitive() == (3, x + y)
1777
+ assert (3*x + 6*y).as_content_primitive() == (3, x + 2*y)
1778
+
1779
+ assert (3/x + 2*x*y*z**2).as_content_primitive() == (1, 3/x + 2*x*y*z**2)
1780
+ assert (3/x + 3*x*y*z**2).as_content_primitive() == (3, 1/x + x*y*z**2)
1781
+ assert (3/x + 6*x*y*z**2).as_content_primitive() == (3, 1/x + 2*x*y*z**2)
1782
+
1783
+ assert (2*x/3 + 4*y/9).as_content_primitive() == \
1784
+ (Rational(2, 9), 3*x + 2*y)
1785
+ assert (2*x/3 + 2.5*y).as_content_primitive() == \
1786
+ (Rational(1, 3), 2*x + 7.5*y)
1787
+
1788
+ # the coefficient may sort to a position other than 0
1789
+ p = 3 + x + y
1790
+ assert (2*p).expand().as_content_primitive() == (2, p)
1791
+ assert (2.0*p).expand().as_content_primitive() == (1, 2.*p)
1792
+ p *= -1
1793
+ assert (2*p).expand().as_content_primitive() == (2, p)
1794
+
1795
+
1796
+ def test_Mul_as_content_primitive():
1797
+ assert (2*x).as_content_primitive() == (2, x)
1798
+ assert (x*(2 + 2*x)).as_content_primitive() == (2, x*(1 + x))
1799
+ assert (x*(2 + 2*y)*(3*x + 3)**2).as_content_primitive() == \
1800
+ (18, x*(1 + y)*(x + 1)**2)
1801
+ assert ((2 + 2*x)**2*(3 + 6*x) + S.Half).as_content_primitive() == \
1802
+ (S.Half, 24*(x + 1)**2*(2*x + 1) + 1)
1803
+
1804
+
1805
+ def test_Pow_as_content_primitive():
1806
+ assert (x**y).as_content_primitive() == (1, x**y)
1807
+ assert ((2*x + 2)**y).as_content_primitive() == \
1808
+ (1, (Mul(2, (x + 1), evaluate=False))**y)
1809
+ assert ((2*x + 2)**3).as_content_primitive() == (8, (x + 1)**3)
1810
+
1811
+
1812
+ def test_issue_5460():
1813
+ u = Mul(2, (1 + x), evaluate=False)
1814
+ assert (2 + u).args == (2, u)
1815
+
1816
+
1817
+ def test_product_irrational():
1818
+ assert (I*pi).is_irrational is False
1819
+ # The following used to be deduced from the above bug:
1820
+ assert (I*pi).is_positive is False
1821
+
1822
+
1823
+ def test_issue_5919():
1824
+ assert (x/(y*(1 + y))).expand() == x/(y**2 + y)
1825
+
1826
+
1827
+ def test_Mod():
1828
+ assert Mod(x, 1).func is Mod
1829
+ assert pi % pi is S.Zero
1830
+ assert Mod(5, 3) == 2
1831
+ assert Mod(-5, 3) == 1
1832
+ assert Mod(5, -3) == -1
1833
+ assert Mod(-5, -3) == -2
1834
+ assert type(Mod(3.2, 2, evaluate=False)) == Mod
1835
+ assert 5 % x == Mod(5, x)
1836
+ assert x % 5 == Mod(x, 5)
1837
+ assert x % y == Mod(x, y)
1838
+ assert (x % y).subs({x: 5, y: 3}) == 2
1839
+ assert Mod(nan, 1) is nan
1840
+ assert Mod(1, nan) is nan
1841
+ assert Mod(nan, nan) is nan
1842
+
1843
+ assert Mod(0, x) == 0
1844
+ with raises(ZeroDivisionError):
1845
+ Mod(x, 0)
1846
+
1847
+ k = Symbol('k', integer=True)
1848
+ m = Symbol('m', integer=True, positive=True)
1849
+ assert (x**m % x).func is Mod
1850
+ assert (k**(-m) % k).func is Mod
1851
+ assert k**m % k == 0
1852
+ assert (-2*k)**m % k == 0
1853
+
1854
+ # Float handling
1855
+ point3 = Float(3.3) % 1
1856
+ assert (x - 3.3) % 1 == Mod(1.*x + 1 - point3, 1)
1857
+ assert Mod(-3.3, 1) == 1 - point3
1858
+ assert Mod(0.7, 1) == Float(0.7)
1859
+ e = Mod(1.3, 1)
1860
+ assert comp(e, .3) and e.is_Float
1861
+ e = Mod(1.3, .7)
1862
+ assert comp(e, .6) and e.is_Float
1863
+ e = Mod(1.3, Rational(7, 10))
1864
+ assert comp(e, .6) and e.is_Float
1865
+ e = Mod(Rational(13, 10), 0.7)
1866
+ assert comp(e, .6) and e.is_Float
1867
+ e = Mod(Rational(13, 10), Rational(7, 10))
1868
+ assert comp(e, .6) and e.is_Rational
1869
+
1870
+ # check that sign is right
1871
+ r2 = sqrt(2)
1872
+ r3 = sqrt(3)
1873
+ for i in [-r3, -r2, r2, r3]:
1874
+ for j in [-r3, -r2, r2, r3]:
1875
+ assert verify_numerically(i % j, i.n() % j.n())
1876
+ for _x in range(4):
1877
+ for _y in range(9):
1878
+ reps = [(x, _x), (y, _y)]
1879
+ assert Mod(3*x + y, 9).subs(reps) == (3*_x + _y) % 9
1880
+
1881
+ # denesting
1882
+ t = Symbol('t', real=True)
1883
+ assert Mod(Mod(x, t), t) == Mod(x, t)
1884
+ assert Mod(-Mod(x, t), t) == Mod(-x, t)
1885
+ assert Mod(Mod(x, 2*t), t) == Mod(x, t)
1886
+ assert Mod(-Mod(x, 2*t), t) == Mod(-x, t)
1887
+ assert Mod(Mod(x, t), 2*t) == Mod(x, t)
1888
+ assert Mod(-Mod(x, t), -2*t) == -Mod(x, t)
1889
+ for i in [-4, -2, 2, 4]:
1890
+ for j in [-4, -2, 2, 4]:
1891
+ for k in range(4):
1892
+ assert Mod(Mod(x, i), j).subs({x: k}) == (k % i) % j
1893
+ assert Mod(-Mod(x, i), j).subs({x: k}) == -(k % i) % j
1894
+
1895
+ # known difference
1896
+ assert Mod(5*sqrt(2), sqrt(5)) == 5*sqrt(2) - 3*sqrt(5)
1897
+ p = symbols('p', positive=True)
1898
+ assert Mod(2, p + 3) == 2
1899
+ assert Mod(-2, p + 3) == p + 1
1900
+ assert Mod(2, -p - 3) == -p - 1
1901
+ assert Mod(-2, -p - 3) == -2
1902
+ assert Mod(p + 5, p + 3) == 2
1903
+ assert Mod(-p - 5, p + 3) == p + 1
1904
+ assert Mod(p + 5, -p - 3) == -p - 1
1905
+ assert Mod(-p - 5, -p - 3) == -2
1906
+ assert Mod(p + 1, p - 1).func is Mod
1907
+
1908
+ # handling sums
1909
+ assert (x + 3) % 1 == Mod(x, 1)
1910
+ assert (x + 3.0) % 1 == Mod(1.*x, 1)
1911
+ assert (x - S(33)/10) % 1 == Mod(x + S(7)/10, 1)
1912
+
1913
+ a = Mod(.6*x + y, .3*y)
1914
+ b = Mod(0.1*y + 0.6*x, 0.3*y)
1915
+ # Test that a, b are equal, with 1e-14 accuracy in coefficients
1916
+ eps = 1e-14
1917
+ assert abs((a.args[0] - b.args[0]).subs({x: 1, y: 1})) < eps
1918
+ assert abs((a.args[1] - b.args[1]).subs({x: 1, y: 1})) < eps
1919
+
1920
+ assert (x + 1) % x == 1 % x
1921
+ assert (x + y) % x == y % x
1922
+ assert (x + y + 2) % x == (y + 2) % x
1923
+ assert (a + 3*x + 1) % (2*x) == Mod(a + x + 1, 2*x)
1924
+ assert (12*x + 18*y) % (3*x) == 3*Mod(6*y, x)
1925
+
1926
+ # gcd extraction
1927
+ assert (-3*x) % (-2*y) == -Mod(3*x, 2*y)
1928
+ assert (.6*pi) % (.3*x*pi) == 0.3*pi*Mod(2, x)
1929
+ assert (.6*pi) % (.31*x*pi) == pi*Mod(0.6, 0.31*x)
1930
+ assert (6*pi) % (.3*x*pi) == 0.3*pi*Mod(20, x)
1931
+ assert (6*pi) % (.31*x*pi) == pi*Mod(6, 0.31*x)
1932
+ assert (6*pi) % (.42*x*pi) == pi*Mod(6, 0.42*x)
1933
+ assert (12*x) % (2*y) == 2*Mod(6*x, y)
1934
+ assert (12*x) % (3*5*y) == 3*Mod(4*x, 5*y)
1935
+ assert (12*x) % (15*x*y) == 3*x*Mod(4, 5*y)
1936
+ assert (-2*pi) % (3*pi) == pi
1937
+ assert (2*x + 2) % (x + 1) == 0
1938
+ assert (x*(x + 1)) % (x + 1) == (x + 1)*Mod(x, 1)
1939
+ assert Mod(5.0*x, 0.1*y) == 0.1*Mod(50*x, y)
1940
+ i = Symbol('i', integer=True)
1941
+ assert (3*i*x) % (2*i*y) == i*Mod(3*x, 2*y)
1942
+ assert Mod(4*i, 4) == 0
1943
+
1944
+ # issue 8677
1945
+ n = Symbol('n', integer=True, positive=True)
1946
+ assert factorial(n) % n == 0
1947
+ assert factorial(n + 2) % n == 0
1948
+ assert (factorial(n + 4) % (n + 5)).func is Mod
1949
+
1950
+ # Wilson's theorem
1951
+ assert factorial(18042, evaluate=False) % 18043 == 18042
1952
+ p = Symbol('n', prime=True)
1953
+ assert factorial(p - 1) % p == p - 1
1954
+ assert factorial(p - 1) % -p == -1
1955
+ assert (factorial(3, evaluate=False) % 4).doit() == 2
1956
+ n = Symbol('n', composite=True, odd=True)
1957
+ assert factorial(n - 1) % n == 0
1958
+
1959
+ # symbolic with known parity
1960
+ n = Symbol('n', even=True)
1961
+ assert Mod(n, 2) == 0
1962
+ n = Symbol('n', odd=True)
1963
+ assert Mod(n, 2) == 1
1964
+
1965
+ # issue 10963
1966
+ assert (x**6000%400).args[1] == 400
1967
+
1968
+ #issue 13543
1969
+ assert Mod(Mod(x + 1, 2) + 1, 2) == Mod(x, 2)
1970
+
1971
+ x1 = Symbol('x1', integer=True)
1972
+ assert Mod(Mod(x1 + 2, 4)*(x1 + 4), 4) == Mod(x1*(x1 + 2), 4)
1973
+ assert Mod(Mod(x1 + 2, 4)*4, 4) == 0
1974
+
1975
+ # issue 15493
1976
+ i, j = symbols('i j', integer=True, positive=True)
1977
+ assert Mod(3*i, 2) == Mod(i, 2)
1978
+ assert Mod(8*i/j, 4) == 4*Mod(2*i/j, 1)
1979
+ assert Mod(8*i, 4) == 0
1980
+
1981
+ # rewrite
1982
+ assert Mod(x, y).rewrite(floor) == x - y*floor(x/y)
1983
+ assert ((x - Mod(x, y))/y).rewrite(floor) == floor(x/y)
1984
+
1985
+ # issue 21373
1986
+ from sympy.functions.elementary.hyperbolic import sinh
1987
+ from sympy.functions.elementary.piecewise import Piecewise
1988
+
1989
+ x_r, y_r = symbols('x_r y_r', real=True)
1990
+ assert (Piecewise((x_r, y_r > x_r), (y_r, True)) / z) % 1
1991
+ expr = exp(sinh(Piecewise((x_r, y_r > x_r), (y_r, True)) / z))
1992
+ expr.subs({1: 1.0})
1993
+ sinh(Piecewise((x_r, y_r > x_r), (y_r, True)) * z ** -1.0).is_zero
1994
+
1995
+ # issue 24215
1996
+ from sympy.abc import phi
1997
+ assert Mod(4.0*Mod(phi, 1) , 2) == 2.0*(Mod(2*(Mod(phi, 1)), 1))
1998
+
1999
+
2000
+ def test_Mod_Pow():
2001
+ # modular exponentiation
2002
+ assert isinstance(Mod(Pow(2, 2, evaluate=False), 3), Integer)
2003
+
2004
+ assert Mod(Pow(4, 13, evaluate=False), 497) == Mod(Pow(4, 13), 497)
2005
+ assert Mod(Pow(2, 10000000000, evaluate=False), 3) == 1
2006
+ assert Mod(Pow(32131231232, 9**10**6, evaluate=False),10**12) == \
2007
+ pow(32131231232,9**10**6,10**12)
2008
+ assert Mod(Pow(33284959323, 123**999, evaluate=False),11**13) == \
2009
+ pow(33284959323,123**999,11**13)
2010
+ assert Mod(Pow(78789849597, 333**555, evaluate=False),12**9) == \
2011
+ pow(78789849597,333**555,12**9)
2012
+
2013
+ # modular nested exponentiation
2014
+ expr = Pow(2, 2, evaluate=False)
2015
+ expr = Pow(2, expr, evaluate=False)
2016
+ assert Mod(expr, 3**10) == 16
2017
+ expr = Pow(2, expr, evaluate=False)
2018
+ assert Mod(expr, 3**10) == 6487
2019
+ expr = Pow(2, expr, evaluate=False)
2020
+ assert Mod(expr, 3**10) == 32191
2021
+ expr = Pow(2, expr, evaluate=False)
2022
+ assert Mod(expr, 3**10) == 18016
2023
+ expr = Pow(2, expr, evaluate=False)
2024
+ assert Mod(expr, 3**10) == 5137
2025
+
2026
+ expr = Pow(2, 2, evaluate=False)
2027
+ expr = Pow(expr, 2, evaluate=False)
2028
+ assert Mod(expr, 3**10) == 16
2029
+ expr = Pow(expr, 2, evaluate=False)
2030
+ assert Mod(expr, 3**10) == 256
2031
+ expr = Pow(expr, 2, evaluate=False)
2032
+ assert Mod(expr, 3**10) == 6487
2033
+ expr = Pow(expr, 2, evaluate=False)
2034
+ assert Mod(expr, 3**10) == 38281
2035
+ expr = Pow(expr, 2, evaluate=False)
2036
+ assert Mod(expr, 3**10) == 15928
2037
+
2038
+ expr = Pow(2, 2, evaluate=False)
2039
+ expr = Pow(expr, expr, evaluate=False)
2040
+ assert Mod(expr, 3**10) == 256
2041
+ expr = Pow(expr, expr, evaluate=False)
2042
+ assert Mod(expr, 3**10) == 9229
2043
+ expr = Pow(expr, expr, evaluate=False)
2044
+ assert Mod(expr, 3**10) == 25708
2045
+ expr = Pow(expr, expr, evaluate=False)
2046
+ assert Mod(expr, 3**10) == 26608
2047
+ expr = Pow(expr, expr, evaluate=False)
2048
+ # XXX This used to fail in a nondeterministic way because of overflow
2049
+ # error.
2050
+ assert Mod(expr, 3**10) == 1966
2051
+
2052
+
2053
+ def test_Mod_is_integer():
2054
+ p = Symbol('p', integer=True)
2055
+ q1 = Symbol('q1', integer=True)
2056
+ q2 = Symbol('q2', integer=True, nonzero=True)
2057
+ assert Mod(x, y).is_integer is None
2058
+ assert Mod(p, q1).is_integer is None
2059
+ assert Mod(x, q2).is_integer is None
2060
+ assert Mod(p, q2).is_integer
2061
+
2062
+
2063
+ def test_Mod_is_nonposneg():
2064
+ n = Symbol('n', integer=True)
2065
+ k = Symbol('k', integer=True, positive=True)
2066
+ assert (n%3).is_nonnegative
2067
+ assert Mod(n, -3).is_nonpositive
2068
+ assert Mod(n, k).is_nonnegative
2069
+ assert Mod(n, -k).is_nonpositive
2070
+ assert Mod(k, n).is_nonnegative is None
2071
+
2072
+
2073
+ def test_issue_6001():
2074
+ A = Symbol("A", commutative=False)
2075
+ eq = A + A**2
2076
+ # it doesn't matter whether it's True or False; they should
2077
+ # just all be the same
2078
+ assert (
2079
+ eq.is_commutative ==
2080
+ (eq + 1).is_commutative ==
2081
+ (A + 1).is_commutative)
2082
+
2083
+ B = Symbol("B", commutative=False)
2084
+ # Although commutative terms could cancel we return True
2085
+ # meaning "there are non-commutative symbols; aftersubstitution
2086
+ # that definition can change, e.g. (A*B).subs(B,A**-1) -> 1
2087
+ assert (sqrt(2)*A).is_commutative is False
2088
+ assert (sqrt(2)*A*B).is_commutative is False
2089
+
2090
+
2091
+ def test_polar():
2092
+ from sympy.functions.elementary.complexes import polar_lift
2093
+ p = Symbol('p', polar=True)
2094
+ x = Symbol('x')
2095
+ assert p.is_polar
2096
+ assert x.is_polar is None
2097
+ assert S.One.is_polar is None
2098
+ assert (p**x).is_polar is True
2099
+ assert (x**p).is_polar is None
2100
+ assert ((2*p)**x).is_polar is True
2101
+ assert (2*p).is_polar is True
2102
+ assert (-2*p).is_polar is not True
2103
+ assert (polar_lift(-2)*p).is_polar is True
2104
+
2105
+ q = Symbol('q', polar=True)
2106
+ assert (p*q)**2 == p**2 * q**2
2107
+ assert (2*q)**2 == 4 * q**2
2108
+ assert ((p*q)**x).expand() == p**x * q**x
2109
+
2110
+
2111
+ def test_issue_6040():
2112
+ a, b = Pow(1, 2, evaluate=False), S.One
2113
+ assert a != b
2114
+ assert b != a
2115
+ assert not (a == b)
2116
+ assert not (b == a)
2117
+
2118
+
2119
+ def test_issue_6082():
2120
+ # Comparison is symmetric
2121
+ assert Basic.compare(Max(x, 1), Max(x, 2)) == \
2122
+ - Basic.compare(Max(x, 2), Max(x, 1))
2123
+ # Equal expressions compare equal
2124
+ assert Basic.compare(Max(x, 1), Max(x, 1)) == 0
2125
+ # Basic subtypes (such as Max) compare different than standard types
2126
+ assert Basic.compare(Max(1, x), frozenset((1, x))) != 0
2127
+
2128
+
2129
+ def test_issue_6077():
2130
+ assert x**2.0/x == x**1.0
2131
+ assert x/x**2.0 == x**-1.0
2132
+ assert x*x**2.0 == x**3.0
2133
+ assert x**1.5*x**2.5 == x**4.0
2134
+
2135
+ assert 2**(2.0*x)/2**x == 2**(1.0*x)
2136
+ assert 2**x/2**(2.0*x) == 2**(-1.0*x)
2137
+ assert 2**x*2**(2.0*x) == 2**(3.0*x)
2138
+ assert 2**(1.5*x)*2**(2.5*x) == 2**(4.0*x)
2139
+
2140
+
2141
+ def test_mul_flatten_oo():
2142
+ p = symbols('p', positive=True)
2143
+ n, m = symbols('n,m', negative=True)
2144
+ x_im = symbols('x_im', imaginary=True)
2145
+ assert n*oo is -oo
2146
+ assert n*m*oo is oo
2147
+ assert p*oo is oo
2148
+ assert x_im*oo != I*oo # i could be +/- 3*I -> +/-oo
2149
+
2150
+
2151
+ def test_add_flatten():
2152
+ # see https://github.com/sympy/sympy/issues/2633#issuecomment-29545524
2153
+ a = oo + I*oo
2154
+ b = oo - I*oo
2155
+ assert a + b is nan
2156
+ assert a - b is nan
2157
+ # FIXME: This evaluates as:
2158
+ # >>> 1/a
2159
+ # 0*(oo + oo*I)
2160
+ # which should not simplify to 0. Should be fixed in Pow.eval
2161
+ #assert (1/a).simplify() == (1/b).simplify() == 0
2162
+
2163
+ a = Pow(2, 3, evaluate=False)
2164
+ assert a + a == 16
2165
+
2166
+
2167
+ def test_issue_5160_6087_6089_6090():
2168
+ # issue 6087
2169
+ assert ((-2*x*y**y)**3.2).n(2) == (2**3.2*(-x*y**y)**3.2).n(2)
2170
+ # issue 6089
2171
+ A, B, C = symbols('A,B,C', commutative=False)
2172
+ assert (2.*B*C)**3 == 8.0*(B*C)**3
2173
+ assert (-2.*B*C)**3 == -8.0*(B*C)**3
2174
+ assert (-2*B*C)**2 == 4*(B*C)**2
2175
+ # issue 5160
2176
+ assert sqrt(-1.0*x) == 1.0*sqrt(-x)
2177
+ assert sqrt(1.0*x) == 1.0*sqrt(x)
2178
+ # issue 6090
2179
+ assert (-2*x*y*A*B)**2 == 4*x**2*y**2*(A*B)**2
2180
+
2181
+
2182
+ def test_float_int_round():
2183
+ assert int(float(sqrt(10))) == int(sqrt(10))
2184
+ assert int(pi**1000) % 10 == 2
2185
+ assert int(Float('1.123456789012345678901234567890e20', '')) == \
2186
+ int(112345678901234567890)
2187
+ assert int(Float('1.123456789012345678901234567890e25', '')) == \
2188
+ int(11234567890123456789012345)
2189
+ # decimal forces float so it's not an exact integer ending in 000000
2190
+ assert int(Float('1.123456789012345678901234567890e35', '')) == \
2191
+ 112345678901234567890123456789000192
2192
+ assert int(Float('123456789012345678901234567890e5', '')) == \
2193
+ 12345678901234567890123456789000000
2194
+ assert Integer(Float('1.123456789012345678901234567890e20', '')) == \
2195
+ 112345678901234567890
2196
+ assert Integer(Float('1.123456789012345678901234567890e25', '')) == \
2197
+ 11234567890123456789012345
2198
+ # decimal forces float so it's not an exact integer ending in 000000
2199
+ assert Integer(Float('1.123456789012345678901234567890e35', '')) == \
2200
+ 112345678901234567890123456789000192
2201
+ assert Integer(Float('123456789012345678901234567890e5', '')) == \
2202
+ 12345678901234567890123456789000000
2203
+ assert same_and_same_prec(Float('123000e-2',''), Float('1230.00', ''))
2204
+ assert same_and_same_prec(Float('123000e2',''), Float('12300000', ''))
2205
+
2206
+ assert int(1 + Rational('.9999999999999999999999999')) == 1
2207
+ assert int(pi/1e20) == 0
2208
+ assert int(1 + pi/1e20) == 1
2209
+ assert int(Add(1.2, -2, evaluate=False)) == int(1.2 - 2)
2210
+ assert int(Add(1.2, +2, evaluate=False)) == int(1.2 + 2)
2211
+ assert int(Add(1 + Float('.99999999999999999', ''), evaluate=False)) == 1
2212
+ raises(TypeError, lambda: float(x))
2213
+ raises(TypeError, lambda: float(sqrt(-1)))
2214
+
2215
+ assert int(12345678901234567890 + cos(1)**2 + sin(1)**2) == \
2216
+ 12345678901234567891
2217
+
2218
+
2219
+ def test_issue_6611a():
2220
+ assert Mul.flatten([3**Rational(1, 3),
2221
+ Pow(-Rational(1, 9), Rational(2, 3), evaluate=False)]) == \
2222
+ ([Rational(1, 3), (-1)**Rational(2, 3)], [], None)
2223
+
2224
+
2225
+ def test_denest_add_mul():
2226
+ # when working with evaluated expressions make sure they denest
2227
+ eq = x + 1
2228
+ eq = Add(eq, 2, evaluate=False)
2229
+ eq = Add(eq, 2, evaluate=False)
2230
+ assert Add(*eq.args) == x + 5
2231
+ eq = x*2
2232
+ eq = Mul(eq, 2, evaluate=False)
2233
+ eq = Mul(eq, 2, evaluate=False)
2234
+ assert Mul(*eq.args) == 8*x
2235
+ # but don't let them denest unnecessarily
2236
+ eq = Mul(-2, x - 2, evaluate=False)
2237
+ assert 2*eq == Mul(-4, x - 2, evaluate=False)
2238
+ assert -eq == Mul(2, x - 2, evaluate=False)
2239
+
2240
+
2241
+ def test_mul_coeff():
2242
+ # It is important that all Numbers be removed from the seq;
2243
+ # This can be tricky when powers combine to produce those numbers
2244
+ p = exp(I*pi/3)
2245
+ assert p**2*x*p*y*p*x*p**2 == x**2*y
2246
+
2247
+
2248
+ def test_mul_zero_detection():
2249
+ nz = Dummy(real=True, zero=False)
2250
+ r = Dummy(extended_real=True)
2251
+ c = Dummy(real=False, complex=True)
2252
+ c2 = Dummy(real=False, complex=True)
2253
+ i = Dummy(imaginary=True)
2254
+ e = nz*r*c
2255
+ assert e.is_imaginary is None
2256
+ assert e.is_extended_real is None
2257
+ e = nz*c
2258
+ assert e.is_imaginary is None
2259
+ assert e.is_extended_real is False
2260
+ e = nz*i*c
2261
+ assert e.is_imaginary is False
2262
+ assert e.is_extended_real is None
2263
+ # check for more than one complex; it is important to use
2264
+ # uniquely named Symbols to ensure that two factors appear
2265
+ # e.g. if the symbols have the same name they just become
2266
+ # a single factor, a power.
2267
+ e = nz*i*c*c2
2268
+ assert e.is_imaginary is None
2269
+ assert e.is_extended_real is None
2270
+
2271
+ # _eval_is_extended_real and _eval_is_zero both employ trapping of the
2272
+ # zero value so args should be tested in both directions and
2273
+ # TO AVOID GETTING THE CACHED RESULT, Dummy MUST BE USED
2274
+
2275
+ # real is unknown
2276
+ def test(z, b, e):
2277
+ if z.is_zero and b.is_finite:
2278
+ assert e.is_extended_real and e.is_zero
2279
+ else:
2280
+ assert e.is_extended_real is None
2281
+ if b.is_finite:
2282
+ if z.is_zero:
2283
+ assert e.is_zero
2284
+ else:
2285
+ assert e.is_zero is None
2286
+ elif b.is_finite is False:
2287
+ if z.is_zero is None:
2288
+ assert e.is_zero is None
2289
+ else:
2290
+ assert e.is_zero is False
2291
+
2292
+
2293
+ for iz, ib in product(*[[True, False, None]]*2):
2294
+ z = Dummy('z', nonzero=iz)
2295
+ b = Dummy('f', finite=ib)
2296
+ e = Mul(z, b, evaluate=False)
2297
+ test(z, b, e)
2298
+ z = Dummy('nz', nonzero=iz)
2299
+ b = Dummy('f', finite=ib)
2300
+ e = Mul(b, z, evaluate=False)
2301
+ test(z, b, e)
2302
+
2303
+ # real is True
2304
+ def test(z, b, e):
2305
+ if z.is_zero and not b.is_finite:
2306
+ assert e.is_extended_real is None
2307
+ else:
2308
+ assert e.is_extended_real is True
2309
+
2310
+ for iz, ib in product(*[[True, False, None]]*2):
2311
+ z = Dummy('z', nonzero=iz, extended_real=True)
2312
+ b = Dummy('b', finite=ib, extended_real=True)
2313
+ e = Mul(z, b, evaluate=False)
2314
+ test(z, b, e)
2315
+ z = Dummy('z', nonzero=iz, extended_real=True)
2316
+ b = Dummy('b', finite=ib, extended_real=True)
2317
+ e = Mul(b, z, evaluate=False)
2318
+ test(z, b, e)
2319
+
2320
+
2321
+ def test_Mul_with_zero_infinite():
2322
+ zer = Dummy(zero=True)
2323
+ inf = Dummy(finite=False)
2324
+
2325
+ e = Mul(zer, inf, evaluate=False)
2326
+ assert e.is_extended_positive is None
2327
+ assert e.is_hermitian is None
2328
+
2329
+ e = Mul(inf, zer, evaluate=False)
2330
+ assert e.is_extended_positive is None
2331
+ assert e.is_hermitian is None
2332
+
2333
+
2334
+ def test_Mul_does_not_cancel_infinities():
2335
+ a, b = symbols('a b')
2336
+ assert ((zoo + 3*a)/(3*a + zoo)) is nan
2337
+ assert ((b - oo)/(b - oo)) is nan
2338
+ # issue 13904
2339
+ expr = (1/(a+b) + 1/(a-b))/(1/(a+b) - 1/(a-b))
2340
+ assert expr.subs(b, a) is nan
2341
+
2342
+
2343
+ def test_Mul_does_not_distribute_infinity():
2344
+ a, b = symbols('a b')
2345
+ assert ((1 + I)*oo).is_Mul
2346
+ assert ((a + b)*(-oo)).is_Mul
2347
+ assert ((a + 1)*zoo).is_Mul
2348
+ assert ((1 + I)*oo).is_finite is False
2349
+ z = (1 + I)*oo
2350
+ assert ((1 - I)*z).expand() is oo
2351
+
2352
+
2353
+ def test_issue_8247_8354():
2354
+ from sympy.functions.elementary.trigonometric import tan
2355
+ z = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3))
2356
+ assert z.is_positive is False # it's 0
2357
+ z = S('''-2**(1/3)*(3*sqrt(93) + 29)**2 - 4*(3*sqrt(93) + 29)**(4/3) +
2358
+ 12*sqrt(93)*(3*sqrt(93) + 29)**(1/3) + 116*(3*sqrt(93) + 29)**(1/3) +
2359
+ 174*2**(1/3)*sqrt(93) + 1678*2**(1/3)''')
2360
+ assert z.is_positive is False # it's 0
2361
+ z = 2*(-3*tan(19*pi/90) + sqrt(3))*cos(11*pi/90)*cos(19*pi/90) - \
2362
+ sqrt(3)*(-3 + 4*cos(19*pi/90)**2)
2363
+ assert z.is_positive is not True # it's zero and it shouldn't hang
2364
+ z = S('''9*(3*sqrt(93) + 29)**(2/3)*((3*sqrt(93) +
2365
+ 29)**(1/3)*(-2**(2/3)*(3*sqrt(93) + 29)**(1/3) - 2) - 2*2**(1/3))**3 +
2366
+ 72*(3*sqrt(93) + 29)**(2/3)*(81*sqrt(93) + 783) + (162*sqrt(93) +
2367
+ 1566)*((3*sqrt(93) + 29)**(1/3)*(-2**(2/3)*(3*sqrt(93) + 29)**(1/3) -
2368
+ 2) - 2*2**(1/3))**2''')
2369
+ assert z.is_positive is False # it's 0 (and a single _mexpand isn't enough)
2370
+
2371
+
2372
+ def test_Add_is_zero():
2373
+ x, y = symbols('x y', zero=True)
2374
+ assert (x + y).is_zero
2375
+
2376
+ # Issue 15873
2377
+ e = -2*I + (1 + I)**2
2378
+ assert e.is_zero is None
2379
+
2380
+
2381
+ def test_issue_14392():
2382
+ assert (sin(zoo)**2).as_real_imag() == (nan, nan)
2383
+
2384
+
2385
+ def test_divmod():
2386
+ assert divmod(x, y) == (x//y, x % y)
2387
+ assert divmod(x, 3) == (x//3, x % 3)
2388
+ assert divmod(3, x) == (3//x, 3 % x)
2389
+
2390
+
2391
+ def test__neg__():
2392
+ assert -(x*y) == -x*y
2393
+ assert -(-x*y) == x*y
2394
+ assert -(1.*x) == -1.*x
2395
+ assert -(-1.*x) == 1.*x
2396
+ assert -(2.*x) == -2.*x
2397
+ assert -(-2.*x) == 2.*x
2398
+ with distribute(False):
2399
+ eq = -(x + y)
2400
+ assert eq.is_Mul and eq.args == (-1, x + y)
2401
+ with evaluate(False):
2402
+ eq = -(x + y)
2403
+ assert eq.is_Mul and eq.args == (-1, x + y)
2404
+
2405
+
2406
+ def test_issue_18507():
2407
+ assert Mul(zoo, zoo, 0) is nan
2408
+
2409
+
2410
+ def test_issue_17130():
2411
+ e = Add(b, -b, I, -I, evaluate=False)
2412
+ assert e.is_zero is None # ideally this would be True
2413
+
2414
+
2415
+ def test_issue_21034():
2416
+ e = -I*log((re(asin(5)) + I*im(asin(5)))/sqrt(re(asin(5))**2 + im(asin(5))**2))/pi
2417
+ assert e.round(2)
2418
+
2419
+
2420
+ def test_issue_22021():
2421
+ from sympy.calculus.accumulationbounds import AccumBounds
2422
+ # these objects are special cases in Mul
2423
+ from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
2424
+ L = TensorIndexType("L")
2425
+ i = tensor_indices("i", L)
2426
+ A, B = tensor_heads("A B", [L])
2427
+ e = A(i) + B(i)
2428
+ assert -e == -1*e
2429
+ e = zoo + x
2430
+ assert -e == -1*e
2431
+ a = AccumBounds(1, 2)
2432
+ e = a + x
2433
+ assert -e == -1*e
2434
+ for args in permutations((zoo, a, x)):
2435
+ e = Add(*args, evaluate=False)
2436
+ assert -e == -1*e
2437
+ assert 2*Add(1, x, x, evaluate=False) == 4*x + 2
2438
+
2439
+
2440
+ def test_issue_22244():
2441
+ assert -(zoo*x) == zoo*x
2442
+
2443
+
2444
+ def test_issue_22453():
2445
+ from sympy.utilities.iterables import cartes
2446
+ e = Symbol('e', extended_positive=True)
2447
+ for a, b in cartes(*[[oo, -oo, 3]]*2):
2448
+ if a == b == 3:
2449
+ continue
2450
+ i = a + I*b
2451
+ assert i**(1 + e) is S.ComplexInfinity
2452
+ assert i**-e is S.Zero
2453
+ assert unchanged(Pow, i, e)
2454
+ assert 1/(oo + I*oo) is S.Zero
2455
+ r, i = [Dummy(infinite=True, extended_real=True) for _ in range(2)]
2456
+ assert 1/(r + I*i) is S.Zero
2457
+ assert 1/(3 + I*i) is S.Zero
2458
+ assert 1/(r + I*3) is S.Zero
2459
+
2460
+
2461
+ def test_issue_22613():
2462
+ assert (0**(x - 2)).as_content_primitive() == (1, 0**(x - 2))
2463
+ assert (0**(x + 2)).as_content_primitive() == (1, 0**(x + 2))
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_assumptions.py ADDED
@@ -0,0 +1,1335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.mod import Mod
2
+ from sympy.core.numbers import (I, oo, pi)
3
+ from sympy.functions.combinatorial.factorials import factorial
4
+ from sympy.functions.elementary.exponential import (exp, log)
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.elementary.trigonometric import (asin, sin)
7
+ from sympy.simplify.simplify import simplify
8
+ from sympy.core import Symbol, S, Rational, Integer, Dummy, Wild, Pow
9
+ from sympy.core.assumptions import (assumptions, check_assumptions,
10
+ failing_assumptions, common_assumptions, _generate_assumption_rules,
11
+ _load_pre_generated_assumption_rules)
12
+ from sympy.core.facts import InconsistentAssumptions
13
+ from sympy.core.random import seed
14
+ from sympy.combinatorics import Permutation
15
+ from sympy.combinatorics.perm_groups import PermutationGroup
16
+
17
+ from sympy.testing.pytest import raises, XFAIL
18
+
19
+
20
+ def test_symbol_unset():
21
+ x = Symbol('x', real=True, integer=True)
22
+ assert x.is_real is True
23
+ assert x.is_integer is True
24
+ assert x.is_imaginary is False
25
+ assert x.is_noninteger is False
26
+ assert x.is_number is False
27
+
28
+
29
+ def test_zero():
30
+ z = Integer(0)
31
+ assert z.is_commutative is True
32
+ assert z.is_integer is True
33
+ assert z.is_rational is True
34
+ assert z.is_algebraic is True
35
+ assert z.is_transcendental is False
36
+ assert z.is_real is True
37
+ assert z.is_complex is True
38
+ assert z.is_noninteger is False
39
+ assert z.is_irrational is False
40
+ assert z.is_imaginary is False
41
+ assert z.is_positive is False
42
+ assert z.is_negative is False
43
+ assert z.is_nonpositive is True
44
+ assert z.is_nonnegative is True
45
+ assert z.is_even is True
46
+ assert z.is_odd is False
47
+ assert z.is_finite is True
48
+ assert z.is_infinite is False
49
+ assert z.is_comparable is True
50
+ assert z.is_prime is False
51
+ assert z.is_composite is False
52
+ assert z.is_number is True
53
+
54
+
55
+ def test_one():
56
+ z = Integer(1)
57
+ assert z.is_commutative is True
58
+ assert z.is_integer is True
59
+ assert z.is_rational is True
60
+ assert z.is_algebraic is True
61
+ assert z.is_transcendental is False
62
+ assert z.is_real is True
63
+ assert z.is_complex is True
64
+ assert z.is_noninteger is False
65
+ assert z.is_irrational is False
66
+ assert z.is_imaginary is False
67
+ assert z.is_positive is True
68
+ assert z.is_negative is False
69
+ assert z.is_nonpositive is False
70
+ assert z.is_nonnegative is True
71
+ assert z.is_even is False
72
+ assert z.is_odd is True
73
+ assert z.is_finite is True
74
+ assert z.is_infinite is False
75
+ assert z.is_comparable is True
76
+ assert z.is_prime is False
77
+ assert z.is_number is True
78
+ assert z.is_composite is False # issue 8807
79
+
80
+
81
+ def test_negativeone():
82
+ z = Integer(-1)
83
+ assert z.is_commutative is True
84
+ assert z.is_integer is True
85
+ assert z.is_rational is True
86
+ assert z.is_algebraic is True
87
+ assert z.is_transcendental is False
88
+ assert z.is_real is True
89
+ assert z.is_complex is True
90
+ assert z.is_noninteger is False
91
+ assert z.is_irrational is False
92
+ assert z.is_imaginary is False
93
+ assert z.is_positive is False
94
+ assert z.is_negative is True
95
+ assert z.is_nonpositive is True
96
+ assert z.is_nonnegative is False
97
+ assert z.is_even is False
98
+ assert z.is_odd is True
99
+ assert z.is_finite is True
100
+ assert z.is_infinite is False
101
+ assert z.is_comparable is True
102
+ assert z.is_prime is False
103
+ assert z.is_composite is False
104
+ assert z.is_number is True
105
+
106
+
107
+ def test_infinity():
108
+ oo = S.Infinity
109
+
110
+ assert oo.is_commutative is True
111
+ assert oo.is_integer is False
112
+ assert oo.is_rational is False
113
+ assert oo.is_algebraic is False
114
+ assert oo.is_transcendental is False
115
+ assert oo.is_extended_real is True
116
+ assert oo.is_real is False
117
+ assert oo.is_complex is False
118
+ assert oo.is_noninteger is True
119
+ assert oo.is_irrational is False
120
+ assert oo.is_imaginary is False
121
+ assert oo.is_nonzero is False
122
+ assert oo.is_positive is False
123
+ assert oo.is_negative is False
124
+ assert oo.is_nonpositive is False
125
+ assert oo.is_nonnegative is False
126
+ assert oo.is_extended_nonzero is True
127
+ assert oo.is_extended_positive is True
128
+ assert oo.is_extended_negative is False
129
+ assert oo.is_extended_nonpositive is False
130
+ assert oo.is_extended_nonnegative is True
131
+ assert oo.is_even is False
132
+ assert oo.is_odd is False
133
+ assert oo.is_finite is False
134
+ assert oo.is_infinite is True
135
+ assert oo.is_comparable is True
136
+ assert oo.is_prime is False
137
+ assert oo.is_composite is False
138
+ assert oo.is_number is True
139
+
140
+
141
+ def test_neg_infinity():
142
+ mm = S.NegativeInfinity
143
+
144
+ assert mm.is_commutative is True
145
+ assert mm.is_integer is False
146
+ assert mm.is_rational is False
147
+ assert mm.is_algebraic is False
148
+ assert mm.is_transcendental is False
149
+ assert mm.is_extended_real is True
150
+ assert mm.is_real is False
151
+ assert mm.is_complex is False
152
+ assert mm.is_noninteger is True
153
+ assert mm.is_irrational is False
154
+ assert mm.is_imaginary is False
155
+ assert mm.is_nonzero is False
156
+ assert mm.is_positive is False
157
+ assert mm.is_negative is False
158
+ assert mm.is_nonpositive is False
159
+ assert mm.is_nonnegative is False
160
+ assert mm.is_extended_nonzero is True
161
+ assert mm.is_extended_positive is False
162
+ assert mm.is_extended_negative is True
163
+ assert mm.is_extended_nonpositive is True
164
+ assert mm.is_extended_nonnegative is False
165
+ assert mm.is_even is False
166
+ assert mm.is_odd is False
167
+ assert mm.is_finite is False
168
+ assert mm.is_infinite is True
169
+ assert mm.is_comparable is True
170
+ assert mm.is_prime is False
171
+ assert mm.is_composite is False
172
+ assert mm.is_number is True
173
+
174
+
175
+ def test_zoo():
176
+ zoo = S.ComplexInfinity
177
+ assert zoo.is_complex is False
178
+ assert zoo.is_real is False
179
+ assert zoo.is_prime is False
180
+
181
+
182
+ def test_nan():
183
+ nan = S.NaN
184
+
185
+ assert nan.is_commutative is True
186
+ assert nan.is_integer is None
187
+ assert nan.is_rational is None
188
+ assert nan.is_algebraic is None
189
+ assert nan.is_transcendental is None
190
+ assert nan.is_real is None
191
+ assert nan.is_complex is None
192
+ assert nan.is_noninteger is None
193
+ assert nan.is_irrational is None
194
+ assert nan.is_imaginary is None
195
+ assert nan.is_positive is None
196
+ assert nan.is_negative is None
197
+ assert nan.is_nonpositive is None
198
+ assert nan.is_nonnegative is None
199
+ assert nan.is_even is None
200
+ assert nan.is_odd is None
201
+ assert nan.is_finite is None
202
+ assert nan.is_infinite is None
203
+ assert nan.is_comparable is False
204
+ assert nan.is_prime is None
205
+ assert nan.is_composite is None
206
+ assert nan.is_number is True
207
+
208
+
209
+ def test_pos_rational():
210
+ r = Rational(3, 4)
211
+ assert r.is_commutative is True
212
+ assert r.is_integer is False
213
+ assert r.is_rational is True
214
+ assert r.is_algebraic is True
215
+ assert r.is_transcendental is False
216
+ assert r.is_real is True
217
+ assert r.is_complex is True
218
+ assert r.is_noninteger is True
219
+ assert r.is_irrational is False
220
+ assert r.is_imaginary is False
221
+ assert r.is_positive is True
222
+ assert r.is_negative is False
223
+ assert r.is_nonpositive is False
224
+ assert r.is_nonnegative is True
225
+ assert r.is_even is False
226
+ assert r.is_odd is False
227
+ assert r.is_finite is True
228
+ assert r.is_infinite is False
229
+ assert r.is_comparable is True
230
+ assert r.is_prime is False
231
+ assert r.is_composite is False
232
+
233
+ r = Rational(1, 4)
234
+ assert r.is_nonpositive is False
235
+ assert r.is_positive is True
236
+ assert r.is_negative is False
237
+ assert r.is_nonnegative is True
238
+ r = Rational(5, 4)
239
+ assert r.is_negative is False
240
+ assert r.is_positive is True
241
+ assert r.is_nonpositive is False
242
+ assert r.is_nonnegative is True
243
+ r = Rational(5, 3)
244
+ assert r.is_nonnegative is True
245
+ assert r.is_positive is True
246
+ assert r.is_negative is False
247
+ assert r.is_nonpositive is False
248
+
249
+
250
+ def test_neg_rational():
251
+ r = Rational(-3, 4)
252
+ assert r.is_positive is False
253
+ assert r.is_nonpositive is True
254
+ assert r.is_negative is True
255
+ assert r.is_nonnegative is False
256
+ r = Rational(-1, 4)
257
+ assert r.is_nonpositive is True
258
+ assert r.is_positive is False
259
+ assert r.is_negative is True
260
+ assert r.is_nonnegative is False
261
+ r = Rational(-5, 4)
262
+ assert r.is_negative is True
263
+ assert r.is_positive is False
264
+ assert r.is_nonpositive is True
265
+ assert r.is_nonnegative is False
266
+ r = Rational(-5, 3)
267
+ assert r.is_nonnegative is False
268
+ assert r.is_positive is False
269
+ assert r.is_negative is True
270
+ assert r.is_nonpositive is True
271
+
272
+
273
+ def test_pi():
274
+ z = S.Pi
275
+ assert z.is_commutative is True
276
+ assert z.is_integer is False
277
+ assert z.is_rational is False
278
+ assert z.is_algebraic is False
279
+ assert z.is_transcendental is True
280
+ assert z.is_real is True
281
+ assert z.is_complex is True
282
+ assert z.is_noninteger is True
283
+ assert z.is_irrational is True
284
+ assert z.is_imaginary is False
285
+ assert z.is_positive is True
286
+ assert z.is_negative is False
287
+ assert z.is_nonpositive is False
288
+ assert z.is_nonnegative is True
289
+ assert z.is_even is False
290
+ assert z.is_odd is False
291
+ assert z.is_finite is True
292
+ assert z.is_infinite is False
293
+ assert z.is_comparable is True
294
+ assert z.is_prime is False
295
+ assert z.is_composite is False
296
+
297
+
298
+ def test_E():
299
+ z = S.Exp1
300
+ assert z.is_commutative is True
301
+ assert z.is_integer is False
302
+ assert z.is_rational is False
303
+ assert z.is_algebraic is False
304
+ assert z.is_transcendental is True
305
+ assert z.is_real is True
306
+ assert z.is_complex is True
307
+ assert z.is_noninteger is True
308
+ assert z.is_irrational is True
309
+ assert z.is_imaginary is False
310
+ assert z.is_positive is True
311
+ assert z.is_negative is False
312
+ assert z.is_nonpositive is False
313
+ assert z.is_nonnegative is True
314
+ assert z.is_even is False
315
+ assert z.is_odd is False
316
+ assert z.is_finite is True
317
+ assert z.is_infinite is False
318
+ assert z.is_comparable is True
319
+ assert z.is_prime is False
320
+ assert z.is_composite is False
321
+
322
+
323
+ def test_I():
324
+ z = S.ImaginaryUnit
325
+ assert z.is_commutative is True
326
+ assert z.is_integer is False
327
+ assert z.is_rational is False
328
+ assert z.is_algebraic is True
329
+ assert z.is_transcendental is False
330
+ assert z.is_real is False
331
+ assert z.is_complex is True
332
+ assert z.is_noninteger is False
333
+ assert z.is_irrational is False
334
+ assert z.is_imaginary is True
335
+ assert z.is_positive is False
336
+ assert z.is_negative is False
337
+ assert z.is_nonpositive is False
338
+ assert z.is_nonnegative is False
339
+ assert z.is_even is False
340
+ assert z.is_odd is False
341
+ assert z.is_finite is True
342
+ assert z.is_infinite is False
343
+ assert z.is_comparable is False
344
+ assert z.is_prime is False
345
+ assert z.is_composite is False
346
+
347
+
348
+ def test_symbol_real_false():
349
+ # issue 3848
350
+ a = Symbol('a', real=False)
351
+
352
+ assert a.is_real is False
353
+ assert a.is_integer is False
354
+ assert a.is_zero is False
355
+
356
+ assert a.is_negative is False
357
+ assert a.is_positive is False
358
+ assert a.is_nonnegative is False
359
+ assert a.is_nonpositive is False
360
+ assert a.is_nonzero is False
361
+
362
+ assert a.is_extended_negative is None
363
+ assert a.is_extended_positive is None
364
+ assert a.is_extended_nonnegative is None
365
+ assert a.is_extended_nonpositive is None
366
+ assert a.is_extended_nonzero is None
367
+
368
+
369
+ def test_symbol_extended_real_false():
370
+ # issue 3848
371
+ a = Symbol('a', extended_real=False)
372
+
373
+ assert a.is_real is False
374
+ assert a.is_integer is False
375
+ assert a.is_zero is False
376
+
377
+ assert a.is_negative is False
378
+ assert a.is_positive is False
379
+ assert a.is_nonnegative is False
380
+ assert a.is_nonpositive is False
381
+ assert a.is_nonzero is False
382
+
383
+ assert a.is_extended_negative is False
384
+ assert a.is_extended_positive is False
385
+ assert a.is_extended_nonnegative is False
386
+ assert a.is_extended_nonpositive is False
387
+ assert a.is_extended_nonzero is False
388
+
389
+
390
+ def test_symbol_imaginary():
391
+ a = Symbol('a', imaginary=True)
392
+
393
+ assert a.is_real is False
394
+ assert a.is_integer is False
395
+ assert a.is_negative is False
396
+ assert a.is_positive is False
397
+ assert a.is_nonnegative is False
398
+ assert a.is_nonpositive is False
399
+ assert a.is_zero is False
400
+ assert a.is_nonzero is False # since nonzero -> real
401
+
402
+
403
+ def test_symbol_zero():
404
+ x = Symbol('x', zero=True)
405
+ assert x.is_positive is False
406
+ assert x.is_nonpositive
407
+ assert x.is_negative is False
408
+ assert x.is_nonnegative
409
+ assert x.is_zero is True
410
+ # TODO Change to x.is_nonzero is None
411
+ # See https://github.com/sympy/sympy/pull/9583
412
+ assert x.is_nonzero is False
413
+ assert x.is_finite is True
414
+
415
+
416
+ def test_symbol_positive():
417
+ x = Symbol('x', positive=True)
418
+ assert x.is_positive is True
419
+ assert x.is_nonpositive is False
420
+ assert x.is_negative is False
421
+ assert x.is_nonnegative is True
422
+ assert x.is_zero is False
423
+ assert x.is_nonzero is True
424
+
425
+
426
+ def test_neg_symbol_positive():
427
+ x = -Symbol('x', positive=True)
428
+ assert x.is_positive is False
429
+ assert x.is_nonpositive is True
430
+ assert x.is_negative is True
431
+ assert x.is_nonnegative is False
432
+ assert x.is_zero is False
433
+ assert x.is_nonzero is True
434
+
435
+
436
+ def test_symbol_nonpositive():
437
+ x = Symbol('x', nonpositive=True)
438
+ assert x.is_positive is False
439
+ assert x.is_nonpositive is True
440
+ assert x.is_negative is None
441
+ assert x.is_nonnegative is None
442
+ assert x.is_zero is None
443
+ assert x.is_nonzero is None
444
+
445
+
446
+ def test_neg_symbol_nonpositive():
447
+ x = -Symbol('x', nonpositive=True)
448
+ assert x.is_positive is None
449
+ assert x.is_nonpositive is None
450
+ assert x.is_negative is False
451
+ assert x.is_nonnegative is True
452
+ assert x.is_zero is None
453
+ assert x.is_nonzero is None
454
+
455
+
456
+ def test_symbol_falsepositive():
457
+ x = Symbol('x', positive=False)
458
+ assert x.is_positive is False
459
+ assert x.is_nonpositive is None
460
+ assert x.is_negative is None
461
+ assert x.is_nonnegative is None
462
+ assert x.is_zero is None
463
+ assert x.is_nonzero is None
464
+
465
+
466
+ def test_symbol_falsepositive_mul():
467
+ # To test pull request 9379
468
+ # Explicit handling of arg.is_positive=False was added to Mul._eval_is_positive
469
+ x = 2*Symbol('x', positive=False)
470
+ assert x.is_positive is False # This was None before
471
+ assert x.is_nonpositive is None
472
+ assert x.is_negative is None
473
+ assert x.is_nonnegative is None
474
+ assert x.is_zero is None
475
+ assert x.is_nonzero is None
476
+
477
+
478
+ @XFAIL
479
+ def test_symbol_infinitereal_mul():
480
+ ix = Symbol('ix', infinite=True, extended_real=True)
481
+ assert (-ix).is_extended_positive is None
482
+
483
+
484
+ def test_neg_symbol_falsepositive():
485
+ x = -Symbol('x', positive=False)
486
+ assert x.is_positive is None
487
+ assert x.is_nonpositive is None
488
+ assert x.is_negative is False
489
+ assert x.is_nonnegative is None
490
+ assert x.is_zero is None
491
+ assert x.is_nonzero is None
492
+
493
+
494
+ def test_neg_symbol_falsenegative():
495
+ # To test pull request 9379
496
+ # Explicit handling of arg.is_negative=False was added to Mul._eval_is_positive
497
+ x = -Symbol('x', negative=False)
498
+ assert x.is_positive is False # This was None before
499
+ assert x.is_nonpositive is None
500
+ assert x.is_negative is None
501
+ assert x.is_nonnegative is None
502
+ assert x.is_zero is None
503
+ assert x.is_nonzero is None
504
+
505
+
506
+ def test_symbol_falsepositive_real():
507
+ x = Symbol('x', positive=False, real=True)
508
+ assert x.is_positive is False
509
+ assert x.is_nonpositive is True
510
+ assert x.is_negative is None
511
+ assert x.is_nonnegative is None
512
+ assert x.is_zero is None
513
+ assert x.is_nonzero is None
514
+
515
+
516
+ def test_neg_symbol_falsepositive_real():
517
+ x = -Symbol('x', positive=False, real=True)
518
+ assert x.is_positive is None
519
+ assert x.is_nonpositive is None
520
+ assert x.is_negative is False
521
+ assert x.is_nonnegative is True
522
+ assert x.is_zero is None
523
+ assert x.is_nonzero is None
524
+
525
+
526
+ def test_symbol_falsenonnegative():
527
+ x = Symbol('x', nonnegative=False)
528
+ assert x.is_positive is False
529
+ assert x.is_nonpositive is None
530
+ assert x.is_negative is None
531
+ assert x.is_nonnegative is False
532
+ assert x.is_zero is False
533
+ assert x.is_nonzero is None
534
+
535
+
536
+ @XFAIL
537
+ def test_neg_symbol_falsenonnegative():
538
+ x = -Symbol('x', nonnegative=False)
539
+ assert x.is_positive is None
540
+ assert x.is_nonpositive is False # this currently returns None
541
+ assert x.is_negative is False # this currently returns None
542
+ assert x.is_nonnegative is None
543
+ assert x.is_zero is False # this currently returns None
544
+ assert x.is_nonzero is True # this currently returns None
545
+
546
+
547
+ def test_symbol_falsenonnegative_real():
548
+ x = Symbol('x', nonnegative=False, real=True)
549
+ assert x.is_positive is False
550
+ assert x.is_nonpositive is True
551
+ assert x.is_negative is True
552
+ assert x.is_nonnegative is False
553
+ assert x.is_zero is False
554
+ assert x.is_nonzero is True
555
+
556
+
557
+ def test_neg_symbol_falsenonnegative_real():
558
+ x = -Symbol('x', nonnegative=False, real=True)
559
+ assert x.is_positive is True
560
+ assert x.is_nonpositive is False
561
+ assert x.is_negative is False
562
+ assert x.is_nonnegative is True
563
+ assert x.is_zero is False
564
+ assert x.is_nonzero is True
565
+
566
+
567
+ def test_prime():
568
+ assert S.NegativeOne.is_prime is False
569
+ assert S(-2).is_prime is False
570
+ assert S(-4).is_prime is False
571
+ assert S.Zero.is_prime is False
572
+ assert S.One.is_prime is False
573
+ assert S(2).is_prime is True
574
+ assert S(17).is_prime is True
575
+ assert S(4).is_prime is False
576
+
577
+
578
+ def test_composite():
579
+ assert S.NegativeOne.is_composite is False
580
+ assert S(-2).is_composite is False
581
+ assert S(-4).is_composite is False
582
+ assert S.Zero.is_composite is False
583
+ assert S(2).is_composite is False
584
+ assert S(17).is_composite is False
585
+ assert S(4).is_composite is True
586
+ x = Dummy(integer=True, positive=True, prime=False)
587
+ assert x.is_composite is None # x could be 1
588
+ assert (x + 1).is_composite is None
589
+ x = Dummy(positive=True, even=True, prime=False)
590
+ assert x.is_integer is True
591
+ assert x.is_composite is True
592
+
593
+
594
+ def test_prime_symbol():
595
+ x = Symbol('x', prime=True)
596
+ assert x.is_prime is True
597
+ assert x.is_integer is True
598
+ assert x.is_positive is True
599
+ assert x.is_negative is False
600
+ assert x.is_nonpositive is False
601
+ assert x.is_nonnegative is True
602
+
603
+ x = Symbol('x', prime=False)
604
+ assert x.is_prime is False
605
+ assert x.is_integer is None
606
+ assert x.is_positive is None
607
+ assert x.is_negative is None
608
+ assert x.is_nonpositive is None
609
+ assert x.is_nonnegative is None
610
+
611
+
612
+ def test_symbol_noncommutative():
613
+ x = Symbol('x', commutative=True)
614
+ assert x.is_complex is None
615
+
616
+ x = Symbol('x', commutative=False)
617
+ assert x.is_integer is False
618
+ assert x.is_rational is False
619
+ assert x.is_algebraic is False
620
+ assert x.is_irrational is False
621
+ assert x.is_real is False
622
+ assert x.is_complex is False
623
+
624
+
625
+ def test_other_symbol():
626
+ x = Symbol('x', integer=True)
627
+ assert x.is_integer is True
628
+ assert x.is_real is True
629
+ assert x.is_finite is True
630
+
631
+ x = Symbol('x', integer=True, nonnegative=True)
632
+ assert x.is_integer is True
633
+ assert x.is_nonnegative is True
634
+ assert x.is_negative is False
635
+ assert x.is_positive is None
636
+ assert x.is_finite is True
637
+
638
+ x = Symbol('x', integer=True, nonpositive=True)
639
+ assert x.is_integer is True
640
+ assert x.is_nonpositive is True
641
+ assert x.is_positive is False
642
+ assert x.is_negative is None
643
+ assert x.is_finite is True
644
+
645
+ x = Symbol('x', odd=True)
646
+ assert x.is_odd is True
647
+ assert x.is_even is False
648
+ assert x.is_integer is True
649
+ assert x.is_finite is True
650
+
651
+ x = Symbol('x', odd=False)
652
+ assert x.is_odd is False
653
+ assert x.is_even is None
654
+ assert x.is_integer is None
655
+ assert x.is_finite is None
656
+
657
+ x = Symbol('x', even=True)
658
+ assert x.is_even is True
659
+ assert x.is_odd is False
660
+ assert x.is_integer is True
661
+ assert x.is_finite is True
662
+
663
+ x = Symbol('x', even=False)
664
+ assert x.is_even is False
665
+ assert x.is_odd is None
666
+ assert x.is_integer is None
667
+ assert x.is_finite is None
668
+
669
+ x = Symbol('x', integer=True, nonnegative=True)
670
+ assert x.is_integer is True
671
+ assert x.is_nonnegative is True
672
+ assert x.is_finite is True
673
+
674
+ x = Symbol('x', integer=True, nonpositive=True)
675
+ assert x.is_integer is True
676
+ assert x.is_nonpositive is True
677
+ assert x.is_finite is True
678
+
679
+ x = Symbol('x', rational=True)
680
+ assert x.is_real is True
681
+ assert x.is_finite is True
682
+
683
+ x = Symbol('x', rational=False)
684
+ assert x.is_real is None
685
+ assert x.is_finite is None
686
+
687
+ x = Symbol('x', irrational=True)
688
+ assert x.is_real is True
689
+ assert x.is_finite is True
690
+
691
+ x = Symbol('x', irrational=False)
692
+ assert x.is_real is None
693
+ assert x.is_finite is None
694
+
695
+ with raises(AttributeError):
696
+ x.is_real = False
697
+
698
+ x = Symbol('x', algebraic=True)
699
+ assert x.is_transcendental is False
700
+ x = Symbol('x', transcendental=True)
701
+ assert x.is_algebraic is False
702
+ assert x.is_rational is False
703
+ assert x.is_integer is False
704
+
705
+
706
+ def test_evaluate_false():
707
+ # Previously this failed because the assumptions query would make new
708
+ # expressions and some of the evaluation logic would fail under
709
+ # evaluate(False).
710
+ from sympy.core.parameters import evaluate
711
+ from sympy.abc import x, h
712
+ f = 2**x**7
713
+ with evaluate(False):
714
+ fh = f.xreplace({x: x+h})
715
+ assert fh.exp.is_rational is None
716
+
717
+
718
+ def test_issue_3825():
719
+ """catch: hash instability"""
720
+ x = Symbol("x")
721
+ y = Symbol("y")
722
+ a1 = x + y
723
+ a2 = y + x
724
+ a2.is_comparable
725
+
726
+ h1 = hash(a1)
727
+ h2 = hash(a2)
728
+ assert h1 == h2
729
+
730
+
731
+ def test_issue_4822():
732
+ z = (-1)**Rational(1, 3)*(1 - I*sqrt(3))
733
+ assert z.is_real in [True, None]
734
+
735
+
736
+ def test_hash_vs_typeinfo():
737
+ """seemingly different typeinfo, but in fact equal"""
738
+
739
+ # the following two are semantically equal
740
+ x1 = Symbol('x', even=True)
741
+ x2 = Symbol('x', integer=True, odd=False)
742
+
743
+ assert hash(x1) == hash(x2)
744
+ assert x1 == x2
745
+
746
+
747
+ def test_hash_vs_typeinfo_2():
748
+ """different typeinfo should mean !eq"""
749
+ # the following two are semantically different
750
+ x = Symbol('x')
751
+ x1 = Symbol('x', even=True)
752
+
753
+ assert x != x1
754
+ assert hash(x) != hash(x1) # This might fail with very low probability
755
+
756
+
757
+ def test_hash_vs_eq():
758
+ """catch: different hash for equal objects"""
759
+ a = 1 + S.Pi # important: do not fold it into a Number instance
760
+ ha = hash(a) # it should be Add/Mul/... to trigger the bug
761
+
762
+ a.is_positive # this uses .evalf() and deduces it is positive
763
+ assert a.is_positive is True
764
+
765
+ # be sure that hash stayed the same
766
+ assert ha == hash(a)
767
+
768
+ # now b should be the same expression
769
+ b = a.expand(trig=True)
770
+ hb = hash(b)
771
+
772
+ assert a == b
773
+ assert ha == hb
774
+
775
+
776
+ def test_Add_is_pos_neg():
777
+ # these cover lines not covered by the rest of tests in core
778
+ n = Symbol('n', extended_negative=True, infinite=True)
779
+ nn = Symbol('n', extended_nonnegative=True, infinite=True)
780
+ np = Symbol('n', extended_nonpositive=True, infinite=True)
781
+ p = Symbol('p', extended_positive=True, infinite=True)
782
+ r = Dummy(extended_real=True, finite=False)
783
+ x = Symbol('x')
784
+ xf = Symbol('xf', finite=True)
785
+ assert (n + p).is_extended_positive is None
786
+ assert (n + x).is_extended_positive is None
787
+ assert (p + x).is_extended_positive is None
788
+ assert (n + p).is_extended_negative is None
789
+ assert (n + x).is_extended_negative is None
790
+ assert (p + x).is_extended_negative is None
791
+
792
+ assert (n + xf).is_extended_positive is False
793
+ assert (p + xf).is_extended_positive is True
794
+ assert (n + xf).is_extended_negative is True
795
+ assert (p + xf).is_extended_negative is False
796
+
797
+ assert (x - S.Infinity).is_extended_negative is None # issue 7798
798
+ # issue 8046, 16.2
799
+ assert (p + nn).is_extended_positive
800
+ assert (n + np).is_extended_negative
801
+ assert (p + r).is_extended_positive is None
802
+
803
+
804
+ def test_Add_is_imaginary():
805
+ nn = Dummy(nonnegative=True)
806
+ assert (I*nn + I).is_imaginary # issue 8046, 17
807
+
808
+
809
+ def test_Add_is_algebraic():
810
+ a = Symbol('a', algebraic=True)
811
+ b = Symbol('a', algebraic=True)
812
+ na = Symbol('na', algebraic=False)
813
+ nb = Symbol('nb', algebraic=False)
814
+ x = Symbol('x')
815
+ assert (a + b).is_algebraic
816
+ assert (na + nb).is_algebraic is None
817
+ assert (a + na).is_algebraic is False
818
+ assert (a + x).is_algebraic is None
819
+ assert (na + x).is_algebraic is None
820
+
821
+
822
+ def test_Mul_is_algebraic():
823
+ a = Symbol('a', algebraic=True)
824
+ b = Symbol('b', algebraic=True)
825
+ na = Symbol('na', algebraic=False)
826
+ an = Symbol('an', algebraic=True, nonzero=True)
827
+ nb = Symbol('nb', algebraic=False)
828
+ x = Symbol('x')
829
+ assert (a*b).is_algebraic is True
830
+ assert (na*nb).is_algebraic is None
831
+ assert (a*na).is_algebraic is None
832
+ assert (an*na).is_algebraic is False
833
+ assert (a*x).is_algebraic is None
834
+ assert (na*x).is_algebraic is None
835
+
836
+
837
+ def test_Pow_is_algebraic():
838
+ e = Symbol('e', algebraic=True)
839
+
840
+ assert Pow(1, e, evaluate=False).is_algebraic
841
+ assert Pow(0, e, evaluate=False).is_algebraic
842
+
843
+ a = Symbol('a', algebraic=True)
844
+ azf = Symbol('azf', algebraic=True, zero=False)
845
+ na = Symbol('na', algebraic=False)
846
+ ia = Symbol('ia', algebraic=True, irrational=True)
847
+ ib = Symbol('ib', algebraic=True, irrational=True)
848
+ r = Symbol('r', rational=True)
849
+ x = Symbol('x')
850
+ assert (a**2).is_algebraic is True
851
+ assert (a**r).is_algebraic is None
852
+ assert (azf**r).is_algebraic is True
853
+ assert (a**x).is_algebraic is None
854
+ assert (na**r).is_algebraic is None
855
+ assert (ia**r).is_algebraic is True
856
+ assert (ia**ib).is_algebraic is False
857
+
858
+ assert (a**e).is_algebraic is None
859
+
860
+ # Gelfond-Schneider constant:
861
+ assert Pow(2, sqrt(2), evaluate=False).is_algebraic is False
862
+
863
+ assert Pow(S.GoldenRatio, sqrt(3), evaluate=False).is_algebraic is False
864
+
865
+ # issue 8649
866
+ t = Symbol('t', real=True, transcendental=True)
867
+ n = Symbol('n', integer=True)
868
+ assert (t**n).is_algebraic is None
869
+ assert (t**n).is_integer is None
870
+
871
+ assert (pi**3).is_algebraic is False
872
+ r = Symbol('r', zero=True)
873
+ assert (pi**r).is_algebraic is True
874
+
875
+
876
+ def test_Mul_is_prime_composite():
877
+ x = Symbol('x', positive=True, integer=True)
878
+ y = Symbol('y', positive=True, integer=True)
879
+ assert (x*y).is_prime is None
880
+ assert ( (x+1)*(y+1) ).is_prime is False
881
+ assert ( (x+1)*(y+1) ).is_composite is True
882
+
883
+ x = Symbol('x', positive=True)
884
+ assert ( (x+1)*(y+1) ).is_prime is None
885
+ assert ( (x+1)*(y+1) ).is_composite is None
886
+
887
+
888
+ def test_Pow_is_pos_neg():
889
+ z = Symbol('z', real=True)
890
+ w = Symbol('w', nonpositive=True)
891
+
892
+ assert (S.NegativeOne**S(2)).is_positive is True
893
+ assert (S.One**z).is_positive is True
894
+ assert (S.NegativeOne**S(3)).is_positive is False
895
+ assert (S.Zero**S.Zero).is_positive is True # 0**0 is 1
896
+ assert (w**S(3)).is_positive is False
897
+ assert (w**S(2)).is_positive is None
898
+ assert (I**2).is_positive is False
899
+ assert (I**4).is_positive is True
900
+
901
+ # tests emerging from #16332 issue
902
+ p = Symbol('p', zero=True)
903
+ q = Symbol('q', zero=False, real=True)
904
+ j = Symbol('j', zero=False, even=True)
905
+ x = Symbol('x', zero=True)
906
+ y = Symbol('y', zero=True)
907
+ assert (p**q).is_positive is False
908
+ assert (p**q).is_negative is False
909
+ assert (p**j).is_positive is False
910
+ assert (x**y).is_positive is True # 0**0
911
+ assert (x**y).is_negative is False
912
+
913
+
914
+ def test_Pow_is_prime_composite():
915
+ x = Symbol('x', positive=True, integer=True)
916
+ y = Symbol('y', positive=True, integer=True)
917
+ assert (x**y).is_prime is None
918
+ assert ( x**(y+1) ).is_prime is False
919
+ assert ( x**(y+1) ).is_composite is None
920
+ assert ( (x+1)**(y+1) ).is_composite is True
921
+ assert ( (-x-1)**(2*y) ).is_composite is True
922
+
923
+ x = Symbol('x', positive=True)
924
+ assert (x**y).is_prime is None
925
+
926
+
927
+ def test_Mul_is_infinite():
928
+ x = Symbol('x')
929
+ f = Symbol('f', finite=True)
930
+ i = Symbol('i', infinite=True)
931
+ z = Dummy(zero=True)
932
+ nzf = Dummy(finite=True, zero=False)
933
+ from sympy.core.mul import Mul
934
+ assert (x*f).is_finite is None
935
+ assert (x*i).is_finite is None
936
+ assert (f*i).is_finite is None
937
+ assert (x*f*i).is_finite is None
938
+ assert (z*i).is_finite is None
939
+ assert (nzf*i).is_finite is False
940
+ assert (z*f).is_finite is True
941
+ assert Mul(0, f, evaluate=False).is_finite is True
942
+ assert Mul(0, i, evaluate=False).is_finite is None
943
+
944
+ assert (x*f).is_infinite is None
945
+ assert (x*i).is_infinite is None
946
+ assert (f*i).is_infinite is None
947
+ assert (x*f*i).is_infinite is None
948
+ assert (z*i).is_infinite is S.NaN.is_infinite
949
+ assert (nzf*i).is_infinite is True
950
+ assert (z*f).is_infinite is False
951
+ assert Mul(0, f, evaluate=False).is_infinite is False
952
+ assert Mul(0, i, evaluate=False).is_infinite is S.NaN.is_infinite
953
+
954
+
955
+ def test_Add_is_infinite():
956
+ x = Symbol('x')
957
+ f = Symbol('f', finite=True)
958
+ i = Symbol('i', infinite=True)
959
+ i2 = Symbol('i2', infinite=True)
960
+ z = Dummy(zero=True)
961
+ nzf = Dummy(finite=True, zero=False)
962
+ from sympy.core.add import Add
963
+ assert (x+f).is_finite is None
964
+ assert (x+i).is_finite is None
965
+ assert (f+i).is_finite is False
966
+ assert (x+f+i).is_finite is None
967
+ assert (z+i).is_finite is False
968
+ assert (nzf+i).is_finite is False
969
+ assert (z+f).is_finite is True
970
+ assert (i+i2).is_finite is None
971
+ assert Add(0, f, evaluate=False).is_finite is True
972
+ assert Add(0, i, evaluate=False).is_finite is False
973
+
974
+ assert (x+f).is_infinite is None
975
+ assert (x+i).is_infinite is None
976
+ assert (f+i).is_infinite is True
977
+ assert (x+f+i).is_infinite is None
978
+ assert (z+i).is_infinite is True
979
+ assert (nzf+i).is_infinite is True
980
+ assert (z+f).is_infinite is False
981
+ assert (i+i2).is_infinite is None
982
+ assert Add(0, f, evaluate=False).is_infinite is False
983
+ assert Add(0, i, evaluate=False).is_infinite is True
984
+
985
+
986
+ def test_special_is_rational():
987
+ i = Symbol('i', integer=True)
988
+ i2 = Symbol('i2', integer=True)
989
+ ni = Symbol('ni', integer=True, nonzero=True)
990
+ r = Symbol('r', rational=True)
991
+ rn = Symbol('r', rational=True, nonzero=True)
992
+ nr = Symbol('nr', irrational=True)
993
+ x = Symbol('x')
994
+ assert sqrt(3).is_rational is False
995
+ assert (3 + sqrt(3)).is_rational is False
996
+ assert (3*sqrt(3)).is_rational is False
997
+ assert exp(3).is_rational is False
998
+ assert exp(ni).is_rational is False
999
+ assert exp(rn).is_rational is False
1000
+ assert exp(x).is_rational is None
1001
+ assert exp(log(3), evaluate=False).is_rational is True
1002
+ assert log(exp(3), evaluate=False).is_rational is True
1003
+ assert log(3).is_rational is False
1004
+ assert log(ni + 1).is_rational is False
1005
+ assert log(rn + 1).is_rational is False
1006
+ assert log(x).is_rational is None
1007
+ assert (sqrt(3) + sqrt(5)).is_rational is None
1008
+ assert (sqrt(3) + S.Pi).is_rational is False
1009
+ assert (x**i).is_rational is None
1010
+ assert (i**i).is_rational is True
1011
+ assert (i**i2).is_rational is None
1012
+ assert (r**i).is_rational is None
1013
+ assert (r**r).is_rational is None
1014
+ assert (r**x).is_rational is None
1015
+ assert (nr**i).is_rational is None # issue 8598
1016
+ assert (nr**Symbol('z', zero=True)).is_rational
1017
+ assert sin(1).is_rational is False
1018
+ assert sin(ni).is_rational is False
1019
+ assert sin(rn).is_rational is False
1020
+ assert sin(x).is_rational is None
1021
+ assert asin(r).is_rational is False
1022
+ assert sin(asin(3), evaluate=False).is_rational is True
1023
+
1024
+
1025
+ @XFAIL
1026
+ def test_issue_6275():
1027
+ x = Symbol('x')
1028
+ # both zero or both Muls...but neither "change would be very appreciated.
1029
+ # This is similar to x/x => 1 even though if x = 0, it is really nan.
1030
+ assert isinstance(x*0, type(0*S.Infinity))
1031
+ if 0*S.Infinity is S.NaN:
1032
+ b = Symbol('b', finite=None)
1033
+ assert (b*0).is_zero is None
1034
+
1035
+
1036
+ def test_sanitize_assumptions():
1037
+ # issue 6666
1038
+ for cls in (Symbol, Dummy, Wild):
1039
+ x = cls('x', real=1, positive=0)
1040
+ assert x.is_real is True
1041
+ assert x.is_positive is False
1042
+ assert cls('', real=True, positive=None).is_positive is None
1043
+ raises(ValueError, lambda: cls('', commutative=None))
1044
+ raises(ValueError, lambda: Symbol._sanitize({"commutative": None}))
1045
+
1046
+
1047
+ def test_special_assumptions():
1048
+ e = -3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2
1049
+ assert simplify(e < 0) is S.false
1050
+ assert simplify(e > 0) is S.false
1051
+ assert (e == 0) is False # it's not a literal 0
1052
+ assert e.equals(0) is True
1053
+
1054
+
1055
+ def test_inconsistent():
1056
+ # cf. issues 5795 and 5545
1057
+ raises(InconsistentAssumptions, lambda: Symbol('x', real=True,
1058
+ commutative=False))
1059
+
1060
+
1061
+ def test_issue_6631():
1062
+ assert ((-1)**(I)).is_real is True
1063
+ assert ((-1)**(I*2)).is_real is True
1064
+ assert ((-1)**(I/2)).is_real is True
1065
+ assert ((-1)**(I*S.Pi)).is_real is True
1066
+ assert (I**(I + 2)).is_real is True
1067
+
1068
+
1069
+ def test_issue_2730():
1070
+ assert (1/(1 + I)).is_real is False
1071
+
1072
+
1073
+ def test_issue_4149():
1074
+ assert (3 + I).is_complex
1075
+ assert (3 + I).is_imaginary is False
1076
+ assert (3*I + S.Pi*I).is_imaginary
1077
+ # as Zero.is_imaginary is False, see issue 7649
1078
+ y = Symbol('y', real=True)
1079
+ assert (3*I + S.Pi*I + y*I).is_imaginary is None
1080
+ p = Symbol('p', positive=True)
1081
+ assert (3*I + S.Pi*I + p*I).is_imaginary
1082
+ n = Symbol('n', negative=True)
1083
+ assert (-3*I - S.Pi*I + n*I).is_imaginary
1084
+
1085
+ i = Symbol('i', imaginary=True)
1086
+ assert ([(i**a).is_imaginary for a in range(4)] ==
1087
+ [False, True, False, True])
1088
+
1089
+ # tests from the PR #7887:
1090
+ e = S("-sqrt(3)*I/2 + 0.866025403784439*I")
1091
+ assert e.is_real is False
1092
+ assert e.is_imaginary
1093
+
1094
+
1095
+ def test_issue_2920():
1096
+ n = Symbol('n', negative=True)
1097
+ assert sqrt(n).is_imaginary
1098
+
1099
+
1100
+ def test_issue_7899():
1101
+ x = Symbol('x', real=True)
1102
+ assert (I*x).is_real is None
1103
+ assert ((x - I)*(x - 1)).is_zero is None
1104
+ assert ((x - I)*(x - 1)).is_real is None
1105
+
1106
+
1107
+ @XFAIL
1108
+ def test_issue_7993():
1109
+ x = Dummy(integer=True)
1110
+ y = Dummy(noninteger=True)
1111
+ assert (x - y).is_zero is False
1112
+
1113
+
1114
+ def test_issue_8075():
1115
+ raises(InconsistentAssumptions, lambda: Dummy(zero=True, finite=False))
1116
+ raises(InconsistentAssumptions, lambda: Dummy(zero=True, infinite=True))
1117
+
1118
+
1119
+ def test_issue_8642():
1120
+ x = Symbol('x', real=True, integer=False)
1121
+ assert (x*2).is_integer is None, (x*2).is_integer
1122
+
1123
+
1124
+ def test_issues_8632_8633_8638_8675_8992():
1125
+ p = Dummy(integer=True, positive=True)
1126
+ nn = Dummy(integer=True, nonnegative=True)
1127
+ assert (p - S.Half).is_positive
1128
+ assert (p - 1).is_nonnegative
1129
+ assert (nn + 1).is_positive
1130
+ assert (-p + 1).is_nonpositive
1131
+ assert (-nn - 1).is_negative
1132
+ prime = Dummy(prime=True)
1133
+ assert (prime - 2).is_nonnegative
1134
+ assert (prime - 3).is_nonnegative is None
1135
+ even = Dummy(positive=True, even=True)
1136
+ assert (even - 2).is_nonnegative
1137
+
1138
+ p = Dummy(positive=True)
1139
+ assert (p/(p + 1) - 1).is_negative
1140
+ assert ((p + 2)**3 - S.Half).is_positive
1141
+ n = Dummy(negative=True)
1142
+ assert (n - 3).is_nonpositive
1143
+
1144
+
1145
+ def test_issue_9115_9150():
1146
+ n = Dummy('n', integer=True, nonnegative=True)
1147
+ assert (factorial(n) >= 1) == True
1148
+ assert (factorial(n) < 1) == False
1149
+
1150
+ assert factorial(n + 1).is_even is None
1151
+ assert factorial(n + 2).is_even is True
1152
+ assert factorial(n + 2) >= 2
1153
+
1154
+
1155
+ def test_issue_9165():
1156
+ z = Symbol('z', zero=True)
1157
+ f = Symbol('f', finite=False)
1158
+ assert 0/z is S.NaN
1159
+ assert 0*(1/z) is S.NaN
1160
+ assert 0*f is S.NaN
1161
+
1162
+
1163
+ def test_issue_10024():
1164
+ x = Dummy('x')
1165
+ assert Mod(x, 2*pi).is_zero is None
1166
+
1167
+
1168
+ def test_issue_10302():
1169
+ x = Symbol('x')
1170
+ r = Symbol('r', real=True)
1171
+ u = -(3*2**pi)**(1/pi) + 2*3**(1/pi)
1172
+ i = u + u*I
1173
+
1174
+ assert i.is_real is None # w/o simplification this should fail
1175
+ assert (u + i).is_zero is None
1176
+ assert (1 + i).is_zero is False
1177
+
1178
+ a = Dummy('a', zero=True)
1179
+ assert (a + I).is_zero is False
1180
+ assert (a + r*I).is_zero is None
1181
+ assert (a + I).is_imaginary
1182
+ assert (a + x + I).is_imaginary is None
1183
+ assert (a + r*I + I).is_imaginary is None
1184
+
1185
+
1186
+ def test_complex_reciprocal_imaginary():
1187
+ assert (1 / (4 + 3*I)).is_imaginary is False
1188
+
1189
+
1190
+ def test_issue_16313():
1191
+ x = Symbol('x', extended_real=False)
1192
+ k = Symbol('k', real=True)
1193
+ l = Symbol('l', real=True, zero=False)
1194
+ assert (-x).is_real is False
1195
+ assert (k*x).is_real is None # k can be zero also
1196
+ assert (l*x).is_real is False
1197
+ assert (l*x*x).is_real is None # since x*x can be a real number
1198
+ assert (-x).is_positive is False
1199
+
1200
+
1201
+ def test_issue_16579():
1202
+ # extended_real -> finite | infinite
1203
+ x = Symbol('x', extended_real=True, infinite=False)
1204
+ y = Symbol('y', extended_real=True, finite=False)
1205
+ assert x.is_finite is True
1206
+ assert y.is_infinite is True
1207
+
1208
+ # With PR 16978, complex now implies finite
1209
+ c = Symbol('c', complex=True)
1210
+ assert c.is_finite is True
1211
+ raises(InconsistentAssumptions, lambda: Dummy(complex=True, finite=False))
1212
+
1213
+ # Now infinite == !finite
1214
+ nf = Symbol('nf', finite=False)
1215
+ assert nf.is_infinite is True
1216
+
1217
+
1218
+ def test_issue_17556():
1219
+ z = I*oo
1220
+ assert z.is_imaginary is False
1221
+ assert z.is_finite is False
1222
+
1223
+
1224
+ def test_issue_21651():
1225
+ k = Symbol('k', positive=True, integer=True)
1226
+ exp = 2*2**(-k)
1227
+ assert exp.is_integer is None
1228
+
1229
+
1230
+ def test_assumptions_copy():
1231
+ assert assumptions(Symbol('x'), {"commutative": True}
1232
+ ) == {'commutative': True}
1233
+ assert assumptions(Symbol('x'), ['integer']) == {}
1234
+ assert assumptions(Symbol('x'), ['commutative']
1235
+ ) == {'commutative': True}
1236
+ assert assumptions(Symbol('x')) == {'commutative': True}
1237
+ assert assumptions(1)['positive']
1238
+ assert assumptions(3 + I) == {
1239
+ 'algebraic': True,
1240
+ 'commutative': True,
1241
+ 'complex': True,
1242
+ 'composite': False,
1243
+ 'even': False,
1244
+ 'extended_negative': False,
1245
+ 'extended_nonnegative': False,
1246
+ 'extended_nonpositive': False,
1247
+ 'extended_nonzero': False,
1248
+ 'extended_positive': False,
1249
+ 'extended_real': False,
1250
+ 'finite': True,
1251
+ 'imaginary': False,
1252
+ 'infinite': False,
1253
+ 'integer': False,
1254
+ 'irrational': False,
1255
+ 'negative': False,
1256
+ 'noninteger': False,
1257
+ 'nonnegative': False,
1258
+ 'nonpositive': False,
1259
+ 'nonzero': False,
1260
+ 'odd': False,
1261
+ 'positive': False,
1262
+ 'prime': False,
1263
+ 'rational': False,
1264
+ 'real': False,
1265
+ 'transcendental': False,
1266
+ 'zero': False}
1267
+
1268
+
1269
+ def test_check_assumptions():
1270
+ assert check_assumptions(1, 0) is False
1271
+ x = Symbol('x', positive=True)
1272
+ assert check_assumptions(1, x) is True
1273
+ assert check_assumptions(1, 1) is True
1274
+ assert check_assumptions(-1, 1) is False
1275
+ i = Symbol('i', integer=True)
1276
+ # don't know if i is positive (or prime, etc...)
1277
+ assert check_assumptions(i, 1) is None
1278
+ assert check_assumptions(Dummy(integer=None), integer=True) is None
1279
+ assert check_assumptions(Dummy(integer=None), integer=False) is None
1280
+ assert check_assumptions(Dummy(integer=False), integer=True) is False
1281
+ assert check_assumptions(Dummy(integer=True), integer=False) is False
1282
+ # no T/F assumptions to check
1283
+ assert check_assumptions(Dummy(integer=False), integer=None) is True
1284
+ raises(ValueError, lambda: check_assumptions(2*x, x, positive=True))
1285
+
1286
+
1287
+ def test_failing_assumptions():
1288
+ x = Symbol('x', positive=True)
1289
+ y = Symbol('y')
1290
+ assert failing_assumptions(6*x + y, **x.assumptions0) == \
1291
+ {'real': None, 'imaginary': None, 'complex': None, 'hermitian': None,
1292
+ 'positive': None, 'nonpositive': None, 'nonnegative': None, 'nonzero': None,
1293
+ 'negative': None, 'zero': None, 'extended_real': None, 'finite': None,
1294
+ 'infinite': None, 'extended_negative': None, 'extended_nonnegative': None,
1295
+ 'extended_nonpositive': None, 'extended_nonzero': None,
1296
+ 'extended_positive': None }
1297
+
1298
+
1299
+ def test_common_assumptions():
1300
+ assert common_assumptions([0, 1, 2]
1301
+ ) == {'algebraic': True, 'irrational': False, 'hermitian':
1302
+ True, 'extended_real': True, 'real': True, 'extended_negative':
1303
+ False, 'extended_nonnegative': True, 'integer': True,
1304
+ 'rational': True, 'imaginary': False, 'complex': True,
1305
+ 'commutative': True,'noninteger': False, 'composite': False,
1306
+ 'infinite': False, 'nonnegative': True, 'finite': True,
1307
+ 'transcendental': False,'negative': False}
1308
+ assert common_assumptions([0, 1, 2], 'positive integer'.split()
1309
+ ) == {'integer': True}
1310
+ assert common_assumptions([0, 1, 2], []) == {}
1311
+ assert common_assumptions([], ['integer']) == {}
1312
+ assert common_assumptions([0], ['integer']) == {'integer': True}
1313
+
1314
+ def test_pre_generated_assumption_rules_are_valid():
1315
+ # check the pre-generated assumptions match freshly generated assumptions
1316
+ # if this check fails, consider updating the assumptions
1317
+ # see sympy.core.assumptions._generate_assumption_rules
1318
+ pre_generated_assumptions =_load_pre_generated_assumption_rules()
1319
+ generated_assumptions =_generate_assumption_rules()
1320
+ assert pre_generated_assumptions._to_python() == generated_assumptions._to_python(), "pre-generated assumptions are invalid, see sympy.core.assumptions._generate_assumption_rules"
1321
+
1322
+
1323
+ def test_ask_shuffle():
1324
+ grp = PermutationGroup(Permutation(1, 0, 2), Permutation(2, 1, 3))
1325
+
1326
+ seed(123)
1327
+ first = grp.random()
1328
+ seed(123)
1329
+ simplify(I)
1330
+ second = grp.random()
1331
+ seed(123)
1332
+ simplify(-I)
1333
+ third = grp.random()
1334
+
1335
+ assert first == second == third
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_basic.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This tests sympy/core/basic.py with (ideally) no reference to subclasses
2
+ of Basic or Atom."""
3
+
4
+ import collections
5
+
6
+ from sympy.assumptions.ask import Q
7
+ from sympy.core.basic import (Basic, Atom, as_Basic,
8
+ _atomic, _aresame)
9
+ from sympy.core.containers import Tuple
10
+ from sympy.core.function import Function, Lambda
11
+ from sympy.core.numbers import I, pi
12
+ from sympy.core.singleton import S
13
+ from sympy.core.symbol import symbols, Symbol, Dummy
14
+ from sympy.concrete.summations import Sum
15
+ from sympy.functions.elementary.trigonometric import (cos, sin)
16
+ from sympy.functions.special.gamma_functions import gamma
17
+ from sympy.integrals.integrals import Integral
18
+ from sympy.functions.elementary.exponential import exp
19
+ from sympy.testing.pytest import raises, warns_deprecated_sympy
20
+
21
+ b1 = Basic()
22
+ b2 = Basic(b1)
23
+ b3 = Basic(b2)
24
+ b21 = Basic(b2, b1)
25
+
26
+
27
+ def test__aresame():
28
+ assert not _aresame(Basic(Tuple()), Basic())
29
+ assert not _aresame(Basic(S(2)), Basic(S(2.)))
30
+
31
+
32
+ def test_structure():
33
+ assert b21.args == (b2, b1)
34
+ assert b21.func(*b21.args) == b21
35
+ assert bool(b1)
36
+
37
+
38
+ def test_immutable():
39
+ assert not hasattr(b1, '__dict__')
40
+ with raises(AttributeError):
41
+ b1.x = 1
42
+
43
+
44
+ def test_equality():
45
+ instances = [b1, b2, b3, b21, Basic(b1, b1, b1), Basic]
46
+ for i, b_i in enumerate(instances):
47
+ for j, b_j in enumerate(instances):
48
+ assert (b_i == b_j) == (i == j)
49
+ assert (b_i != b_j) == (i != j)
50
+
51
+ assert Basic() != []
52
+ assert not(Basic() == [])
53
+ assert Basic() != 0
54
+ assert not(Basic() == 0)
55
+
56
+ class Foo:
57
+ """
58
+ Class that is unaware of Basic, and relies on both classes returning
59
+ the NotImplemented singleton for equivalence to evaluate to False.
60
+
61
+ """
62
+
63
+ b = Basic()
64
+ foo = Foo()
65
+
66
+ assert b != foo
67
+ assert foo != b
68
+ assert not b == foo
69
+ assert not foo == b
70
+
71
+ class Bar:
72
+ """
73
+ Class that considers itself equal to any instance of Basic, and relies
74
+ on Basic returning the NotImplemented singleton in order to achieve
75
+ a symmetric equivalence relation.
76
+
77
+ """
78
+ def __eq__(self, other):
79
+ if isinstance(other, Basic):
80
+ return True
81
+ return NotImplemented
82
+
83
+ def __ne__(self, other):
84
+ return not self == other
85
+
86
+ bar = Bar()
87
+
88
+ assert b == bar
89
+ assert bar == b
90
+ assert not b != bar
91
+ assert not bar != b
92
+
93
+
94
+ def test_matches_basic():
95
+ instances = [Basic(b1, b1, b2), Basic(b1, b2, b1), Basic(b2, b1, b1),
96
+ Basic(b1, b2), Basic(b2, b1), b2, b1]
97
+ for i, b_i in enumerate(instances):
98
+ for j, b_j in enumerate(instances):
99
+ if i == j:
100
+ assert b_i.matches(b_j) == {}
101
+ else:
102
+ assert b_i.matches(b_j) is None
103
+ assert b1.match(b1) == {}
104
+
105
+
106
+ def test_has():
107
+ assert b21.has(b1)
108
+ assert b21.has(b3, b1)
109
+ assert b21.has(Basic)
110
+ assert not b1.has(b21, b3)
111
+ assert not b21.has()
112
+ assert not b21.has(str)
113
+ assert not Symbol("x").has("x")
114
+
115
+
116
+ def test_subs():
117
+ assert b21.subs(b2, b1) == Basic(b1, b1)
118
+ assert b21.subs(b2, b21) == Basic(b21, b1)
119
+ assert b3.subs(b2, b1) == b2
120
+
121
+ assert b21.subs([(b2, b1), (b1, b2)]) == Basic(b2, b2)
122
+
123
+ assert b21.subs({b1: b2, b2: b1}) == Basic(b2, b2)
124
+ assert b21.subs(collections.ChainMap({b1: b2}, {b2: b1})) == Basic(b2, b2)
125
+ assert b21.subs(collections.OrderedDict([(b2, b1), (b1, b2)])) == Basic(b2, b2)
126
+
127
+ raises(ValueError, lambda: b21.subs('bad arg'))
128
+ raises(ValueError, lambda: b21.subs(b1, b2, b3))
129
+ # dict(b1=foo) creates a string 'b1' but leaves foo unchanged; subs
130
+ # will convert the first to a symbol but will raise an error if foo
131
+ # cannot be sympified; sympification is strict if foo is not string
132
+ raises(ValueError, lambda: b21.subs(b1='bad arg'))
133
+
134
+ assert Symbol("text").subs({"text": b1}) == b1
135
+ assert Symbol("s").subs({"s": 1}) == 1
136
+
137
+
138
+ def test_subs_with_unicode_symbols():
139
+ expr = Symbol('var1')
140
+ replaced = expr.subs('var1', 'x')
141
+ assert replaced.name == 'x'
142
+
143
+ replaced = expr.subs('var1', 'x')
144
+ assert replaced.name == 'x'
145
+
146
+
147
+ def test_atoms():
148
+ assert b21.atoms() == {Basic()}
149
+
150
+
151
+ def test_free_symbols_empty():
152
+ assert b21.free_symbols == set()
153
+
154
+
155
+ def test_doit():
156
+ assert b21.doit() == b21
157
+ assert b21.doit(deep=False) == b21
158
+
159
+
160
+ def test_S():
161
+ assert repr(S) == 'S'
162
+
163
+
164
+ def test_xreplace():
165
+ assert b21.xreplace({b2: b1}) == Basic(b1, b1)
166
+ assert b21.xreplace({b2: b21}) == Basic(b21, b1)
167
+ assert b3.xreplace({b2: b1}) == b2
168
+ assert Basic(b1, b2).xreplace({b1: b2, b2: b1}) == Basic(b2, b1)
169
+ assert Atom(b1).xreplace({b1: b2}) == Atom(b1)
170
+ assert Atom(b1).xreplace({Atom(b1): b2}) == b2
171
+ raises(TypeError, lambda: b1.xreplace())
172
+ raises(TypeError, lambda: b1.xreplace([b1, b2]))
173
+ for f in (exp, Function('f')):
174
+ assert f.xreplace({}) == f
175
+ assert f.xreplace({}, hack2=True) == f
176
+ assert f.xreplace({f: b1}) == b1
177
+ assert f.xreplace({f: b1}, hack2=True) == b1
178
+
179
+
180
+ def test_sorted_args():
181
+ x = symbols('x')
182
+ assert b21._sorted_args == b21.args
183
+ raises(AttributeError, lambda: x._sorted_args)
184
+
185
+ def test_call():
186
+ x, y = symbols('x y')
187
+ # See the long history of this in issues 5026 and 5105.
188
+
189
+ raises(TypeError, lambda: sin(x)({ x : 1, sin(x) : 2}))
190
+ raises(TypeError, lambda: sin(x)(1))
191
+
192
+ # No effect as there are no callables
193
+ assert sin(x).rcall(1) == sin(x)
194
+ assert (1 + sin(x)).rcall(1) == 1 + sin(x)
195
+
196
+ # Effect in the pressence of callables
197
+ l = Lambda(x, 2*x)
198
+ assert (l + x).rcall(y) == 2*y + x
199
+ assert (x**l).rcall(2) == x**4
200
+ # TODO UndefinedFunction does not subclass Expr
201
+ #f = Function('f')
202
+ #assert (2*f)(x) == 2*f(x)
203
+
204
+ assert (Q.real & Q.positive).rcall(x) == Q.real(x) & Q.positive(x)
205
+
206
+
207
+ def test_rewrite():
208
+ x, y, z = symbols('x y z')
209
+ a, b = symbols('a b')
210
+ f1 = sin(x) + cos(x)
211
+ assert f1.rewrite(cos,exp) == exp(I*x)/2 + sin(x) + exp(-I*x)/2
212
+ assert f1.rewrite([cos],sin) == sin(x) + sin(x + pi/2, evaluate=False)
213
+ f2 = sin(x) + cos(y)/gamma(z)
214
+ assert f2.rewrite(sin,exp) == -I*(exp(I*x) - exp(-I*x))/2 + cos(y)/gamma(z)
215
+
216
+ assert f1.rewrite() == f1
217
+
218
+ def test_literal_evalf_is_number_is_zero_is_comparable():
219
+ x = symbols('x')
220
+ f = Function('f')
221
+
222
+ # issue 5033
223
+ assert f.is_number is False
224
+ # issue 6646
225
+ assert f(1).is_number is False
226
+ i = Integral(0, (x, x, x))
227
+ # expressions that are symbolically 0 can be difficult to prove
228
+ # so in case there is some easy way to know if something is 0
229
+ # it should appear in the is_zero property for that object;
230
+ # if is_zero is true evalf should always be able to compute that
231
+ # zero
232
+ assert i.n() == 0
233
+ assert i.is_zero
234
+ assert i.is_number is False
235
+ assert i.evalf(2, strict=False) == 0
236
+
237
+ # issue 10268
238
+ n = sin(1)**2 + cos(1)**2 - 1
239
+ assert n.is_comparable is False
240
+ assert n.n(2).is_comparable is False
241
+ assert n.n(2).n(2).is_comparable
242
+
243
+
244
+ def test_as_Basic():
245
+ assert as_Basic(1) is S.One
246
+ assert as_Basic(()) == Tuple()
247
+ raises(TypeError, lambda: as_Basic([]))
248
+
249
+
250
+ def test_atomic():
251
+ g, h = map(Function, 'gh')
252
+ x = symbols('x')
253
+ assert _atomic(g(x + h(x))) == {g(x + h(x))}
254
+ assert _atomic(g(x + h(x)), recursive=True) == {h(x), x, g(x + h(x))}
255
+ assert _atomic(1) == set()
256
+ assert _atomic(Basic(S(1), S(2))) == set()
257
+
258
+
259
+ def test_as_dummy():
260
+ u, v, x, y, z, _0, _1 = symbols('u v x y z _0 _1')
261
+ assert Lambda(x, x + 1).as_dummy() == Lambda(_0, _0 + 1)
262
+ assert Lambda(x, x + _0).as_dummy() == Lambda(_1, _0 + _1)
263
+ eq = (1 + Sum(x, (x, 1, x)))
264
+ ans = 1 + Sum(_0, (_0, 1, x))
265
+ once = eq.as_dummy()
266
+ assert once == ans
267
+ twice = once.as_dummy()
268
+ assert twice == ans
269
+ assert Integral(x + _0, (x, x + 1), (_0, 1, 2)
270
+ ).as_dummy() == Integral(_0 + _1, (_0, x + 1), (_1, 1, 2))
271
+ for T in (Symbol, Dummy):
272
+ d = T('x', real=True)
273
+ D = d.as_dummy()
274
+ assert D != d and D.func == Dummy and D.is_real is None
275
+ assert Dummy().as_dummy().is_commutative
276
+ assert Dummy(commutative=False).as_dummy().is_commutative is False
277
+
278
+
279
+ def test_canonical_variables():
280
+ x, i0, i1 = symbols('x _:2')
281
+ assert Integral(x, (x, x + 1)).canonical_variables == {x: i0}
282
+ assert Integral(x, (x, x + 1), (i0, 1, 2)).canonical_variables == {
283
+ x: i0, i0: i1}
284
+ assert Integral(x, (x, x + i0)).canonical_variables == {x: i1}
285
+
286
+
287
+ def test_replace_exceptions():
288
+ from sympy.core.symbol import Wild
289
+ x, y = symbols('x y')
290
+ e = (x**2 + x*y)
291
+ raises(TypeError, lambda: e.replace(sin, 2))
292
+ b = Wild('b')
293
+ c = Wild('c')
294
+ raises(TypeError, lambda: e.replace(b*c, c.is_real))
295
+ raises(TypeError, lambda: e.replace(b.is_real, 1))
296
+ raises(TypeError, lambda: e.replace(lambda d: d.is_Number, 1))
297
+
298
+
299
+ def test_ManagedProperties():
300
+ # ManagedProperties is now deprecated. Here we do our best to check that if
301
+ # someone is using it then it does work in the way that it previously did
302
+ # but gives a deprecation warning.
303
+ from sympy.core.assumptions import ManagedProperties
304
+
305
+ myclasses = []
306
+
307
+ class MyMeta(ManagedProperties):
308
+ def __init__(cls, *args, **kwargs):
309
+ myclasses.append('executed')
310
+ super().__init__(*args, **kwargs)
311
+
312
+ code = """
313
+ class MySubclass(Basic, metaclass=MyMeta):
314
+ pass
315
+ """
316
+ with warns_deprecated_sympy():
317
+ exec(code)
318
+
319
+ assert myclasses == ['executed']
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_cache.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from sympy.core.cache import cacheit, cached_property, lazy_function
3
+ from sympy.testing.pytest import raises
4
+
5
+ def test_cacheit_doc():
6
+ @cacheit
7
+ def testfn():
8
+ "test docstring"
9
+ pass
10
+
11
+ assert testfn.__doc__ == "test docstring"
12
+ assert testfn.__name__ == "testfn"
13
+
14
+ def test_cacheit_unhashable():
15
+ @cacheit
16
+ def testit(x):
17
+ return x
18
+
19
+ assert testit(1) == 1
20
+ assert testit(1) == 1
21
+ a = {}
22
+ assert testit(a) == {}
23
+ a[1] = 2
24
+ assert testit(a) == {1: 2}
25
+
26
+ def test_cachit_exception():
27
+ # Make sure the cache doesn't call functions multiple times when they
28
+ # raise TypeError
29
+
30
+ a = []
31
+
32
+ @cacheit
33
+ def testf(x):
34
+ a.append(0)
35
+ raise TypeError
36
+
37
+ raises(TypeError, lambda: testf(1))
38
+ assert len(a) == 1
39
+
40
+ a.clear()
41
+ # Unhashable type
42
+ raises(TypeError, lambda: testf([]))
43
+ assert len(a) == 1
44
+
45
+ @cacheit
46
+ def testf2(x):
47
+ a.append(0)
48
+ raise TypeError("Error")
49
+
50
+ a.clear()
51
+ raises(TypeError, lambda: testf2(1))
52
+ assert len(a) == 1
53
+
54
+ a.clear()
55
+ # Unhashable type
56
+ raises(TypeError, lambda: testf2([]))
57
+ assert len(a) == 1
58
+
59
+ def test_cached_property():
60
+ class A:
61
+ def __init__(self, value):
62
+ self.value = value
63
+ self.calls = 0
64
+
65
+ @cached_property
66
+ def prop(self):
67
+ self.calls = self.calls + 1
68
+ return self.value
69
+
70
+ a = A(2)
71
+ assert a.calls == 0
72
+ assert a.prop == 2
73
+ assert a.calls == 1
74
+ assert a.prop == 2
75
+ assert a.calls == 1
76
+ b = A(None)
77
+ assert b.prop == None
78
+
79
+
80
+ def test_lazy_function():
81
+ module_name='xmlrpc.client'
82
+ function_name = 'gzip_decode'
83
+ lazy = lazy_function(module_name, function_name)
84
+ assert lazy(b'') == b''
85
+ assert module_name in sys.modules
86
+ assert function_name in str(lazy)
87
+ repr_lazy = repr(lazy)
88
+ assert 'LazyFunction' in repr_lazy
89
+ assert function_name in repr_lazy
90
+
91
+ lazy = lazy_function('sympy.core.cache', 'cheap')
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_compatibility.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from sympy.testing.pytest import warns_deprecated_sympy
2
+
3
+ def test_compatibility_submodule():
4
+ # Test the sympy.core.compatibility deprecation warning
5
+ with warns_deprecated_sympy():
6
+ import sympy.core.compatibility # noqa:F401
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_complex.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import expand_complex
2
+ from sympy.core.numbers import (I, Integer, Rational, pi)
3
+ from sympy.core.power import Pow
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import (Symbol, symbols)
6
+ from sympy.functions.elementary.complexes import (Abs, conjugate, im, re, sign)
7
+ from sympy.functions.elementary.exponential import exp
8
+ from sympy.functions.elementary.hyperbolic import (cosh, coth, sinh, tanh)
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.functions.elementary.trigonometric import (cos, cot, sin, tan)
11
+
12
+ def test_complex():
13
+ a = Symbol("a", real=True)
14
+ b = Symbol("b", real=True)
15
+ e = (a + I*b)*(a - I*b)
16
+ assert e.expand() == a**2 + b**2
17
+ assert sqrt(I) == Pow(I, S.Half)
18
+
19
+
20
+ def test_conjugate():
21
+ a = Symbol("a", real=True)
22
+ b = Symbol("b", real=True)
23
+ c = Symbol("c", imaginary=True)
24
+ d = Symbol("d", imaginary=True)
25
+ x = Symbol('x')
26
+ z = a + I*b + c + I*d
27
+ zc = a - I*b - c + I*d
28
+ assert conjugate(z) == zc
29
+ assert conjugate(exp(z)) == exp(zc)
30
+ assert conjugate(exp(I*x)) == exp(-I*conjugate(x))
31
+ assert conjugate(z**5) == zc**5
32
+ assert conjugate(abs(x)) == abs(x)
33
+ assert conjugate(sign(z)) == sign(zc)
34
+ assert conjugate(sin(z)) == sin(zc)
35
+ assert conjugate(cos(z)) == cos(zc)
36
+ assert conjugate(tan(z)) == tan(zc)
37
+ assert conjugate(cot(z)) == cot(zc)
38
+ assert conjugate(sinh(z)) == sinh(zc)
39
+ assert conjugate(cosh(z)) == cosh(zc)
40
+ assert conjugate(tanh(z)) == tanh(zc)
41
+ assert conjugate(coth(z)) == coth(zc)
42
+
43
+
44
+ def test_abs1():
45
+ a = Symbol("a", real=True)
46
+ b = Symbol("b", real=True)
47
+ assert abs(a) == Abs(a)
48
+ assert abs(-a) == abs(a)
49
+ assert abs(a + I*b) == sqrt(a**2 + b**2)
50
+
51
+
52
+ def test_abs2():
53
+ a = Symbol("a", real=False)
54
+ b = Symbol("b", real=False)
55
+ assert abs(a) != a
56
+ assert abs(-a) != a
57
+ assert abs(a + I*b) != sqrt(a**2 + b**2)
58
+
59
+
60
+ def test_evalc():
61
+ x = Symbol("x", real=True)
62
+ y = Symbol("y", real=True)
63
+ z = Symbol("z")
64
+ assert ((x + I*y)**2).expand(complex=True) == x**2 + 2*I*x*y - y**2
65
+ assert expand_complex(z**(2*I)) == (re((re(z) + I*im(z))**(2*I)) +
66
+ I*im((re(z) + I*im(z))**(2*I)))
67
+ assert expand_complex(
68
+ z**(2*I), deep=False) == I*im(z**(2*I)) + re(z**(2*I))
69
+
70
+ assert exp(I*x) != cos(x) + I*sin(x)
71
+ assert exp(I*x).expand(complex=True) == cos(x) + I*sin(x)
72
+ assert exp(I*x + y).expand(complex=True) == exp(y)*cos(x) + I*sin(x)*exp(y)
73
+
74
+ assert sin(I*x).expand(complex=True) == I * sinh(x)
75
+ assert sin(x + I*y).expand(complex=True) == sin(x)*cosh(y) + \
76
+ I * sinh(y) * cos(x)
77
+
78
+ assert cos(I*x).expand(complex=True) == cosh(x)
79
+ assert cos(x + I*y).expand(complex=True) == cos(x)*cosh(y) - \
80
+ I * sinh(y) * sin(x)
81
+
82
+ assert tan(I*x).expand(complex=True) == tanh(x) * I
83
+ assert tan(x + I*y).expand(complex=True) == (
84
+ sin(2*x)/(cos(2*x) + cosh(2*y)) +
85
+ I*sinh(2*y)/(cos(2*x) + cosh(2*y)))
86
+
87
+ assert sinh(I*x).expand(complex=True) == I * sin(x)
88
+ assert sinh(x + I*y).expand(complex=True) == sinh(x)*cos(y) + \
89
+ I * sin(y) * cosh(x)
90
+
91
+ assert cosh(I*x).expand(complex=True) == cos(x)
92
+ assert cosh(x + I*y).expand(complex=True) == cosh(x)*cos(y) + \
93
+ I * sin(y) * sinh(x)
94
+
95
+ assert tanh(I*x).expand(complex=True) == tan(x) * I
96
+ assert tanh(x + I*y).expand(complex=True) == (
97
+ (sinh(x)*cosh(x) + I*cos(y)*sin(y)) /
98
+ (sinh(x)**2 + cos(y)**2)).expand()
99
+
100
+
101
+ def test_pythoncomplex():
102
+ x = Symbol("x")
103
+ assert 4j*x != 4*x*I
104
+ assert 4j*x == 4.0*x*I
105
+ assert 4.1j*x != 4*x*I
106
+
107
+
108
+ def test_rootcomplex():
109
+ R = Rational
110
+ assert ((+1 + I)**R(1, 2)).expand(
111
+ complex=True) == 2**R(1, 4)*cos( pi/8) + 2**R(1, 4)*sin( pi/8)*I
112
+ assert ((-1 - I)**R(1, 2)).expand(
113
+ complex=True) == 2**R(1, 4)*cos(3*pi/8) - 2**R(1, 4)*sin(3*pi/8)*I
114
+ assert (sqrt(-10)*I).as_real_imag() == (-sqrt(10), 0)
115
+
116
+
117
+ def test_expand_inverse():
118
+ assert (1/(1 + I)).expand(complex=True) == (1 - I)/2
119
+ assert ((1 + 2*I)**(-2)).expand(complex=True) == (-3 - 4*I)/25
120
+ assert ((1 + I)**(-8)).expand(complex=True) == Rational(1, 16)
121
+
122
+
123
+ def test_expand_complex():
124
+ assert ((2 + 3*I)**10).expand(complex=True) == -341525 - 145668*I
125
+ # the following two tests are to ensure the SymPy uses an efficient
126
+ # algorithm for calculating powers of complex numbers. They should execute
127
+ # in something like 0.01s.
128
+ assert ((2 + 3*I)**1000).expand(complex=True) == \
129
+ -81079464736246615951519029367296227340216902563389546989376269312984127074385455204551402940331021387412262494620336565547972162814110386834027871072723273110439771695255662375718498785908345629702081336606863762777939617745464755635193139022811989314881997210583159045854968310911252660312523907616129080027594310008539817935736331124833163907518549408018652090650537035647520296539436440394920287688149200763245475036722326561143851304795139005599209239350981457301460233967137708519975586996623552182807311159141501424576682074392689622074945519232029999 + \
130
+ 46938745946789557590804551905243206242164799136976022474337918748798900569942573265747576032611189047943842446167719177749107138603040963603119861476016947257034472364028585381714774667326478071264878108114128915685688115488744955550920239128462489496563930809677159214598114273887061533057125164518549173898349061972857446844052995037423459472376202251620778517659247970283904820245958198842631651569984310559418135975795868314764489884749573052997832686979294085577689571149679540256349988338406458116270429842222666345146926395233040564229555893248370000*I
131
+ assert ((2 + 3*I/4)**1000).expand(complex=True) == \
132
+ Integer(1)*37079892761199059751745775382463070250205990218394308874593455293485167797989691280095867197640410033222367257278387021789651672598831503296531725827158233077451476545928116965316544607115843772405184272449644892857783761260737279675075819921259597776770965829089907990486964515784097181964312256560561065607846661496055417619388874421218472707497847700629822858068783288579581649321248495739224020822198695759609598745114438265083593711851665996586461937988748911532242908776883696631067311443171682974330675406616373422505939887984366289623091300746049101284856530270685577940283077888955692921951247230006346681086274961362500646889925803654263491848309446197554307105991537357310209426736453173441104334496173618419659521888945605315751089087820455852582920963561495787655250624781448951403353654348109893478206364632640344111022531861683064175862889459084900614967785405977231549003280842218501570429860550379522498497412180001/114813069527425452423283320117768198402231770208869520047764273682576626139237031385665948631650626991844596463898746277344711896086305533142593135616665318539129989145312280000688779148240044871428926990063486244781615463646388363947317026040466353970904996558162398808944629605623311649536164221970332681344168908984458505602379484807914058900934776500429002716706625830522008132236281291761267883317206598995396418127021779858404042159853183251540889433902091920554957783589672039160081957216630582755380425583726015528348786419432054508915275783882625175435528800822842770817965453762184851149029376 + \
133
+ I*421638390580169706973991429333213477486930178424989246669892530737775352519112934278994501272111385966211392610029433824534634841747911783746811994443436271013377059560245191441549885048056920190833693041257216263519792201852046825443439142932464031501882145407459174948712992271510309541474392303461939389368955986650538525895866713074543004916049550090364398070215427272240155060576252568700906004691224321432509053286859100920489253598392100207663785243368195857086816912514025693453058403158416856847185079684216151337200057494966741268925263085619240941610301610538225414050394612058339070756009433535451561664522479191267503989904464718368605684297071150902631208673621618217106272361061676184840810762902463998065947687814692402219182668782278472952758690939877465065070481351343206840649517150634973307937551168752642148704904383991876969408056379195860410677814566225456558230131911142229028179902418223009651437985670625/1793954211366022694113801876840128100034871409513586250746316776290259783425578615401030447369541046747571819748417910583511123376348523955353017744010395602173906080395504375010762174191250701116076984219741972574712741619474818186676828531882286780795390571221287481389759837587864244524002565968286448146002639202882164150037179450123657170327105882819203167448541028601906377066191895183769810676831353109303069033234715310287563158747705988305326397404720186258671215368588625611876280581509852855552819149745718992630449787803625851701801184123166018366180137512856918294030710215034138299203584
134
+ assert ((2 + 3*I)**-1000).expand(complex=True) == \
135
+ Integer(1)*-81079464736246615951519029367296227340216902563389546989376269312984127074385455204551402940331021387412262494620336565547972162814110386834027871072723273110439771695255662375718498785908345629702081336606863762777939617745464755635193139022811989314881997210583159045854968310911252660312523907616129080027594310008539817935736331124833163907518549408018652090650537035647520296539436440394920287688149200763245475036722326561143851304795139005599209239350981457301460233967137708519975586996623552182807311159141501424576682074392689622074945519232029999/8777125472973511649630750050295188683351430110097915876250894978429797369155961290321829625004920141758416719066805645579710744290541337680113772670040386863849283653078324415471816788604945889094925784900885812724984087843737442111926413818245854362613018058774368703971604921858023116665586358870612944209398056562604561248859926344335598822815885851096698226775053153403320782439987679978321289537645645163767251396759519805603090332694449553371530571613352311006350058217982509738362083094920649452123351717366337410243853659113315547584871655479914439219520157174729130746351059075207407866012574386726064196992865627149566238044625779078186624347183905913357718850537058578084932880569701242598663149911276357125355850792073635533676541250531086757377369962506979378337216411188347761901006460813413505861461267545723590468627854202034450569581626648934062198718362303420281555886394558137408159453103395918783625713213314350531051312551733021627153081075080140680608080529736975658786227362251632725009435866547613598753584705455955419696609282059191031962604169242974038517575645939316377801594539335940001 - Integer(1)*46938745946789557590804551905243206242164799136976022474337918748798900569942573265747576032611189047943842446167719177749107138603040963603119861476016947257034472364028585381714774667326478071264878108114128915685688115488744955550920239128462489496563930809677159214598114273887061533057125164518549173898349061972857446844052995037423459472376202251620778517659247970283904820245958198842631651569984310559418135975795868314764489884749573052997832686979294085577689571149679540256349988338406458116270429842222666345146926395233040564229555893248370000*I/8777125472973511649630750050295188683351430110097915876250894978429797369155961290321829625004920141758416719066805645579710744290541337680113772670040386863849283653078324415471816788604945889094925784900885812724984087843737442111926413818245854362613018058774368703971604921858023116665586358870612944209398056562604561248859926344335598822815885851096698226775053153403320782439987679978321289537645645163767251396759519805603090332694449553371530571613352311006350058217982509738362083094920649452123351717366337410243853659113315547584871655479914439219520157174729130746351059075207407866012574386726064196992865627149566238044625779078186624347183905913357718850537058578084932880569701242598663149911276357125355850792073635533676541250531086757377369962506979378337216411188347761901006460813413505861461267545723590468627854202034450569581626648934062198718362303420281555886394558137408159453103395918783625713213314350531051312551733021627153081075080140680608080529736975658786227362251632725009435866547613598753584705455955419696609282059191031962604169242974038517575645939316377801594539335940001
136
+ assert ((2 + 3*I/4)**-1000).expand(complex=True) == \
137
+ Integer(1)*4257256305661027385394552848555894604806501409793288342610746813288539790051927148781268212212078237301273165351052934681382567968787279534591114913777456610214738290619922068269909423637926549603264174216950025398244509039145410016404821694746262142525173737175066432954496592560621330313807235750500564940782099283410261748370262433487444897446779072067625787246390824312580440138770014838135245148574339248259670887549732495841810961088930810608893772914812838358159009303794863047635845688453859317690488124382253918725010358589723156019888846606295866740117645571396817375322724096486161308083462637370825829567578309445855481578518239186117686659177284332344643124760453112513611749309168470605289172320376911472635805822082051716625171429727162039621902266619821870482519063133136820085579315127038372190224739238686708451840610064871885616258831386810233957438253532027049148030157164346719204500373766157143311767338973363806106967439378604898250533766359989107510507493549529158818602327525235240510049484816090584478644771183158342479140194633579061295740839490629457435283873180259847394582069479062820225159699506175855369539201399183443253793905149785994830358114153241481884290274629611529758663543080724574566578220908907477622643689220814376054314972190402285121776593824615083669045183404206291739005554569305329760211752815718335731118664756831942466773261465213581616104242113894521054475516019456867271362053692785300826523328020796670205463390909136593859765912483565093461468865534470710132881677639651348709376/2103100954337624833663208713697737151593634525061637972297915388685604042449504336765884978184588688426595940401280828953096857809292320006227881797146858511436638446932833617514351442216409828605662238790280753075176269765767010004889778647709740770757817960711900340755635772183674511158570690702969774966791073165467918123298694584729211212414462628433370481195120564586361368504153395406845170075275051749019600057116719726628746724489572189061061036426955163696859127711110719502594479795200686212257570291758725259007379710596548777812659422174199194837355646482046783616494013289495563083118517507178847555801163089723056310287760875135196081975602765511153122381201303871673391366630940702817360340900568748719988954847590748960761446218262344767250783946365392689256634180417145926390656439421745644011831124277463643383712803287985472471755648426749842410972650924240795946699346613614779460399530274263580007672855851663196114585312432954432654691485867618908420370875753749297487803461900447407917655296784879220450937110470920633595689721819488638484547259978337741496090602390463594556401615298457456112485536498177883358587125449801777718900375736758266215245325999241624148841915093787519330809347240990363802360596034171167818310322276373120180985148650099673289383722502488957717848531612020897298448601714154586319660314294591620415272119454982220034319689607295960162971300417552364254983071768070124456169427638371140064235083443242844616326538396503937972586505546495649094344512270582463639152160238137952390380581401171977159154009407415523525096743009110916334144716516647041176989758534635251844947906038080852185583742296318878233394998111078843229681030277039104786225656992262073797524057992347971177720807155842376332851559276430280477639539393920006008737472164850104411971830120295750221200029811143140323763349636629725073624360001 - Integer(1)*3098214262599218784594285246258841485430681674561917573155883806818465520660668045042109232930382494608383663464454841313154390741655282039877410154577448327874989496074260116195788919037407420625081798124301494353693248757853222257918294662198297114746822817460991242508743651430439120439020484502408313310689912381846149597061657483084652685283853595100434135149479564507015504022249330340259111426799121454516345905101620532787348293877485702600390665276070250119465888154331218827342488849948540687659846652377277250614246402784754153678374932540789808703029043827352976139228402417432199779415751301480406673762521987999573209628597459357964214510139892316208670927074795773830798600837815329291912002136924506221066071242281626618211060464126372574400100990746934953437169840312584285942093951405864225230033279614235191326102697164613004299868695519642598882914862568516635347204441042798206770888274175592401790040170576311989738272102077819127459014286741435419468254146418098278519775722104890854275995510700298782146199325790002255362719776098816136732897323406228294203133323296591166026338391813696715894870956511298793595675308998014158717167429941371979636895553724830981754579086664608880698350866487717403917070872269853194118364230971216854931998642990452908852258008095741042117326241406479532880476938937997238098399302185675832474590293188864060116934035867037219176916416481757918864533515526389079998129329045569609325290897577497835388451456680707076072624629697883854217331728051953671643278797380171857920000*I/2103100954337624833663208713697737151593634525061637972297915388685604042449504336765884978184588688426595940401280828953096857809292320006227881797146858511436638446932833617514351442216409828605662238790280753075176269765767010004889778647709740770757817960711900340755635772183674511158570690702969774966791073165467918123298694584729211212414462628433370481195120564586361368504153395406845170075275051749019600057116719726628746724489572189061061036426955163696859127711110719502594479795200686212257570291758725259007379710596548777812659422174199194837355646482046783616494013289495563083118517507178847555801163089723056310287760875135196081975602765511153122381201303871673391366630940702817360340900568748719988954847590748960761446218262344767250783946365392689256634180417145926390656439421745644011831124277463643383712803287985472471755648426749842410972650924240795946699346613614779460399530274263580007672855851663196114585312432954432654691485867618908420370875753749297487803461900447407917655296784879220450937110470920633595689721819488638484547259978337741496090602390463594556401615298457456112485536498177883358587125449801777718900375736758266215245325999241624148841915093787519330809347240990363802360596034171167818310322276373120180985148650099673289383722502488957717848531612020897298448601714154586319660314294591620415272119454982220034319689607295960162971300417552364254983071768070124456169427638371140064235083443242844616326538396503937972586505546495649094344512270582463639152160238137952390380581401171977159154009407415523525096743009110916334144716516647041176989758534635251844947906038080852185583742296318878233394998111078843229681030277039104786225656992262073797524057992347971177720807155842376332851559276430280477639539393920006008737472164850104411971830120295750221200029811143140323763349636629725073624360001
138
+
139
+ a = Symbol('a', real=True)
140
+ b = Symbol('b', real=True)
141
+ assert exp(a*(2 + I*b)).expand(complex=True) == \
142
+ I*exp(2*a)*sin(a*b) + exp(2*a)*cos(a*b)
143
+
144
+
145
+ def test_expand():
146
+ f = (16 - 2*sqrt(29))**2
147
+ assert f.expand() == 372 - 64*sqrt(29)
148
+ f = (Integer(1)/2 + I/2)**10
149
+ assert f.expand() == I/32
150
+ f = (Integer(1)/2 + I)**10
151
+ assert f.expand() == Integer(237)/1024 - 779*I/256
152
+
153
+
154
+ def test_re_im1652():
155
+ x = Symbol('x')
156
+ assert re(x) == re(conjugate(x))
157
+ assert im(x) == - im(conjugate(x))
158
+ assert im(x)*re(conjugate(x)) + im(conjugate(x)) * re(x) == 0
159
+
160
+
161
+ def test_issue_5084():
162
+ x = Symbol('x')
163
+ assert ((x + x*I)/(1 + I)).as_real_imag() == (re((x + I*x)/(1 + I)
164
+ ), im((x + I*x)/(1 + I)))
165
+
166
+
167
+ def test_issue_5236():
168
+ assert (cos(1 + I)**3).as_real_imag() == (-3*sin(1)**2*sinh(1)**2*cos(1)*cosh(1) +
169
+ cos(1)**3*cosh(1)**3, -3*cos(1)**2*cosh(1)**2*sin(1)*sinh(1) + sin(1)**3*sinh(1)**3)
170
+
171
+
172
+ def test_real_imag():
173
+ x, y, z = symbols('x, y, z')
174
+ X, Y, Z = symbols('X, Y, Z', commutative=False)
175
+ a = Symbol('a', real=True)
176
+ assert (2*a*x).as_real_imag() == (2*a*re(x), 2*a*im(x))
177
+
178
+ # issue 5395:
179
+ assert (x*x.conjugate()).as_real_imag() == (Abs(x)**2, 0)
180
+ assert im(x*x.conjugate()) == 0
181
+ assert im(x*y.conjugate()*z*y) == im(x*z)*Abs(y)**2
182
+ assert im(x*y.conjugate()*x*y) == im(x**2)*Abs(y)**2
183
+ assert im(Z*y.conjugate()*X*y) == im(Z*X)*Abs(y)**2
184
+ assert im(X*X.conjugate()) == im(X*X.conjugate(), evaluate=False)
185
+ assert (sin(x)*sin(x).conjugate()).as_real_imag() == \
186
+ (Abs(sin(x))**2, 0)
187
+
188
+ # issue 6573:
189
+ assert (x**2).as_real_imag() == (re(x)**2 - im(x)**2, 2*re(x)*im(x))
190
+
191
+ # issue 6428:
192
+ r = Symbol('r', real=True)
193
+ i = Symbol('i', imaginary=True)
194
+ assert (i*r*x).as_real_imag() == (I*i*r*im(x), -I*i*r*re(x))
195
+ assert (i*r*x*(y + 2)).as_real_imag() == (
196
+ I*i*r*(re(y) + 2)*im(x) + I*i*r*re(x)*im(y),
197
+ -I*i*r*(re(y) + 2)*re(x) + I*i*r*im(x)*im(y))
198
+
199
+ # issue 7106:
200
+ assert ((1 + I)/(1 - I)).as_real_imag() == (0, 1)
201
+ assert ((1 + 2*I)*(1 + 3*I)).as_real_imag() == (-5, 5)
202
+
203
+
204
+ def test_pow_issue_1724():
205
+ e = ((S.NegativeOne)**(S.One/3))
206
+ assert e.conjugate().n() == e.n().conjugate()
207
+ e = S('-2/3 - (-29/54 + sqrt(93)/18)**(1/3) - 1/(9*(-29/54 + sqrt(93)/18)**(1/3))')
208
+ assert e.conjugate().n() == e.n().conjugate()
209
+ e = 2**I
210
+ assert e.conjugate().n() == e.n().conjugate()
211
+
212
+
213
+ def test_issue_5429():
214
+ assert sqrt(I).conjugate() != sqrt(I)
215
+
216
+ def test_issue_4124():
217
+ from sympy.core.numbers import oo
218
+ assert expand_complex(I*oo) == oo*I
219
+
220
+ def test_issue_11518():
221
+ x = Symbol("x", real=True)
222
+ y = Symbol("y", real=True)
223
+ r = sqrt(x**2 + y**2)
224
+ assert conjugate(r) == r
225
+ s = abs(x + I * y)
226
+ assert conjugate(s) == r
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_constructor_postprocessor.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.basic import Basic
2
+ from sympy.core.mul import Mul
3
+ from sympy.core.symbol import (Symbol, symbols)
4
+
5
+ from sympy.testing.pytest import XFAIL
6
+
7
+ class SymbolInMulOnce(Symbol):
8
+ # Test class for a symbol that can only appear once in a `Mul` expression.
9
+ pass
10
+
11
+
12
+ Basic._constructor_postprocessor_mapping[SymbolInMulOnce] = {
13
+ "Mul": [lambda x: x],
14
+ "Pow": [lambda x: x.base if isinstance(x.base, SymbolInMulOnce) else x],
15
+ "Add": [lambda x: x],
16
+ }
17
+
18
+
19
+ def _postprocess_SymbolRemovesOtherSymbols(expr):
20
+ args = tuple(i for i in expr.args if not isinstance(i, Symbol) or isinstance(i, SymbolRemovesOtherSymbols))
21
+ if args == expr.args:
22
+ return expr
23
+ return Mul.fromiter(args)
24
+
25
+
26
+ class SymbolRemovesOtherSymbols(Symbol):
27
+ # Test class for a symbol that removes other symbols in `Mul`.
28
+ pass
29
+
30
+ Basic._constructor_postprocessor_mapping[SymbolRemovesOtherSymbols] = {
31
+ "Mul": [_postprocess_SymbolRemovesOtherSymbols],
32
+ }
33
+
34
+ class SubclassSymbolInMulOnce(SymbolInMulOnce):
35
+ pass
36
+
37
+ class SubclassSymbolRemovesOtherSymbols(SymbolRemovesOtherSymbols):
38
+ pass
39
+
40
+
41
+ def test_constructor_postprocessors1():
42
+ x = SymbolInMulOnce("x")
43
+ y = SymbolInMulOnce("y")
44
+ assert isinstance(3*x, Mul)
45
+ assert (3*x).args == (3, x)
46
+ assert x*x == x
47
+ assert 3*x*x == 3*x
48
+ assert 2*x*x + x == 3*x
49
+ assert x**3*y*y == x*y
50
+ assert x**5 + y*x**3 == x + x*y
51
+
52
+ w = SymbolRemovesOtherSymbols("w")
53
+ assert x*w == w
54
+ assert (3*w).args == (3, w)
55
+ assert set((w + x).args) == {x, w}
56
+
57
+ def test_constructor_postprocessors2():
58
+ x = SubclassSymbolInMulOnce("x")
59
+ y = SubclassSymbolInMulOnce("y")
60
+ assert isinstance(3*x, Mul)
61
+ assert (3*x).args == (3, x)
62
+ assert x*x == x
63
+ assert 3*x*x == 3*x
64
+ assert 2*x*x + x == 3*x
65
+ assert x**3*y*y == x*y
66
+ assert x**5 + y*x**3 == x + x*y
67
+
68
+ w = SubclassSymbolRemovesOtherSymbols("w")
69
+ assert x*w == w
70
+ assert (3*w).args == (3, w)
71
+ assert set((w + x).args) == {x, w}
72
+
73
+
74
+ @XFAIL
75
+ def test_subexpression_postprocessors():
76
+ # The postprocessors used to work with subexpressions, but the
77
+ # functionality was removed. See #15948.
78
+ a = symbols("a")
79
+ x = SymbolInMulOnce("x")
80
+ w = SymbolRemovesOtherSymbols("w")
81
+ assert 3*a*w**2 == 3*w**2
82
+ assert 3*a*x**3*w**2 == 3*w**2
83
+
84
+ x = SubclassSymbolInMulOnce("x")
85
+ w = SubclassSymbolRemovesOtherSymbols("w")
86
+ assert 3*a*w**2 == 3*w**2
87
+ assert 3*a*x**3*w**2 == 3*w**2
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_containers.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ from sympy.core.basic import Basic
4
+ from sympy.core.containers import (Dict, Tuple)
5
+ from sympy.core.numbers import Integer
6
+ from sympy.core.kind import NumberKind
7
+ from sympy.matrices.common import MatrixKind
8
+ from sympy.core.singleton import S
9
+ from sympy.core.symbol import symbols
10
+ from sympy.core.sympify import sympify
11
+ from sympy.matrices.dense import Matrix
12
+ from sympy.sets.sets import FiniteSet
13
+ from sympy.core.containers import tuple_wrapper, TupleKind
14
+ from sympy.core.expr import unchanged
15
+ from sympy.core.function import Function, Lambda
16
+ from sympy.core.relational import Eq
17
+ from sympy.testing.pytest import raises
18
+ from sympy.utilities.iterables import is_sequence, iterable
19
+
20
+ from sympy.abc import x, y
21
+
22
+
23
+ def test_Tuple():
24
+ t = (1, 2, 3, 4)
25
+ st = Tuple(*t)
26
+ assert set(sympify(t)) == set(st)
27
+ assert len(t) == len(st)
28
+ assert set(sympify(t[:2])) == set(st[:2])
29
+ assert isinstance(st[:], Tuple)
30
+ assert st == Tuple(1, 2, 3, 4)
31
+ assert st.func(*st.args) == st
32
+ p, q, r, s = symbols('p q r s')
33
+ t2 = (p, q, r, s)
34
+ st2 = Tuple(*t2)
35
+ assert st2.atoms() == set(t2)
36
+ assert st == st2.subs({p: 1, q: 2, r: 3, s: 4})
37
+ # issue 5505
38
+ assert all(isinstance(arg, Basic) for arg in st.args)
39
+ assert Tuple(p, 1).subs(p, 0) == Tuple(0, 1)
40
+ assert Tuple(p, Tuple(p, 1)).subs(p, 0) == Tuple(0, Tuple(0, 1))
41
+
42
+ assert Tuple(t2) == Tuple(Tuple(*t2))
43
+ assert Tuple.fromiter(t2) == Tuple(*t2)
44
+ assert Tuple.fromiter(x for x in range(4)) == Tuple(0, 1, 2, 3)
45
+ assert st2.fromiter(st2.args) == st2
46
+
47
+
48
+ def test_Tuple_contains():
49
+ t1, t2 = Tuple(1), Tuple(2)
50
+ assert t1 in Tuple(1, 2, 3, t1, Tuple(t2))
51
+ assert t2 not in Tuple(1, 2, 3, t1, Tuple(t2))
52
+
53
+
54
+ def test_Tuple_concatenation():
55
+ assert Tuple(1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4)
56
+ assert (1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4)
57
+ assert Tuple(1, 2) + (3, 4) == Tuple(1, 2, 3, 4)
58
+ raises(TypeError, lambda: Tuple(1, 2) + 3)
59
+ raises(TypeError, lambda: 1 + Tuple(2, 3))
60
+
61
+ #the Tuple case in __radd__ is only reached when a subclass is involved
62
+ class Tuple2(Tuple):
63
+ def __radd__(self, other):
64
+ return Tuple.__radd__(self, other + other)
65
+ assert Tuple(1, 2) + Tuple2(3, 4) == Tuple(1, 2, 1, 2, 3, 4)
66
+ assert Tuple2(1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4)
67
+
68
+
69
+ def test_Tuple_equality():
70
+ assert not isinstance(Tuple(1, 2), tuple)
71
+ assert (Tuple(1, 2) == (1, 2)) is True
72
+ assert (Tuple(1, 2) != (1, 2)) is False
73
+ assert (Tuple(1, 2) == (1, 3)) is False
74
+ assert (Tuple(1, 2) != (1, 3)) is True
75
+ assert (Tuple(1, 2) == Tuple(1, 2)) is True
76
+ assert (Tuple(1, 2) != Tuple(1, 2)) is False
77
+ assert (Tuple(1, 2) == Tuple(1, 3)) is False
78
+ assert (Tuple(1, 2) != Tuple(1, 3)) is True
79
+
80
+
81
+ def test_Tuple_Eq():
82
+ assert Eq(Tuple(), Tuple()) is S.true
83
+ assert Eq(Tuple(1), 1) is S.false
84
+ assert Eq(Tuple(1, 2), Tuple(1)) is S.false
85
+ assert Eq(Tuple(1), Tuple(1)) is S.true
86
+ assert Eq(Tuple(1, 2), Tuple(1, 3)) is S.false
87
+ assert Eq(Tuple(1, 2), Tuple(1, 2)) is S.true
88
+ assert unchanged(Eq, Tuple(1, x), Tuple(1, 2))
89
+ assert Eq(Tuple(1, x), Tuple(1, 2)).subs(x, 2) is S.true
90
+ assert unchanged(Eq, Tuple(1, 2), x)
91
+ f = Function('f')
92
+ assert unchanged(Eq, Tuple(1), f(x))
93
+ assert Eq(Tuple(1), f(x)).subs(x, 1).subs(f, Lambda(y, (y,))) is S.true
94
+
95
+
96
+ def test_Tuple_comparision():
97
+ assert (Tuple(1, 3) >= Tuple(-10, 30)) is S.true
98
+ assert (Tuple(1, 3) <= Tuple(-10, 30)) is S.false
99
+ assert (Tuple(1, 3) >= Tuple(1, 3)) is S.true
100
+ assert (Tuple(1, 3) <= Tuple(1, 3)) is S.true
101
+
102
+
103
+ def test_Tuple_tuple_count():
104
+ assert Tuple(0, 1, 2, 3).tuple_count(4) == 0
105
+ assert Tuple(0, 4, 1, 2, 3).tuple_count(4) == 1
106
+ assert Tuple(0, 4, 1, 4, 2, 3).tuple_count(4) == 2
107
+ assert Tuple(0, 4, 1, 4, 2, 4, 3).tuple_count(4) == 3
108
+
109
+
110
+ def test_Tuple_index():
111
+ assert Tuple(4, 0, 1, 2, 3).index(4) == 0
112
+ assert Tuple(0, 4, 1, 2, 3).index(4) == 1
113
+ assert Tuple(0, 1, 4, 2, 3).index(4) == 2
114
+ assert Tuple(0, 1, 2, 4, 3).index(4) == 3
115
+ assert Tuple(0, 1, 2, 3, 4).index(4) == 4
116
+
117
+ raises(ValueError, lambda: Tuple(0, 1, 2, 3).index(4))
118
+ raises(ValueError, lambda: Tuple(4, 0, 1, 2, 3).index(4, 1))
119
+ raises(ValueError, lambda: Tuple(0, 1, 2, 3, 4).index(4, 1, 4))
120
+
121
+
122
+ def test_Tuple_mul():
123
+ assert Tuple(1, 2, 3)*2 == Tuple(1, 2, 3, 1, 2, 3)
124
+ assert 2*Tuple(1, 2, 3) == Tuple(1, 2, 3, 1, 2, 3)
125
+ assert Tuple(1, 2, 3)*Integer(2) == Tuple(1, 2, 3, 1, 2, 3)
126
+ assert Integer(2)*Tuple(1, 2, 3) == Tuple(1, 2, 3, 1, 2, 3)
127
+
128
+ raises(TypeError, lambda: Tuple(1, 2, 3)*S.Half)
129
+ raises(TypeError, lambda: S.Half*Tuple(1, 2, 3))
130
+
131
+
132
+ def test_tuple_wrapper():
133
+
134
+ @tuple_wrapper
135
+ def wrap_tuples_and_return(*t):
136
+ return t
137
+
138
+ p = symbols('p')
139
+ assert wrap_tuples_and_return(p, 1) == (p, 1)
140
+ assert wrap_tuples_and_return((p, 1)) == (Tuple(p, 1),)
141
+ assert wrap_tuples_and_return(1, (p, 2), 3) == (1, Tuple(p, 2), 3)
142
+
143
+
144
+ def test_iterable_is_sequence():
145
+ ordered = [[], (), Tuple(), Matrix([[]])]
146
+ unordered = [set()]
147
+ not_sympy_iterable = [{}, '', '']
148
+ assert all(is_sequence(i) for i in ordered)
149
+ assert all(not is_sequence(i) for i in unordered)
150
+ assert all(iterable(i) for i in ordered + unordered)
151
+ assert all(not iterable(i) for i in not_sympy_iterable)
152
+ assert all(iterable(i, exclude=None) for i in not_sympy_iterable)
153
+
154
+
155
+ def test_TupleKind():
156
+ kind = TupleKind(NumberKind, MatrixKind(NumberKind))
157
+ assert Tuple(1, Matrix([1, 2])).kind is kind
158
+ assert Tuple(1, 2).kind is TupleKind(NumberKind, NumberKind)
159
+ assert Tuple(1, 2).kind.element_kind == (NumberKind, NumberKind)
160
+
161
+
162
+ def test_Dict():
163
+ x, y, z = symbols('x y z')
164
+ d = Dict({x: 1, y: 2, z: 3})
165
+ assert d[x] == 1
166
+ assert d[y] == 2
167
+ raises(KeyError, lambda: d[2])
168
+ raises(KeyError, lambda: d['2'])
169
+ assert len(d) == 3
170
+ assert set(d.keys()) == {x, y, z}
171
+ assert set(d.values()) == {S.One, S(2), S(3)}
172
+ assert d.get(5, 'default') == 'default'
173
+ assert d.get('5', 'default') == 'default'
174
+ assert x in d and z in d and 5 not in d and '5' not in d
175
+ assert d.has(x) and d.has(1) # SymPy Basic .has method
176
+
177
+ # Test input types
178
+ # input - a Python dict
179
+ # input - items as args - SymPy style
180
+ assert (Dict({x: 1, y: 2, z: 3}) ==
181
+ Dict((x, 1), (y, 2), (z, 3)))
182
+
183
+ raises(TypeError, lambda: Dict(((x, 1), (y, 2), (z, 3))))
184
+ with raises(NotImplementedError):
185
+ d[5] = 6 # assert immutability
186
+
187
+ assert set(
188
+ d.items()) == {Tuple(x, S.One), Tuple(y, S(2)), Tuple(z, S(3))}
189
+ assert set(d) == {x, y, z}
190
+ assert str(d) == '{x: 1, y: 2, z: 3}'
191
+ assert d.__repr__() == '{x: 1, y: 2, z: 3}'
192
+
193
+ # Test creating a Dict from a Dict.
194
+ d = Dict({x: 1, y: 2, z: 3})
195
+ assert d == Dict(d)
196
+
197
+ # Test for supporting defaultdict
198
+ d = defaultdict(int)
199
+ assert d[x] == 0
200
+ assert d[y] == 0
201
+ assert d[z] == 0
202
+ assert Dict(d)
203
+ d = Dict(d)
204
+ assert len(d) == 3
205
+ assert set(d.keys()) == {x, y, z}
206
+ assert set(d.values()) == {S.Zero, S.Zero, S.Zero}
207
+
208
+
209
+ def test_issue_5788():
210
+ args = [(1, 2), (2, 1)]
211
+ for o in [Dict, Tuple, FiniteSet]:
212
+ # __eq__ and arg handling
213
+ if o != Tuple:
214
+ assert o(*args) == o(*reversed(args))
215
+ pair = [o(*args), o(*reversed(args))]
216
+ assert sorted(pair) == sorted(pair)
217
+ assert set(o(*args)) # doesn't fail
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_count_ops.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.basic import Basic
3
+ from sympy.core.function import (Derivative, Function, count_ops)
4
+ from sympy.core.numbers import (I, Rational, pi)
5
+ from sympy.core.relational import (Eq, Rel)
6
+ from sympy.core.singleton import S
7
+ from sympy.core.symbol import (Symbol, symbols)
8
+ from sympy.functions.elementary.exponential import exp
9
+ from sympy.functions.elementary.trigonometric import (cos, sin)
10
+ from sympy.integrals.integrals import Integral
11
+ from sympy.logic.boolalg import (And, Equivalent, ITE, Implies, Nand,
12
+ Nor, Not, Or, Xor)
13
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
14
+ from sympy.core.containers import Tuple
15
+
16
+ x, y, z = symbols('x,y,z')
17
+ a, b, c = symbols('a,b,c')
18
+
19
+ def test_count_ops_non_visual():
20
+ def count(val):
21
+ return count_ops(val, visual=False)
22
+ assert count(x) == 0
23
+ assert count(x) is not S.Zero
24
+ assert count(x + y) == 1
25
+ assert count(x + y) is not S.One
26
+ assert count(x + y*x + 2*y) == 4
27
+ assert count({x + y: x}) == 1
28
+ assert count({x + y: S(2) + x}) is not S.One
29
+ assert count(x < y) == 1
30
+ assert count(Or(x,y)) == 1
31
+ assert count(And(x,y)) == 1
32
+ assert count(Not(x)) == 1
33
+ assert count(Nor(x,y)) == 2
34
+ assert count(Nand(x,y)) == 2
35
+ assert count(Xor(x,y)) == 1
36
+ assert count(Implies(x,y)) == 1
37
+ assert count(Equivalent(x,y)) == 1
38
+ assert count(ITE(x,y,z)) == 1
39
+ assert count(ITE(True,x,y)) == 0
40
+
41
+
42
+ def test_count_ops_visual():
43
+ ADD, MUL, POW, SIN, COS, EXP, AND, D, G, M = symbols(
44
+ 'Add Mul Pow sin cos exp And Derivative Integral Sum'.upper())
45
+ DIV, SUB, NEG = symbols('DIV SUB NEG')
46
+ LT, LE, GT, GE, EQ, NE = symbols('LT LE GT GE EQ NE')
47
+ NOT, OR, AND, XOR, IMPLIES, EQUIVALENT, _ITE, BASIC, TUPLE = symbols(
48
+ 'Not Or And Xor Implies Equivalent ITE Basic Tuple'.upper())
49
+
50
+ def count(val):
51
+ return count_ops(val, visual=True)
52
+
53
+ assert count(7) is S.Zero
54
+ assert count(S(7)) is S.Zero
55
+ assert count(-1) == NEG
56
+ assert count(-2) == NEG
57
+ assert count(S(2)/3) == DIV
58
+ assert count(Rational(2, 3)) == DIV
59
+ assert count(pi/3) == DIV
60
+ assert count(-pi/3) == DIV + NEG
61
+ assert count(I - 1) == SUB
62
+ assert count(1 - I) == SUB
63
+ assert count(1 - 2*I) == SUB + MUL
64
+
65
+ assert count(x) is S.Zero
66
+ assert count(-x) == NEG
67
+ assert count(-2*x/3) == NEG + DIV + MUL
68
+ assert count(Rational(-2, 3)*x) == NEG + DIV + MUL
69
+ assert count(1/x) == DIV
70
+ assert count(1/(x*y)) == DIV + MUL
71
+ assert count(-1/x) == NEG + DIV
72
+ assert count(-2/x) == NEG + DIV
73
+ assert count(x/y) == DIV
74
+ assert count(-x/y) == NEG + DIV
75
+
76
+ assert count(x**2) == POW
77
+ assert count(-x**2) == POW + NEG
78
+ assert count(-2*x**2) == POW + MUL + NEG
79
+
80
+ assert count(x + pi/3) == ADD + DIV
81
+ assert count(x + S.One/3) == ADD + DIV
82
+ assert count(x + Rational(1, 3)) == ADD + DIV
83
+ assert count(x + y) == ADD
84
+ assert count(x - y) == SUB
85
+ assert count(y - x) == SUB
86
+ assert count(-1/(x - y)) == DIV + NEG + SUB
87
+ assert count(-1/(y - x)) == DIV + NEG + SUB
88
+ assert count(1 + x**y) == ADD + POW
89
+ assert count(1 + x + y) == 2*ADD
90
+ assert count(1 + x + y + z) == 3*ADD
91
+ assert count(1 + x**y + 2*x*y + y**2) == 3*ADD + 2*POW + 2*MUL
92
+ assert count(2*z + y + x + 1) == 3*ADD + MUL
93
+ assert count(2*z + y**17 + x + 1) == 3*ADD + MUL + POW
94
+ assert count(2*z + y**17 + x + sin(x)) == 3*ADD + POW + MUL + SIN
95
+ assert count(2*z + y**17 + x + sin(x**2)) == 3*ADD + MUL + 2*POW + SIN
96
+ assert count(2*z + y**17 + x + sin(
97
+ x**2) + exp(cos(x))) == 4*ADD + MUL + 2*POW + EXP + COS + SIN
98
+
99
+ assert count(Derivative(x, x)) == D
100
+ assert count(Integral(x, x) + 2*x/(1 + x)) == G + DIV + MUL + 2*ADD
101
+ assert count(Sum(x, (x, 1, x + 1)) + 2*x/(1 + x)) == M + DIV + MUL + 3*ADD
102
+ assert count(Basic()) is S.Zero
103
+
104
+ assert count({x + 1: sin(x)}) == ADD + SIN
105
+ assert count([x + 1, sin(x) + y, None]) == ADD + SIN + ADD
106
+ assert count({x + 1: sin(x), y: cos(x) + 1}) == SIN + COS + 2*ADD
107
+ assert count({}) is S.Zero
108
+ assert count([x + 1, sin(x)*y, None]) == SIN + ADD + MUL
109
+ assert count([]) is S.Zero
110
+
111
+ assert count(Basic()) == 0
112
+ assert count(Basic(Basic(),Basic(x,x+y))) == ADD + 2*BASIC
113
+ assert count(Basic(x, x + y)) == ADD + BASIC
114
+ assert [count(Rel(x, y, op)) for op in '< <= > >= == <> !='.split()
115
+ ] == [LT, LE, GT, GE, EQ, NE, NE]
116
+ assert count(Or(x, y)) == OR
117
+ assert count(And(x, y)) == AND
118
+ assert count(Or(x, Or(y, And(z, a)))) == AND + OR
119
+ assert count(Nor(x, y)) == NOT + OR
120
+ assert count(Nand(x, y)) == NOT + AND
121
+ assert count(Xor(x, y)) == XOR
122
+ assert count(Implies(x, y)) == IMPLIES
123
+ assert count(Equivalent(x, y)) == EQUIVALENT
124
+ assert count(ITE(x, y, z)) == _ITE
125
+ assert count([Or(x, y), And(x, y), Basic(x + y)]
126
+ ) == ADD + AND + BASIC + OR
127
+
128
+ assert count(Basic(Tuple(x))) == BASIC + TUPLE
129
+ #It checks that TUPLE is counted as an operation.
130
+
131
+ assert count(Eq(x + y, S(2))) == ADD + EQ
132
+
133
+
134
+ def test_issue_9324():
135
+ def count(val):
136
+ return count_ops(val, visual=False)
137
+
138
+ M = MatrixSymbol('M', 10, 10)
139
+ assert count(M[0, 0]) == 0
140
+ assert count(2 * M[0, 0] + M[5, 7]) == 2
141
+ P = MatrixSymbol('P', 3, 3)
142
+ Q = MatrixSymbol('Q', 3, 3)
143
+ assert count(P + Q) == 1
144
+ m = Symbol('m', integer=True)
145
+ n = Symbol('n', integer=True)
146
+ M = MatrixSymbol('M', m + n, m * m)
147
+ assert count(M[0, 1]) == 2
148
+
149
+
150
+ def test_issue_21532():
151
+ f = Function('f')
152
+ g = Function('g')
153
+ FUNC_F, FUNC_G = symbols('FUNC_F, FUNC_G')
154
+ assert f(x).count_ops(visual=True) == FUNC_F
155
+ assert g(x).count_ops(visual=True) == FUNC_G
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_diff.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.expr import Expr
3
+ from sympy.core.function import (Derivative, Function, diff, Subs)
4
+ from sympy.core.numbers import (I, Rational, pi)
5
+ from sympy.core.relational import Eq
6
+ from sympy.core.singleton import S
7
+ from sympy.core.symbol import Symbol
8
+ from sympy.functions.combinatorial.factorials import factorial
9
+ from sympy.functions.elementary.complexes import (im, re)
10
+ from sympy.functions.elementary.exponential import (exp, log)
11
+ from sympy.functions.elementary.miscellaneous import Max
12
+ from sympy.functions.elementary.piecewise import Piecewise
13
+ from sympy.functions.elementary.trigonometric import (cos, cot, sin, tan)
14
+ from sympy.tensor.array.ndim_array import NDimArray
15
+ from sympy.testing.pytest import raises
16
+ from sympy.abc import a, b, c, x, y, z
17
+
18
+ def test_diff():
19
+ assert Rational(1, 3).diff(x) is S.Zero
20
+ assert I.diff(x) is S.Zero
21
+ assert pi.diff(x) is S.Zero
22
+ assert x.diff(x, 0) == x
23
+ assert (x**2).diff(x, 2, x) == 0
24
+ assert (x**2).diff((x, 2), x) == 0
25
+ assert (x**2).diff((x, 1), x) == 2
26
+ assert (x**2).diff((x, 1), (x, 1)) == 2
27
+ assert (x**2).diff((x, 2)) == 2
28
+ assert (x**2).diff(x, y, 0) == 2*x
29
+ assert (x**2).diff(x, (y, 0)) == 2*x
30
+ assert (x**2).diff(x, y) == 0
31
+ raises(ValueError, lambda: x.diff(1, x))
32
+
33
+ p = Rational(5)
34
+ e = a*b + b**p
35
+ assert e.diff(a) == b
36
+ assert e.diff(b) == a + 5*b**4
37
+ assert e.diff(b).diff(a) == Rational(1)
38
+ e = a*(b + c)
39
+ assert e.diff(a) == b + c
40
+ assert e.diff(b) == a
41
+ assert e.diff(b).diff(a) == Rational(1)
42
+ e = c**p
43
+ assert e.diff(c, 6) == Rational(0)
44
+ assert e.diff(c, 5) == Rational(120)
45
+ e = c**Rational(2)
46
+ assert e.diff(c) == 2*c
47
+ e = a*b*c
48
+ assert e.diff(c) == a*b
49
+
50
+
51
+ def test_diff2():
52
+ n3 = Rational(3)
53
+ n2 = Rational(2)
54
+ n6 = Rational(6)
55
+
56
+ e = n3*(-n2 + x**n2)*cos(x) + x*(-n6 + x**n2)*sin(x)
57
+ assert e == 3*(-2 + x**2)*cos(x) + x*(-6 + x**2)*sin(x)
58
+ assert e.diff(x).expand() == x**3*cos(x)
59
+
60
+ e = (x + 1)**3
61
+ assert e.diff(x) == 3*(x + 1)**2
62
+ e = x*(x + 1)**3
63
+ assert e.diff(x) == (x + 1)**3 + 3*x*(x + 1)**2
64
+ e = 2*exp(x*x)*x
65
+ assert e.diff(x) == 2*exp(x**2) + 4*x**2*exp(x**2)
66
+
67
+
68
+ def test_diff3():
69
+ p = Rational(5)
70
+ e = a*b + sin(b**p)
71
+ assert e == a*b + sin(b**5)
72
+ assert e.diff(a) == b
73
+ assert e.diff(b) == a + 5*b**4*cos(b**5)
74
+ e = tan(c)
75
+ assert e == tan(c)
76
+ assert e.diff(c) in [cos(c)**(-2), 1 + sin(c)**2/cos(c)**2, 1 + tan(c)**2]
77
+ e = c*log(c) - c
78
+ assert e == -c + c*log(c)
79
+ assert e.diff(c) == log(c)
80
+ e = log(sin(c))
81
+ assert e == log(sin(c))
82
+ assert e.diff(c) in [sin(c)**(-1)*cos(c), cot(c)]
83
+ e = (Rational(2)**a/log(Rational(2)))
84
+ assert e == 2**a*log(Rational(2))**(-1)
85
+ assert e.diff(a) == 2**a
86
+
87
+
88
+ def test_diff_no_eval_derivative():
89
+ class My(Expr):
90
+ def __new__(cls, x):
91
+ return Expr.__new__(cls, x)
92
+
93
+ # My doesn't have its own _eval_derivative method
94
+ assert My(x).diff(x).func is Derivative
95
+ assert My(x).diff(x, 3).func is Derivative
96
+ assert re(x).diff(x, 2) == Derivative(re(x), (x, 2)) # issue 15518
97
+ assert diff(NDimArray([re(x), im(x)]), (x, 2)) == NDimArray(
98
+ [Derivative(re(x), (x, 2)), Derivative(im(x), (x, 2))])
99
+ # it doesn't have y so it shouldn't need a method for this case
100
+ assert My(x).diff(y) == 0
101
+
102
+
103
+ def test_speed():
104
+ # this should return in 0.0s. If it takes forever, it's wrong.
105
+ assert x.diff(x, 10**8) == 0
106
+
107
+
108
+ def test_deriv_noncommutative():
109
+ A = Symbol("A", commutative=False)
110
+ f = Function("f")
111
+ assert A*f(x)*A == f(x)*A**2
112
+ assert A*f(x).diff(x)*A == f(x).diff(x) * A**2
113
+
114
+
115
+ def test_diff_nth_derivative():
116
+ f = Function("f")
117
+ n = Symbol("n", integer=True)
118
+
119
+ expr = diff(sin(x), (x, n))
120
+ expr2 = diff(f(x), (x, 2))
121
+ expr3 = diff(f(x), (x, n))
122
+
123
+ assert expr.subs(sin(x), cos(-x)) == Derivative(cos(-x), (x, n))
124
+ assert expr.subs(n, 1).doit() == cos(x)
125
+ assert expr.subs(n, 2).doit() == -sin(x)
126
+
127
+ assert expr2.subs(Derivative(f(x), x), y) == Derivative(y, x)
128
+ # Currently not supported (cannot determine if `n > 1`):
129
+ #assert expr3.subs(Derivative(f(x), x), y) == Derivative(y, (x, n-1))
130
+ assert expr3 == Derivative(f(x), (x, n))
131
+
132
+ assert diff(x, (x, n)) == Piecewise((x, Eq(n, 0)), (1, Eq(n, 1)), (0, True))
133
+ assert diff(2*x, (x, n)).dummy_eq(
134
+ Sum(Piecewise((2*x*factorial(n)/(factorial(y)*factorial(-y + n)),
135
+ Eq(y, 0) & Eq(Max(0, -y + n), 0)),
136
+ (2*factorial(n)/(factorial(y)*factorial(-y + n)), Eq(y, 0) & Eq(Max(0,
137
+ -y + n), 1)), (0, True)), (y, 0, n)))
138
+ # TODO: assert diff(x**2, (x, n)) == x**(2-n)*ff(2, n)
139
+ exprm = x*sin(x)
140
+ mul_diff = diff(exprm, (x, n))
141
+ assert isinstance(mul_diff, Sum)
142
+ for i in range(5):
143
+ assert mul_diff.subs(n, i).doit() == exprm.diff((x, i)).expand()
144
+
145
+ exprm2 = 2*y*x*sin(x)*cos(x)*log(x)*exp(x)
146
+ dex = exprm2.diff((x, n))
147
+ assert isinstance(dex, Sum)
148
+ for i in range(7):
149
+ assert dex.subs(n, i).doit().expand() == \
150
+ exprm2.diff((x, i)).expand()
151
+
152
+ assert (cos(x)*sin(y)).diff([[x, y, z]]) == NDimArray([
153
+ -sin(x)*sin(y), cos(x)*cos(y), 0])
154
+
155
+
156
+ def test_issue_16160():
157
+ assert Derivative(x**3, (x, x)).subs(x, 2) == Subs(
158
+ Derivative(x**3, (x, 2)), x, 2)
159
+ assert Derivative(1 + x**3, (x, x)).subs(x, 0
160
+ ) == Derivative(1 + y**3, (y, 0)).subs(y, 0)
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_equal.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Rational
2
+ from sympy.core.symbol import (Dummy, Symbol)
3
+ from sympy.functions.elementary.exponential import exp
4
+
5
+
6
+ def test_equal():
7
+ b = Symbol("b")
8
+ a = Symbol("a")
9
+ e1 = a + b
10
+ e2 = 2*a*b
11
+ e3 = a**3*b**2
12
+ e4 = a*b + b*a
13
+ assert not e1 == e2
14
+ assert not e1 == e2
15
+ assert e1 != e2
16
+ assert e2 == e4
17
+ assert e2 != e3
18
+ assert not e2 == e3
19
+
20
+ x = Symbol("x")
21
+ e1 = exp(x + 1/x)
22
+ y = Symbol("x")
23
+ e2 = exp(y + 1/y)
24
+ assert e1 == e2
25
+ assert not e1 != e2
26
+ y = Symbol("y")
27
+ e2 = exp(y + 1/y)
28
+ assert not e1 == e2
29
+ assert e1 != e2
30
+
31
+ e5 = Rational(3) + 2*x - x - x
32
+ assert e5 == 3
33
+ assert 3 == e5
34
+ assert e5 != 4
35
+ assert 4 != e5
36
+ assert e5 != 3 + x
37
+ assert 3 + x != e5
38
+
39
+
40
+ def test_expevalbug():
41
+ x = Symbol("x")
42
+ e1 = exp(1*x)
43
+ e3 = exp(x)
44
+ assert e1 == e3
45
+
46
+
47
+ def test_cmp_bug1():
48
+ class T:
49
+ pass
50
+
51
+ t = T()
52
+ x = Symbol("x")
53
+
54
+ assert not (x == t)
55
+ assert (x != t)
56
+
57
+
58
+ def test_cmp_bug2():
59
+ class T:
60
+ pass
61
+
62
+ t = T()
63
+
64
+ assert not (Symbol == t)
65
+ assert (Symbol != t)
66
+
67
+
68
+ def test_cmp_issue_4357():
69
+ """ Check that Basic subclasses can be compared with sympifiable objects.
70
+
71
+ https://github.com/sympy/sympy/issues/4357
72
+ """
73
+ assert not (Symbol == 1)
74
+ assert (Symbol != 1)
75
+ assert not (Symbol == 'x')
76
+ assert (Symbol != 'x')
77
+
78
+
79
+ def test_dummy_eq():
80
+ x = Symbol('x')
81
+ y = Symbol('y')
82
+
83
+ u = Dummy('u')
84
+
85
+ assert (u**2 + 1).dummy_eq(x**2 + 1) is True
86
+ assert ((u**2 + 1) == (x**2 + 1)) is False
87
+
88
+ assert (u**2 + y).dummy_eq(x**2 + y, x) is True
89
+ assert (u**2 + y).dummy_eq(x**2 + y, y) is False
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_eval.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import Function
2
+ from sympy.core.numbers import (I, Rational)
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import Symbol
5
+ from sympy.functions.elementary.exponential import exp
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.functions.elementary.trigonometric import (cos, tan)
8
+ from sympy.testing.pytest import XFAIL
9
+
10
+
11
+ def test_add_eval():
12
+ a = Symbol("a")
13
+ b = Symbol("b")
14
+ c = Rational(1)
15
+ p = Rational(5)
16
+ assert a*b + c + p == a*b + 6
17
+ assert c + a + p == a + 6
18
+ assert c + a - p == a + (-4)
19
+ assert a + a == 2*a
20
+ assert a + p + a == 2*a + 5
21
+ assert c + p == Rational(6)
22
+ assert b + a - b == a
23
+
24
+
25
+ def test_addmul_eval():
26
+ a = Symbol("a")
27
+ b = Symbol("b")
28
+ c = Rational(1)
29
+ p = Rational(5)
30
+ assert c + a + b*c + a - p == 2*a + b + (-4)
31
+ assert a*2 + p + a == a*2 + 5 + a
32
+ assert a*2 + p + a == 3*a + 5
33
+ assert a*2 + a == 3*a
34
+
35
+
36
+ def test_pow_eval():
37
+ # XXX Pow does not fully support conversion of negative numbers
38
+ # to their complex equivalent
39
+
40
+ assert sqrt(-1) == I
41
+
42
+ assert sqrt(-4) == 2*I
43
+ assert sqrt( 4) == 2
44
+ assert (8)**Rational(1, 3) == 2
45
+ assert (-8)**Rational(1, 3) == 2*((-1)**Rational(1, 3))
46
+
47
+ assert sqrt(-2) == I*sqrt(2)
48
+ assert (-1)**Rational(1, 3) != I
49
+ assert (-10)**Rational(1, 3) != I*((10)**Rational(1, 3))
50
+ assert (-2)**Rational(1, 4) != (2)**Rational(1, 4)
51
+
52
+ assert 64**Rational(1, 3) == 4
53
+ assert 64**Rational(2, 3) == 16
54
+ assert 24/sqrt(64) == 3
55
+ assert (-27)**Rational(1, 3) == 3*(-1)**Rational(1, 3)
56
+
57
+ assert (cos(2) / tan(2))**2 == (cos(2) / tan(2))**2
58
+
59
+
60
+ @XFAIL
61
+ def test_pow_eval_X1():
62
+ assert (-1)**Rational(1, 3) == S.Half + S.Half*I*sqrt(3)
63
+
64
+
65
+ def test_mulpow_eval():
66
+ x = Symbol('x')
67
+ assert sqrt(50)/(sqrt(2)*x) == 5/x
68
+ assert sqrt(27)/sqrt(3) == 3
69
+
70
+
71
+ def test_evalpow_bug():
72
+ x = Symbol("x")
73
+ assert 1/(1/x) == x
74
+ assert 1/(-1/x) == -x
75
+
76
+
77
+ def test_symbol_expand():
78
+ x = Symbol('x')
79
+ y = Symbol('y')
80
+
81
+ f = x**4*y**4
82
+ assert f == x**4*y**4
83
+ assert f == f.expand()
84
+
85
+ g = (x*y)**4
86
+ assert g == f
87
+ assert g.expand() == f
88
+ assert g.expand() == g.expand().expand()
89
+
90
+
91
+ def test_function():
92
+ f, l = map(Function, 'fl')
93
+ x = Symbol('x')
94
+ assert exp(l(x))*l(x)/exp(l(x)) == l(x)
95
+ assert exp(f(x))*f(x)/exp(f(x)) == f(x)
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_evalf.py ADDED
@@ -0,0 +1,732 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ from sympy.concrete.products import (Product, product)
4
+ from sympy.concrete.summations import Sum
5
+ from sympy.core.add import Add
6
+ from sympy.core.evalf import N
7
+ from sympy.core.function import (Function, nfloat)
8
+ from sympy.core.mul import Mul
9
+ from sympy.core import (GoldenRatio)
10
+ from sympy.core.numbers import (AlgebraicNumber, E, Float, I, Rational,
11
+ oo, zoo, nan, pi)
12
+ from sympy.core.power import Pow
13
+ from sympy.core.relational import Eq
14
+ from sympy.core.singleton import S
15
+ from sympy.core.symbol import Symbol
16
+ from sympy.core.sympify import sympify
17
+ from sympy.functions.combinatorial.factorials import factorial
18
+ from sympy.functions.combinatorial.numbers import fibonacci
19
+ from sympy.functions.elementary.complexes import (Abs, re, im)
20
+ from sympy.functions.elementary.exponential import (exp, log)
21
+ from sympy.functions.elementary.hyperbolic import (acosh, cosh)
22
+ from sympy.functions.elementary.integers import (ceiling, floor)
23
+ from sympy.functions.elementary.miscellaneous import (Max, sqrt)
24
+ from sympy.functions.elementary.trigonometric import (acos, atan, cos, sin, tan)
25
+ from sympy.integrals.integrals import (Integral, integrate)
26
+ from sympy.polys.polytools import factor
27
+ from sympy.polys.rootoftools import CRootOf
28
+ from sympy.polys.specialpolys import cyclotomic_poly
29
+ from sympy.printing import srepr
30
+ from sympy.printing.str import sstr
31
+ from sympy.simplify.simplify import simplify
32
+ from sympy.core.numbers import comp
33
+ from sympy.core.evalf import (complex_accuracy, PrecisionExhausted,
34
+ scaled_zero, get_integer_part, as_mpmath, evalf, _evalf_with_bounded_error)
35
+ from mpmath import inf, ninf, make_mpc
36
+ from mpmath.libmp.libmpf import from_float, fzero
37
+ from sympy.core.expr import unchanged
38
+ from sympy.testing.pytest import raises, XFAIL
39
+ from sympy.abc import n, x, y
40
+
41
+
42
+ def NS(e, n=15, **options):
43
+ return sstr(sympify(e).evalf(n, **options), full_prec=True)
44
+
45
+
46
+ def test_evalf_helpers():
47
+ from mpmath.libmp import finf
48
+ assert complex_accuracy((from_float(2.0), None, 35, None)) == 35
49
+ assert complex_accuracy((from_float(2.0), from_float(10.0), 35, 100)) == 37
50
+ assert complex_accuracy(
51
+ (from_float(2.0), from_float(1000.0), 35, 100)) == 43
52
+ assert complex_accuracy((from_float(2.0), from_float(10.0), 100, 35)) == 35
53
+ assert complex_accuracy(
54
+ (from_float(2.0), from_float(1000.0), 100, 35)) == 35
55
+ assert complex_accuracy(finf) == math.inf
56
+ assert complex_accuracy(zoo) == math.inf
57
+ raises(ValueError, lambda: get_integer_part(zoo, 1, {}))
58
+
59
+
60
+ def test_evalf_basic():
61
+ assert NS('pi', 15) == '3.14159265358979'
62
+ assert NS('2/3', 10) == '0.6666666667'
63
+ assert NS('355/113-pi', 6) == '2.66764e-7'
64
+ assert NS('16*atan(1/5)-4*atan(1/239)', 15) == '3.14159265358979'
65
+
66
+
67
+ def test_cancellation():
68
+ assert NS(Add(pi, Rational(1, 10**1000), -pi, evaluate=False), 15,
69
+ maxn=1200) == '1.00000000000000e-1000'
70
+
71
+
72
+ def test_evalf_powers():
73
+ assert NS('pi**(10**20)', 10) == '1.339148777e+49714987269413385435'
74
+ assert NS(pi**(10**100), 10) == ('4.946362032e+4971498726941338543512682882'
75
+ '9089887365167832438044244613405349992494711208'
76
+ '95526746555473864642912223')
77
+ assert NS('2**(1/10**50)', 15) == '1.00000000000000'
78
+ assert NS('2**(1/10**50)-1', 15) == '6.93147180559945e-51'
79
+
80
+ # Evaluation of Rump's ill-conditioned polynomial
81
+
82
+
83
+ def test_evalf_rump():
84
+ a = 1335*y**6/4 + x**2*(11*x**2*y**2 - y**6 - 121*y**4 - 2) + 11*y**8/2 + x/(2*y)
85
+ assert NS(a, 15, subs={x: 77617, y: 33096}) == '-0.827396059946821'
86
+
87
+
88
+ def test_evalf_complex():
89
+ assert NS('2*sqrt(pi)*I', 10) == '3.544907702*I'
90
+ assert NS('3+3*I', 15) == '3.00000000000000 + 3.00000000000000*I'
91
+ assert NS('E+pi*I', 15) == '2.71828182845905 + 3.14159265358979*I'
92
+ assert NS('pi * (3+4*I)', 15) == '9.42477796076938 + 12.5663706143592*I'
93
+ assert NS('I*(2+I)', 15) == '-1.00000000000000 + 2.00000000000000*I'
94
+
95
+
96
+ @XFAIL
97
+ def test_evalf_complex_bug():
98
+ assert NS('(pi+E*I)*(E+pi*I)', 15) in ('0.e-15 + 17.25866050002*I',
99
+ '0.e-17 + 17.25866050002*I', '-0.e-17 + 17.25866050002*I')
100
+
101
+
102
+ def test_evalf_complex_powers():
103
+ assert NS('(E+pi*I)**100000000000000000') == \
104
+ '-3.58896782867793e+61850354284995199 + 4.58581754997159e+61850354284995199*I'
105
+ # XXX: rewrite if a+a*I simplification introduced in SymPy
106
+ #assert NS('(pi + pi*I)**2') in ('0.e-15 + 19.7392088021787*I', '0.e-16 + 19.7392088021787*I')
107
+ assert NS('(pi + pi*I)**2', chop=True) == '19.7392088021787*I'
108
+ assert NS(
109
+ '(pi + 1/10**8 + pi*I)**2') == '6.2831853e-8 + 19.7392088650106*I'
110
+ assert NS('(pi + 1/10**12 + pi*I)**2') == '6.283e-12 + 19.7392088021850*I'
111
+ assert NS('(pi + pi*I)**4', chop=True) == '-389.636364136010'
112
+ assert NS(
113
+ '(pi + 1/10**8 + pi*I)**4') == '-389.636366616512 + 2.4805021e-6*I'
114
+ assert NS('(pi + 1/10**12 + pi*I)**4') == '-389.636364136258 + 2.481e-10*I'
115
+ assert NS(
116
+ '(10000*pi + 10000*pi*I)**4', chop=True) == '-3.89636364136010e+18'
117
+
118
+
119
+ @XFAIL
120
+ def test_evalf_complex_powers_bug():
121
+ assert NS('(pi + pi*I)**4') == '-389.63636413601 + 0.e-14*I'
122
+
123
+
124
+ def test_evalf_exponentiation():
125
+ assert NS(sqrt(-pi)) == '1.77245385090552*I'
126
+ assert NS(Pow(pi*I, Rational(
127
+ 1, 2), evaluate=False)) == '1.25331413731550 + 1.25331413731550*I'
128
+ assert NS(pi**I) == '0.413292116101594 + 0.910598499212615*I'
129
+ assert NS(pi**(E + I/3)) == '20.8438653991931 + 8.36343473930031*I'
130
+ assert NS((pi + I/3)**(E + I/3)) == '17.2442906093590 + 13.6839376767037*I'
131
+ assert NS(exp(pi)) == '23.1406926327793'
132
+ assert NS(exp(pi + E*I)) == '-21.0981542849657 + 9.50576358282422*I'
133
+ assert NS(pi**pi) == '36.4621596072079'
134
+ assert NS((-pi)**pi) == '-32.9138577418939 - 15.6897116534332*I'
135
+ assert NS((-pi)**(-pi)) == '-0.0247567717232697 + 0.0118013091280262*I'
136
+
137
+ # An example from Smith, "Multiple Precision Complex Arithmetic and Functions"
138
+
139
+
140
+ def test_evalf_complex_cancellation():
141
+ A = Rational('63287/100000')
142
+ B = Rational('52498/100000')
143
+ C = Rational('69301/100000')
144
+ D = Rational('83542/100000')
145
+ F = Rational('2231321613/2500000000')
146
+ # XXX: the number of returned mantissa digits in the real part could
147
+ # change with the implementation. What matters is that the returned digits are
148
+ # correct; those that are showing now are correct.
149
+ # >>> ((A+B*I)*(C+D*I)).expand()
150
+ # 64471/10000000000 + 2231321613*I/2500000000
151
+ # >>> 2231321613*4
152
+ # 8925286452L
153
+ assert NS((A + B*I)*(C + D*I), 6) == '6.44710e-6 + 0.892529*I'
154
+ assert NS((A + B*I)*(C + D*I), 10) == '6.447100000e-6 + 0.8925286452*I'
155
+ assert NS((A + B*I)*(
156
+ C + D*I) - F*I, 5) in ('6.4471e-6 + 0.e-14*I', '6.4471e-6 - 0.e-14*I')
157
+
158
+
159
+ def test_evalf_logs():
160
+ assert NS("log(3+pi*I)", 15) == '1.46877619736226 + 0.808448792630022*I'
161
+ assert NS("log(pi*I)", 15) == '1.14472988584940 + 1.57079632679490*I'
162
+ assert NS('log(-1 + 0.00001)', 2) == '-1.0e-5 + 3.1*I'
163
+ assert NS('log(100, 10, evaluate=False)', 15) == '2.00000000000000'
164
+ assert NS('-2*I*log(-(-1)**(S(1)/9))', 15) == '-5.58505360638185'
165
+
166
+
167
+ def test_evalf_trig():
168
+ assert NS('sin(1)', 15) == '0.841470984807897'
169
+ assert NS('cos(1)', 15) == '0.540302305868140'
170
+ assert NS('sin(10**-6)', 15) == '9.99999999999833e-7'
171
+ assert NS('cos(10**-6)', 15) == '0.999999999999500'
172
+ assert NS('sin(E*10**100)', 15) == '0.409160531722613'
173
+ # Some input near roots
174
+ assert NS(sin(exp(pi*sqrt(163))*pi), 15) == '-2.35596641936785e-12'
175
+ assert NS(sin(pi*10**100 + Rational(7, 10**5), evaluate=False), 15, maxn=120) == \
176
+ '6.99999999428333e-5'
177
+ assert NS(sin(Rational(7, 10**5), evaluate=False), 15) == \
178
+ '6.99999999428333e-5'
179
+
180
+ # Check detection of various false identities
181
+
182
+
183
+ def test_evalf_near_integers():
184
+ # Binet's formula
185
+ f = lambda n: ((1 + sqrt(5))**n)/(2**n * sqrt(5))
186
+ assert NS(f(5000) - fibonacci(5000), 10, maxn=1500) == '5.156009964e-1046'
187
+ # Some near-integer identities from
188
+ # http://mathworld.wolfram.com/AlmostInteger.html
189
+ assert NS('sin(2017*2**(1/5))', 15) == '-1.00000000000000'
190
+ assert NS('sin(2017*2**(1/5))', 20) == '-0.99999999999999997857'
191
+ assert NS('1+sin(2017*2**(1/5))', 15) == '2.14322287389390e-17'
192
+ assert NS('45 - 613*E/37 + 35/991', 15) == '6.03764498766326e-11'
193
+
194
+
195
+ def test_evalf_ramanujan():
196
+ assert NS(exp(pi*sqrt(163)) - 640320**3 - 744, 10) == '-7.499274028e-13'
197
+ # A related identity
198
+ A = 262537412640768744*exp(-pi*sqrt(163))
199
+ B = 196884*exp(-2*pi*sqrt(163))
200
+ C = 103378831900730205293632*exp(-3*pi*sqrt(163))
201
+ assert NS(1 - A - B + C, 10) == '1.613679005e-59'
202
+
203
+ # Input that for various reasons have failed at some point
204
+
205
+
206
+ def test_evalf_bugs():
207
+ assert NS(sin(1) + exp(-10**10), 10) == NS(sin(1), 10)
208
+ assert NS(exp(10**10) + sin(1), 10) == NS(exp(10**10), 10)
209
+ assert NS('expand_log(log(1+1/10**50))', 20) == '1.0000000000000000000e-50'
210
+ assert NS('log(10**100,10)', 10) == '100.0000000'
211
+ assert NS('log(2)', 10) == '0.6931471806'
212
+ assert NS(
213
+ '(sin(x)-x)/x**3', 15, subs={x: '1/10**50'}) == '-0.166666666666667'
214
+ assert NS(sin(1) + Rational(
215
+ 1, 10**100)*I, 15) == '0.841470984807897 + 1.00000000000000e-100*I'
216
+ assert x.evalf() == x
217
+ assert NS((1 + I)**2*I, 6) == '-2.00000'
218
+ d = {n: (
219
+ -1)**Rational(6, 7), y: (-1)**Rational(4, 7), x: (-1)**Rational(2, 7)}
220
+ assert NS((x*(1 + y*(1 + n))).subs(d).evalf(), 6) == '0.346011 + 0.433884*I'
221
+ assert NS(((-I - sqrt(2)*I)**2).evalf()) == '-5.82842712474619'
222
+ assert NS((1 + I)**2*I, 15) == '-2.00000000000000'
223
+ # issue 4758 (1/2):
224
+ assert NS(pi.evalf(69) - pi) == '-4.43863937855894e-71'
225
+ # issue 4758 (2/2): With the bug present, this still only fails if the
226
+ # terms are in the order given here. This is not generally the case,
227
+ # because the order depends on the hashes of the terms.
228
+ assert NS(20 - 5008329267844*n**25 - 477638700*n**37 - 19*n,
229
+ subs={n: .01}) == '19.8100000000000'
230
+ assert NS(((x - 1)*(1 - x)**1000).n()
231
+ ) == '(1.00000000000000 - x)**1000*(x - 1.00000000000000)'
232
+ assert NS((-x).n()) == '-x'
233
+ assert NS((-2*x).n()) == '-2.00000000000000*x'
234
+ assert NS((-2*x*y).n()) == '-2.00000000000000*x*y'
235
+ assert cos(x).n(subs={x: 1+I}) == cos(x).subs(x, 1+I).n()
236
+ # issue 6660. Also NaN != mpmath.nan
237
+ # In this order:
238
+ # 0*nan, 0/nan, 0*inf, 0/inf
239
+ # 0+nan, 0-nan, 0+inf, 0-inf
240
+ # >>> n = Some Number
241
+ # n*nan, n/nan, n*inf, n/inf
242
+ # n+nan, n-nan, n+inf, n-inf
243
+ assert (0*E**(oo)).n() is S.NaN
244
+ assert (0/E**(oo)).n() is S.Zero
245
+
246
+ assert (0+E**(oo)).n() is S.Infinity
247
+ assert (0-E**(oo)).n() is S.NegativeInfinity
248
+
249
+ assert (5*E**(oo)).n() is S.Infinity
250
+ assert (5/E**(oo)).n() is S.Zero
251
+
252
+ assert (5+E**(oo)).n() is S.Infinity
253
+ assert (5-E**(oo)).n() is S.NegativeInfinity
254
+
255
+ #issue 7416
256
+ assert as_mpmath(0.0, 10, {'chop': True}) == 0
257
+
258
+ #issue 5412
259
+ assert ((oo*I).n() == S.Infinity*I)
260
+ assert ((oo+oo*I).n() == S.Infinity + S.Infinity*I)
261
+
262
+ #issue 11518
263
+ assert NS(2*x**2.5, 5) == '2.0000*x**2.5000'
264
+
265
+ #issue 13076
266
+ assert NS(Mul(Max(0, y), x, evaluate=False).evalf()) == 'x*Max(0, y)'
267
+
268
+ #issue 18516
269
+ assert NS(log(S(3273390607896141870013189696827599152216642046043064789483291368096133796404674554883270092325904157150886684127560071009217256545885393053328527589376)/36360291795869936842385267079543319118023385026001623040346035832580600191583895484198508262979388783308179702534403855752855931517013066142992430916562025780021771247847643450125342836565813209972590371590152578728008385990139795377610001).evalf(15, chop=True)) == '-oo'
270
+
271
+
272
+ def test_evalf_integer_parts():
273
+ a = floor(log(8)/log(2) - exp(-1000), evaluate=False)
274
+ b = floor(log(8)/log(2), evaluate=False)
275
+ assert a.evalf() == 3.0
276
+ assert b.evalf() == 3.0
277
+ # equals, as a fallback, can still fail but it might succeed as here
278
+ assert ceiling(10*(sin(1)**2 + cos(1)**2)) == 10
279
+
280
+ assert int(floor(factorial(50)/E, evaluate=False).evalf(70)) == \
281
+ int(11188719610782480504630258070757734324011354208865721592720336800)
282
+ assert int(ceiling(factorial(50)/E, evaluate=False).evalf(70)) == \
283
+ int(11188719610782480504630258070757734324011354208865721592720336801)
284
+ assert int(floor(GoldenRatio**999 / sqrt(5) + S.Half)
285
+ .evalf(1000)) == fibonacci(999)
286
+ assert int(floor(GoldenRatio**1000 / sqrt(5) + S.Half)
287
+ .evalf(1000)) == fibonacci(1000)
288
+
289
+ assert ceiling(x).evalf(subs={x: 3}) == 3.0
290
+ assert ceiling(x).evalf(subs={x: 3*I}) == 3.0*I
291
+ assert ceiling(x).evalf(subs={x: 2 + 3*I}) == 2.0 + 3.0*I
292
+ assert ceiling(x).evalf(subs={x: 3.}) == 3.0
293
+ assert ceiling(x).evalf(subs={x: 3.*I}) == 3.0*I
294
+ assert ceiling(x).evalf(subs={x: 2. + 3*I}) == 2.0 + 3.0*I
295
+
296
+ assert float((floor(1.5, evaluate=False)+1/9).evalf()) == 1 + 1/9
297
+ assert float((floor(0.5, evaluate=False)+20).evalf()) == 20
298
+
299
+ # issue 19991
300
+ n = 1169809367327212570704813632106852886389036911
301
+ r = 744723773141314414542111064094745678855643068
302
+
303
+ assert floor(n / (pi / 2)) == r
304
+ assert floor(80782 * sqrt(2)) == 114242
305
+
306
+ # issue 20076
307
+ assert 260515 - floor(260515/pi + 1/2) * pi == atan(tan(260515))
308
+
309
+
310
+ def test_evalf_trig_zero_detection():
311
+ a = sin(160*pi, evaluate=False)
312
+ t = a.evalf(maxn=100)
313
+ assert abs(t) < 1e-100
314
+ assert t._prec < 2
315
+ assert a.evalf(chop=True) == 0
316
+ raises(PrecisionExhausted, lambda: a.evalf(strict=True))
317
+
318
+
319
+ def test_evalf_sum():
320
+ assert Sum(n,(n,1,2)).evalf() == 3.
321
+ assert Sum(n,(n,1,2)).doit().evalf() == 3.
322
+ # the next test should return instantly
323
+ assert Sum(1/n,(n,1,2)).evalf() == 1.5
324
+
325
+ # issue 8219
326
+ assert Sum(E/factorial(n), (n, 0, oo)).evalf() == (E*E).evalf()
327
+ # issue 8254
328
+ assert Sum(2**n*n/factorial(n), (n, 0, oo)).evalf() == (2*E*E).evalf()
329
+ # issue 8411
330
+ s = Sum(1/x**2, (x, 100, oo))
331
+ assert s.n() == s.doit().n()
332
+
333
+
334
+ def test_evalf_divergent_series():
335
+ raises(ValueError, lambda: Sum(1/n, (n, 1, oo)).evalf())
336
+ raises(ValueError, lambda: Sum(n/(n**2 + 1), (n, 1, oo)).evalf())
337
+ raises(ValueError, lambda: Sum((-1)**n, (n, 1, oo)).evalf())
338
+ raises(ValueError, lambda: Sum((-1)**n, (n, 1, oo)).evalf())
339
+ raises(ValueError, lambda: Sum(n**2, (n, 1, oo)).evalf())
340
+ raises(ValueError, lambda: Sum(2**n, (n, 1, oo)).evalf())
341
+ raises(ValueError, lambda: Sum((-2)**n, (n, 1, oo)).evalf())
342
+ raises(ValueError, lambda: Sum((2*n + 3)/(3*n**2 + 4), (n, 0, oo)).evalf())
343
+ raises(ValueError, lambda: Sum((0.5*n**3)/(n**4 + 1), (n, 0, oo)).evalf())
344
+
345
+
346
+ def test_evalf_product():
347
+ assert Product(n, (n, 1, 10)).evalf() == 3628800.
348
+ assert comp(Product(1 - S.Half**2/n**2, (n, 1, oo)).n(5), 0.63662)
349
+ assert Product(n, (n, -1, 3)).evalf() == 0
350
+
351
+
352
+ def test_evalf_py_methods():
353
+ assert abs(float(pi + 1) - 4.1415926535897932) < 1e-10
354
+ assert abs(complex(pi + 1) - 4.1415926535897932) < 1e-10
355
+ assert abs(
356
+ complex(pi + E*I) - (3.1415926535897931 + 2.7182818284590451j)) < 1e-10
357
+ raises(TypeError, lambda: float(pi + x))
358
+
359
+
360
+ def test_evalf_power_subs_bugs():
361
+ assert (x**2).evalf(subs={x: 0}) == 0
362
+ assert sqrt(x).evalf(subs={x: 0}) == 0
363
+ assert (x**Rational(2, 3)).evalf(subs={x: 0}) == 0
364
+ assert (x**x).evalf(subs={x: 0}) == 1.0
365
+ assert (3**x).evalf(subs={x: 0}) == 1.0
366
+ assert exp(x).evalf(subs={x: 0}) == 1.0
367
+ assert ((2 + I)**x).evalf(subs={x: 0}) == 1.0
368
+ assert (0**x).evalf(subs={x: 0}) == 1.0
369
+
370
+
371
+ def test_evalf_arguments():
372
+ raises(TypeError, lambda: pi.evalf(method="garbage"))
373
+
374
+
375
+ def test_implemented_function_evalf():
376
+ from sympy.utilities.lambdify import implemented_function
377
+ f = Function('f')
378
+ f = implemented_function(f, lambda x: x + 1)
379
+ assert str(f(x)) == "f(x)"
380
+ assert str(f(2)) == "f(2)"
381
+ assert f(2).evalf() == 3.0
382
+ assert f(x).evalf() == f(x)
383
+ f = implemented_function(Function('sin'), lambda x: x + 1)
384
+ assert f(2).evalf() != sin(2)
385
+ del f._imp_ # XXX: due to caching _imp_ would influence all other tests
386
+
387
+
388
+ def test_evaluate_false():
389
+ for no in [0, False]:
390
+ assert Add(3, 2, evaluate=no).is_Add
391
+ assert Mul(3, 2, evaluate=no).is_Mul
392
+ assert Pow(3, 2, evaluate=no).is_Pow
393
+ assert Pow(y, 2, evaluate=True) - Pow(y, 2, evaluate=True) == 0
394
+
395
+
396
+ def test_evalf_relational():
397
+ assert Eq(x/5, y/10).evalf() == Eq(0.2*x, 0.1*y)
398
+ # if this first assertion fails it should be replaced with
399
+ # one that doesn't
400
+ assert unchanged(Eq, (3 - I)**2/2 + I, 0)
401
+ assert Eq((3 - I)**2/2 + I, 0).n() is S.false
402
+ assert nfloat(Eq((3 - I)**2 + I, 0)) == S.false
403
+
404
+
405
+ def test_issue_5486():
406
+ assert not cos(sqrt(0.5 + I)).n().is_Function
407
+
408
+
409
+ def test_issue_5486_bug():
410
+ from sympy.core.expr import Expr
411
+ from sympy.core.numbers import I
412
+ assert abs(Expr._from_mpmath(I._to_mpmath(15), 15) - I) < 1.0e-15
413
+
414
+
415
+ def test_bugs():
416
+ from sympy.functions.elementary.complexes import (polar_lift, re)
417
+
418
+ assert abs(re((1 + I)**2)) < 1e-15
419
+
420
+ # anything that evalf's to 0 will do in place of polar_lift
421
+ assert abs(polar_lift(0)).n() == 0
422
+
423
+
424
+ def test_subs():
425
+ assert NS('besseli(-x, y) - besseli(x, y)', subs={x: 3.5, y: 20.0}) == \
426
+ '-4.92535585957223e-10'
427
+ assert NS('Piecewise((x, x>0)) + Piecewise((1-x, x>0))', subs={x: 0.1}) == \
428
+ '1.00000000000000'
429
+ raises(TypeError, lambda: x.evalf(subs=(x, 1)))
430
+
431
+
432
+ def test_issue_4956_5204():
433
+ # issue 4956
434
+ v = S('''(-27*12**(1/3)*sqrt(31)*I +
435
+ 27*2**(2/3)*3**(1/3)*sqrt(31)*I)/(-2511*2**(2/3)*3**(1/3) +
436
+ (29*18**(1/3) + 9*2**(1/3)*3**(2/3)*sqrt(31)*I +
437
+ 87*2**(1/3)*3**(1/6)*I)**2)''')
438
+ assert NS(v, 1) == '0.e-118 - 0.e-118*I'
439
+
440
+ # issue 5204
441
+ v = S('''-(357587765856 + 18873261792*249**(1/2) + 56619785376*I*83**(1/2) +
442
+ 108755765856*I*3**(1/2) + 41281887168*6**(1/3)*(1422 +
443
+ 54*249**(1/2))**(1/3) - 1239810624*6**(1/3)*249**(1/2)*(1422 +
444
+ 54*249**(1/2))**(1/3) - 3110400000*I*6**(1/3)*83**(1/2)*(1422 +
445
+ 54*249**(1/2))**(1/3) + 13478400000*I*3**(1/2)*6**(1/3)*(1422 +
446
+ 54*249**(1/2))**(1/3) + 1274950152*6**(2/3)*(1422 +
447
+ 54*249**(1/2))**(2/3) + 32347944*6**(2/3)*249**(1/2)*(1422 +
448
+ 54*249**(1/2))**(2/3) - 1758790152*I*3**(1/2)*6**(2/3)*(1422 +
449
+ 54*249**(1/2))**(2/3) - 304403832*I*6**(2/3)*83**(1/2)*(1422 +
450
+ 4*249**(1/2))**(2/3))/(175732658352 + (1106028 + 25596*249**(1/2) +
451
+ 76788*I*83**(1/2))**2)''')
452
+ assert NS(v, 5) == '0.077284 + 1.1104*I'
453
+ assert NS(v, 1) == '0.08 + 1.*I'
454
+
455
+
456
+ def test_old_docstring():
457
+ a = (E + pi*I)*(E - pi*I)
458
+ assert NS(a) == '17.2586605000200'
459
+ assert a.n() == 17.25866050002001
460
+
461
+
462
+ def test_issue_4806():
463
+ assert integrate(atan(x)**2, (x, -1, 1)).evalf().round(1) == Float(0.5, 1)
464
+ assert atan(0, evaluate=False).n() == 0
465
+
466
+
467
+ def test_evalf_mul():
468
+ # SymPy should not try to expand this; it should be handled term-wise
469
+ # in evalf through mpmath
470
+ assert NS(product(1 + sqrt(n)*I, (n, 1, 500)), 1) == '5.e+567 + 2.e+568*I'
471
+
472
+
473
+ def test_scaled_zero():
474
+ a, b = (([0], 1, 100, 1), -1)
475
+ assert scaled_zero(100) == (a, b)
476
+ assert scaled_zero(a) == (0, 1, 100, 1)
477
+ a, b = (([1], 1, 100, 1), -1)
478
+ assert scaled_zero(100, -1) == (a, b)
479
+ assert scaled_zero(a) == (1, 1, 100, 1)
480
+ raises(ValueError, lambda: scaled_zero(scaled_zero(100)))
481
+ raises(ValueError, lambda: scaled_zero(100, 2))
482
+ raises(ValueError, lambda: scaled_zero(100, 0))
483
+ raises(ValueError, lambda: scaled_zero((1, 5, 1, 3)))
484
+
485
+
486
+ def test_chop_value():
487
+ for i in range(-27, 28):
488
+ assert (Pow(10, i)*2).n(chop=10**i) and not (Pow(10, i)).n(chop=10**i)
489
+
490
+
491
+ def test_infinities():
492
+ assert oo.evalf(chop=True) == inf
493
+ assert (-oo).evalf(chop=True) == ninf
494
+
495
+
496
+ def test_to_mpmath():
497
+ assert sqrt(3)._to_mpmath(20)._mpf_ == (0, int(908093), -19, 20)
498
+ assert S(3.2)._to_mpmath(20)._mpf_ == (0, int(838861), -18, 20)
499
+
500
+
501
+ def test_issue_6632_evalf():
502
+ add = (-100000*sqrt(2500000001) + 5000000001)
503
+ assert add.n() == 9.999999998e-11
504
+ assert (add*add).n() == 9.999999996e-21
505
+
506
+
507
+ def test_issue_4945():
508
+ from sympy.abc import H
509
+ assert (H/0).evalf(subs={H:1}) == zoo
510
+
511
+
512
+ def test_evalf_integral():
513
+ # test that workprec has to increase in order to get a result other than 0
514
+ eps = Rational(1, 1000000)
515
+ assert Integral(sin(x), (x, -pi, pi + eps)).n(2)._prec == 10
516
+
517
+
518
+ def test_issue_8821_highprec_from_str():
519
+ s = str(pi.evalf(128))
520
+ p = N(s)
521
+ assert Abs(sin(p)) < 1e-15
522
+ p = N(s, 64)
523
+ assert Abs(sin(p)) < 1e-64
524
+
525
+
526
+ def test_issue_8853():
527
+ p = Symbol('x', even=True, positive=True)
528
+ assert floor(-p - S.Half).is_even == False
529
+ assert floor(-p + S.Half).is_even == True
530
+ assert ceiling(p - S.Half).is_even == True
531
+ assert ceiling(p + S.Half).is_even == False
532
+
533
+ assert get_integer_part(S.Half, -1, {}, True) == (0, 0)
534
+ assert get_integer_part(S.Half, 1, {}, True) == (1, 0)
535
+ assert get_integer_part(Rational(-1, 2), -1, {}, True) == (-1, 0)
536
+ assert get_integer_part(Rational(-1, 2), 1, {}, True) == (0, 0)
537
+
538
+
539
+ def test_issue_17681():
540
+ class identity_func(Function):
541
+
542
+ def _eval_evalf(self, *args, **kwargs):
543
+ return self.args[0].evalf(*args, **kwargs)
544
+
545
+ assert floor(identity_func(S(0))) == 0
546
+ assert get_integer_part(S(0), 1, {}, True) == (0, 0)
547
+
548
+
549
+ def test_issue_9326():
550
+ from sympy.core.symbol import Dummy
551
+ d1 = Dummy('d')
552
+ d2 = Dummy('d')
553
+ e = d1 + d2
554
+ assert e.evalf(subs = {d1: 1, d2: 2}) == 3.0
555
+
556
+
557
+ def test_issue_10323():
558
+ assert ceiling(sqrt(2**30 + 1)) == 2**15 + 1
559
+
560
+
561
+ def test_AssocOp_Function():
562
+ # the first arg of Min is not comparable in the imaginary part
563
+ raises(ValueError, lambda: S('''
564
+ Min(-sqrt(3)*cos(pi/18)/6 + re(1/((-1/2 - sqrt(3)*I/2)*(1/6 +
565
+ sqrt(3)*I/18)**(1/3)))/3 + sin(pi/18)/2 + 2 + I*(-cos(pi/18)/2 -
566
+ sqrt(3)*sin(pi/18)/6 + im(1/((-1/2 - sqrt(3)*I/2)*(1/6 +
567
+ sqrt(3)*I/18)**(1/3)))/3), re(1/((-1/2 + sqrt(3)*I/2)*(1/6 +
568
+ sqrt(3)*I/18)**(1/3)))/3 - sqrt(3)*cos(pi/18)/6 - sin(pi/18)/2 + 2 +
569
+ I*(im(1/((-1/2 + sqrt(3)*I/2)*(1/6 + sqrt(3)*I/18)**(1/3)))/3 -
570
+ sqrt(3)*sin(pi/18)/6 + cos(pi/18)/2))'''))
571
+ # if that is changed so a non-comparable number remains as
572
+ # an arg, then the Min/Max instantiation needs to be changed
573
+ # to watch out for non-comparable args when making simplifications
574
+ # and the following test should be added instead (with e being
575
+ # the sympified expression above):
576
+ # raises(ValueError, lambda: e._eval_evalf(2))
577
+
578
+
579
+ def test_issue_10395():
580
+ eq = x*Max(0, y)
581
+ assert nfloat(eq) == eq
582
+ eq = x*Max(y, -1.1)
583
+ assert nfloat(eq) == eq
584
+ assert Max(y, 4).n() == Max(4.0, y)
585
+
586
+
587
+ def test_issue_13098():
588
+ assert floor(log(S('9.'+'9'*20), 10)) == 0
589
+ assert ceiling(log(S('9.'+'9'*20), 10)) == 1
590
+ assert floor(log(20 - S('9.'+'9'*20), 10)) == 1
591
+ assert ceiling(log(20 - S('9.'+'9'*20), 10)) == 2
592
+
593
+
594
+ def test_issue_14601():
595
+ e = 5*x*y/2 - y*(35*(x**3)/2 - 15*x/2)
596
+ subst = {x:0.0, y:0.0}
597
+ e2 = e.evalf(subs=subst)
598
+ assert float(e2) == 0.0
599
+ assert float((x + x*(x**2 + x)).evalf(subs={x: 0.0})) == 0.0
600
+
601
+
602
+ def test_issue_11151():
603
+ z = S.Zero
604
+ e = Sum(z, (x, 1, 2))
605
+ assert e != z # it shouldn't evaluate
606
+ # when it does evaluate, this is what it should give
607
+ assert evalf(e, 15, {}) == \
608
+ evalf(z, 15, {}) == (None, None, 15, None)
609
+ # so this shouldn't fail
610
+ assert (e/2).n() == 0
611
+ # this was where the issue appeared
612
+ expr0 = Sum(x**2 + x, (x, 1, 2))
613
+ expr1 = Sum(0, (x, 1, 2))
614
+ expr2 = expr1/expr0
615
+ assert simplify(factor(expr2) - expr2) == 0
616
+
617
+
618
+ def test_issue_13425():
619
+ assert N('2**.5', 30) == N('sqrt(2)', 30)
620
+ assert N('x - x', 30) == 0
621
+ assert abs((N('pi*.1', 22)*10 - pi).n()) < 1e-22
622
+
623
+
624
+ def test_issue_17421():
625
+ assert N(acos(-I + acosh(cosh(cosh(1) + I)))) == 1.0*I
626
+
627
+
628
+ def test_issue_20291():
629
+ from sympy.sets import EmptySet, Reals
630
+ from sympy.sets.sets import (Complement, FiniteSet, Intersection)
631
+ a = Symbol('a')
632
+ b = Symbol('b')
633
+ A = FiniteSet(a, b)
634
+ assert A.evalf(subs={a: 1, b: 2}) == FiniteSet(1.0, 2.0)
635
+ B = FiniteSet(a-b, 1)
636
+ assert B.evalf(subs={a: 1, b: 2}) == FiniteSet(-1.0, 1.0)
637
+
638
+ sol = Complement(Intersection(FiniteSet(-b/2 - sqrt(b**2-4*pi)/2), Reals), FiniteSet(0))
639
+ assert sol.evalf(subs={b: 1}) == EmptySet
640
+
641
+
642
+ def test_evalf_with_zoo():
643
+ assert (1/x).evalf(subs={x: 0}) == zoo # issue 8242
644
+ assert (-1/x).evalf(subs={x: 0}) == zoo # PR 16150
645
+ assert (0 ** x).evalf(subs={x: -1}) == zoo # PR 16150
646
+ assert (0 ** x).evalf(subs={x: -1 + I}) == nan
647
+ assert Mul(2, Pow(0, -1, evaluate=False), evaluate=False).evalf() == zoo # issue 21147
648
+ assert Mul(x, 1/x, evaluate=False).evalf(subs={x: 0}) == Mul(x, 1/x, evaluate=False).subs(x, 0) == nan
649
+ assert Mul(1/x, 1/x, evaluate=False).evalf(subs={x: 0}) == zoo
650
+ assert Mul(1/x, Abs(1/x), evaluate=False).evalf(subs={x: 0}) == zoo
651
+ assert Abs(zoo, evaluate=False).evalf() == oo
652
+ assert re(zoo, evaluate=False).evalf() == nan
653
+ assert im(zoo, evaluate=False).evalf() == nan
654
+ assert Add(zoo, zoo, evaluate=False).evalf() == nan
655
+ assert Add(oo, zoo, evaluate=False).evalf() == nan
656
+ assert Pow(zoo, -1, evaluate=False).evalf() == 0
657
+ assert Pow(zoo, Rational(-1, 3), evaluate=False).evalf() == 0
658
+ assert Pow(zoo, Rational(1, 3), evaluate=False).evalf() == zoo
659
+ assert Pow(zoo, S.Half, evaluate=False).evalf() == zoo
660
+ assert Pow(zoo, 2, evaluate=False).evalf() == zoo
661
+ assert Pow(0, zoo, evaluate=False).evalf() == nan
662
+ assert log(zoo, evaluate=False).evalf() == zoo
663
+ assert zoo.evalf(chop=True) == zoo
664
+ assert x.evalf(subs={x: zoo}) == zoo
665
+
666
+
667
+ def test_evalf_with_bounded_error():
668
+ cases = [
669
+ # zero
670
+ (Rational(0), None, 1),
671
+ # zero im part
672
+ (pi, None, 10),
673
+ # zero real part
674
+ (pi*I, None, 10),
675
+ # re and im nonzero
676
+ (2-3*I, None, 5),
677
+ # similar tests again, but using eps instead of m
678
+ (Rational(0), Rational(1, 2), None),
679
+ (pi, Rational(1, 1000), None),
680
+ (pi * I, Rational(1, 1000), None),
681
+ (2 - 3 * I, Rational(1, 1000), None),
682
+ # very large eps
683
+ (2 - 3 * I, Rational(1000), None),
684
+ # case where x already small, hence some cancellation in p = m + n - 1
685
+ (Rational(1234, 10**8), Rational(1, 10**12), None),
686
+ ]
687
+ for x0, eps, m in cases:
688
+ a, b, _, _ = evalf(x0, 53, {})
689
+ c, d, _, _ = _evalf_with_bounded_error(x0, eps, m)
690
+ if eps is None:
691
+ eps = 2**(-m)
692
+ z = make_mpc((a or fzero, b or fzero))
693
+ w = make_mpc((c or fzero, d or fzero))
694
+ assert abs(w - z) < eps
695
+
696
+ # eps must be positive
697
+ raises(ValueError, lambda: _evalf_with_bounded_error(pi, Rational(0)))
698
+ raises(ValueError, lambda: _evalf_with_bounded_error(pi, -pi))
699
+ raises(ValueError, lambda: _evalf_with_bounded_error(pi, I))
700
+
701
+
702
+ def test_issue_22849():
703
+ a = -8 + 3 * sqrt(3)
704
+ x = AlgebraicNumber(a)
705
+ assert evalf(a, 1, {}) == evalf(x, 1, {})
706
+
707
+
708
+ def test_evalf_real_alg_num():
709
+ # This test demonstrates why the entry for `AlgebraicNumber` in
710
+ # `sympy.core.evalf._create_evalf_table()` has to use `x.to_root()`,
711
+ # instead of `x.as_expr()`. If the latter is used, then `z` will be
712
+ # a complex number with `0.e-20` for imaginary part, even though `a5`
713
+ # is a real number.
714
+ zeta = Symbol('zeta')
715
+ a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1), [-1, -1, 0, 0], alias=zeta)
716
+ z = a5.evalf()
717
+ assert isinstance(z, Float)
718
+ assert not hasattr(z, '_mpc_')
719
+ assert hasattr(z, '_mpf_')
720
+
721
+
722
+ def test_issue_20733():
723
+ expr = 1/((x - 9)*(x - 8)*(x - 7)*(x - 4)**2*(x - 3)**3*(x - 2))
724
+ assert str(expr.evalf(1, subs={x:1})) == '-4.e-5'
725
+ assert str(expr.evalf(2, subs={x:1})) == '-4.1e-5'
726
+ assert str(expr.evalf(11, subs={x:1})) == '-4.1335978836e-5'
727
+ assert str(expr.evalf(20, subs={x:1})) == '-0.000041335978835978835979'
728
+
729
+ expr = Mul(*((x - i) for i in range(2, 1000)))
730
+ assert srepr(expr.evalf(2, subs={x: 1})) == "Float('4.0271e+2561', precision=10)"
731
+ assert srepr(expr.evalf(10, subs={x: 1})) == "Float('4.02790050126e+2561', precision=37)"
732
+ assert srepr(expr.evalf(53, subs={x: 1})) == "Float('4.0279005012722099453824067459760158730668154575647110393e+2561', precision=179)"
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_expr.py ADDED
@@ -0,0 +1,2261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions.refine import refine
2
+ from sympy.concrete.summations import Sum
3
+ from sympy.core.add import Add
4
+ from sympy.core.basic import Basic
5
+ from sympy.core.containers import Tuple
6
+ from sympy.core.expr import (ExprBuilder, unchanged, Expr,
7
+ UnevaluatedExpr)
8
+ from sympy.core.function import (Function, expand, WildFunction,
9
+ AppliedUndef, Derivative, diff, Subs)
10
+ from sympy.core.mul import Mul
11
+ from sympy.core.numbers import (NumberSymbol, E, zoo, oo, Float, I,
12
+ Rational, nan, Integer, Number, pi, _illegal)
13
+ from sympy.core.power import Pow
14
+ from sympy.core.relational import Ge, Lt, Gt, Le
15
+ from sympy.core.singleton import S
16
+ from sympy.core.sorting import default_sort_key
17
+ from sympy.core.symbol import Symbol, symbols, Dummy, Wild
18
+ from sympy.core.sympify import sympify
19
+ from sympy.functions.combinatorial.factorials import factorial
20
+ from sympy.functions.elementary.exponential import exp_polar, exp, log
21
+ from sympy.functions.elementary.miscellaneous import sqrt, Max
22
+ from sympy.functions.elementary.piecewise import Piecewise
23
+ from sympy.functions.elementary.trigonometric import tan, sin, cos
24
+ from sympy.functions.special.delta_functions import (Heaviside,
25
+ DiracDelta)
26
+ from sympy.functions.special.error_functions import Si
27
+ from sympy.functions.special.gamma_functions import gamma
28
+ from sympy.integrals.integrals import integrate, Integral
29
+ from sympy.physics.secondquant import FockState
30
+ from sympy.polys.partfrac import apart
31
+ from sympy.polys.polytools import factor, cancel, Poly
32
+ from sympy.polys.rationaltools import together
33
+ from sympy.series.order import O
34
+ from sympy.sets.sets import FiniteSet
35
+ from sympy.simplify.combsimp import combsimp
36
+ from sympy.simplify.gammasimp import gammasimp
37
+ from sympy.simplify.powsimp import powsimp
38
+ from sympy.simplify.radsimp import collect, radsimp
39
+ from sympy.simplify.ratsimp import ratsimp
40
+ from sympy.simplify.simplify import simplify, nsimplify
41
+ from sympy.simplify.trigsimp import trigsimp
42
+ from sympy.tensor.indexed import Indexed
43
+ from sympy.physics.units import meter
44
+
45
+ from sympy.testing.pytest import raises, XFAIL
46
+
47
+ from sympy.abc import a, b, c, n, t, u, x, y, z
48
+
49
+
50
+ f, g, h = symbols('f,g,h', cls=Function)
51
+
52
+
53
+ class DummyNumber:
54
+ """
55
+ Minimal implementation of a number that works with SymPy.
56
+
57
+ If one has a Number class (e.g. Sage Integer, or some other custom class)
58
+ that one wants to work well with SymPy, one has to implement at least the
59
+ methods of this class DummyNumber, resp. its subclasses I5 and F1_1.
60
+
61
+ Basically, one just needs to implement either __int__() or __float__() and
62
+ then one needs to make sure that the class works with Python integers and
63
+ with itself.
64
+ """
65
+
66
+ def __radd__(self, a):
67
+ if isinstance(a, (int, float)):
68
+ return a + self.number
69
+ return NotImplemented
70
+
71
+ def __add__(self, a):
72
+ if isinstance(a, (int, float, DummyNumber)):
73
+ return self.number + a
74
+ return NotImplemented
75
+
76
+ def __rsub__(self, a):
77
+ if isinstance(a, (int, float)):
78
+ return a - self.number
79
+ return NotImplemented
80
+
81
+ def __sub__(self, a):
82
+ if isinstance(a, (int, float, DummyNumber)):
83
+ return self.number - a
84
+ return NotImplemented
85
+
86
+ def __rmul__(self, a):
87
+ if isinstance(a, (int, float)):
88
+ return a * self.number
89
+ return NotImplemented
90
+
91
+ def __mul__(self, a):
92
+ if isinstance(a, (int, float, DummyNumber)):
93
+ return self.number * a
94
+ return NotImplemented
95
+
96
+ def __rtruediv__(self, a):
97
+ if isinstance(a, (int, float)):
98
+ return a / self.number
99
+ return NotImplemented
100
+
101
+ def __truediv__(self, a):
102
+ if isinstance(a, (int, float, DummyNumber)):
103
+ return self.number / a
104
+ return NotImplemented
105
+
106
+ def __rpow__(self, a):
107
+ if isinstance(a, (int, float)):
108
+ return a ** self.number
109
+ return NotImplemented
110
+
111
+ def __pow__(self, a):
112
+ if isinstance(a, (int, float, DummyNumber)):
113
+ return self.number ** a
114
+ return NotImplemented
115
+
116
+ def __pos__(self):
117
+ return self.number
118
+
119
+ def __neg__(self):
120
+ return - self.number
121
+
122
+
123
+ class I5(DummyNumber):
124
+ number = 5
125
+
126
+ def __int__(self):
127
+ return self.number
128
+
129
+
130
+ class F1_1(DummyNumber):
131
+ number = 1.1
132
+
133
+ def __float__(self):
134
+ return self.number
135
+
136
+ i5 = I5()
137
+ f1_1 = F1_1()
138
+
139
+ # basic SymPy objects
140
+ basic_objs = [
141
+ Rational(2),
142
+ Float("1.3"),
143
+ x,
144
+ y,
145
+ pow(x, y)*y,
146
+ ]
147
+
148
+ # all supported objects
149
+ all_objs = basic_objs + [
150
+ 5,
151
+ 5.5,
152
+ i5,
153
+ f1_1
154
+ ]
155
+
156
+
157
+ def dotest(s):
158
+ for xo in all_objs:
159
+ for yo in all_objs:
160
+ s(xo, yo)
161
+ return True
162
+
163
+
164
+ def test_basic():
165
+ def j(a, b):
166
+ x = a
167
+ x = +a
168
+ x = -a
169
+ x = a + b
170
+ x = a - b
171
+ x = a*b
172
+ x = a/b
173
+ x = a**b
174
+ del x
175
+ assert dotest(j)
176
+
177
+
178
+ def test_ibasic():
179
+ def s(a, b):
180
+ x = a
181
+ x += b
182
+ x = a
183
+ x -= b
184
+ x = a
185
+ x *= b
186
+ x = a
187
+ x /= b
188
+ assert dotest(s)
189
+
190
+
191
+ class NonBasic:
192
+ '''This class represents an object that knows how to implement binary
193
+ operations like +, -, etc with Expr but is not a subclass of Basic itself.
194
+ The NonExpr subclass below does subclass Basic but not Expr.
195
+
196
+ For both NonBasic and NonExpr it should be possible for them to override
197
+ Expr.__add__ etc because Expr.__add__ should be returning NotImplemented
198
+ for non Expr classes. Otherwise Expr.__add__ would create meaningless
199
+ objects like Add(Integer(1), FiniteSet(2)) and it wouldn't be possible for
200
+ other classes to override these operations when interacting with Expr.
201
+ '''
202
+ def __add__(self, other):
203
+ return SpecialOp('+', self, other)
204
+
205
+ def __radd__(self, other):
206
+ return SpecialOp('+', other, self)
207
+
208
+ def __sub__(self, other):
209
+ return SpecialOp('-', self, other)
210
+
211
+ def __rsub__(self, other):
212
+ return SpecialOp('-', other, self)
213
+
214
+ def __mul__(self, other):
215
+ return SpecialOp('*', self, other)
216
+
217
+ def __rmul__(self, other):
218
+ return SpecialOp('*', other, self)
219
+
220
+ def __truediv__(self, other):
221
+ return SpecialOp('/', self, other)
222
+
223
+ def __rtruediv__(self, other):
224
+ return SpecialOp('/', other, self)
225
+
226
+ def __floordiv__(self, other):
227
+ return SpecialOp('//', self, other)
228
+
229
+ def __rfloordiv__(self, other):
230
+ return SpecialOp('//', other, self)
231
+
232
+ def __mod__(self, other):
233
+ return SpecialOp('%', self, other)
234
+
235
+ def __rmod__(self, other):
236
+ return SpecialOp('%', other, self)
237
+
238
+ def __divmod__(self, other):
239
+ return SpecialOp('divmod', self, other)
240
+
241
+ def __rdivmod__(self, other):
242
+ return SpecialOp('divmod', other, self)
243
+
244
+ def __pow__(self, other):
245
+ return SpecialOp('**', self, other)
246
+
247
+ def __rpow__(self, other):
248
+ return SpecialOp('**', other, self)
249
+
250
+ def __lt__(self, other):
251
+ return SpecialOp('<', self, other)
252
+
253
+ def __gt__(self, other):
254
+ return SpecialOp('>', self, other)
255
+
256
+ def __le__(self, other):
257
+ return SpecialOp('<=', self, other)
258
+
259
+ def __ge__(self, other):
260
+ return SpecialOp('>=', self, other)
261
+
262
+
263
+ class NonExpr(Basic, NonBasic):
264
+ '''Like NonBasic above except this is a subclass of Basic but not Expr'''
265
+ pass
266
+
267
+
268
+ class SpecialOp():
269
+ '''Represents the results of operations with NonBasic and NonExpr'''
270
+ def __new__(cls, op, arg1, arg2):
271
+ obj = object.__new__(cls)
272
+ obj.args = (op, arg1, arg2)
273
+ return obj
274
+
275
+
276
+ class NonArithmetic(Basic):
277
+ '''Represents a Basic subclass that does not support arithmetic operations'''
278
+ pass
279
+
280
+
281
+ def test_cooperative_operations():
282
+ '''Tests that Expr uses binary operations cooperatively.
283
+
284
+ In particular it should be possible for non-Expr classes to override
285
+ binary operators like +, - etc when used with Expr instances. This should
286
+ work for non-Expr classes whether they are Basic subclasses or not. Also
287
+ non-Expr classes that do not define binary operators with Expr should give
288
+ TypeError.
289
+ '''
290
+ # A bunch of instances of Expr subclasses
291
+ exprs = [
292
+ Expr(),
293
+ S.Zero,
294
+ S.One,
295
+ S.Infinity,
296
+ S.NegativeInfinity,
297
+ S.ComplexInfinity,
298
+ S.Half,
299
+ Float(0.5),
300
+ Integer(2),
301
+ Symbol('x'),
302
+ Mul(2, Symbol('x')),
303
+ Add(2, Symbol('x')),
304
+ Pow(2, Symbol('x')),
305
+ ]
306
+
307
+ for e in exprs:
308
+ # Test that these classes can override arithmetic operations in
309
+ # combination with various Expr types.
310
+ for ne in [NonBasic(), NonExpr()]:
311
+
312
+ results = [
313
+ (ne + e, ('+', ne, e)),
314
+ (e + ne, ('+', e, ne)),
315
+ (ne - e, ('-', ne, e)),
316
+ (e - ne, ('-', e, ne)),
317
+ (ne * e, ('*', ne, e)),
318
+ (e * ne, ('*', e, ne)),
319
+ (ne / e, ('/', ne, e)),
320
+ (e / ne, ('/', e, ne)),
321
+ (ne // e, ('//', ne, e)),
322
+ (e // ne, ('//', e, ne)),
323
+ (ne % e, ('%', ne, e)),
324
+ (e % ne, ('%', e, ne)),
325
+ (divmod(ne, e), ('divmod', ne, e)),
326
+ (divmod(e, ne), ('divmod', e, ne)),
327
+ (ne ** e, ('**', ne, e)),
328
+ (e ** ne, ('**', e, ne)),
329
+ (e < ne, ('>', ne, e)),
330
+ (ne < e, ('<', ne, e)),
331
+ (e > ne, ('<', ne, e)),
332
+ (ne > e, ('>', ne, e)),
333
+ (e <= ne, ('>=', ne, e)),
334
+ (ne <= e, ('<=', ne, e)),
335
+ (e >= ne, ('<=', ne, e)),
336
+ (ne >= e, ('>=', ne, e)),
337
+ ]
338
+
339
+ for res, args in results:
340
+ assert type(res) is SpecialOp and res.args == args
341
+
342
+ # These classes do not support binary operators with Expr. Every
343
+ # operation should raise in combination with any of the Expr types.
344
+ for na in [NonArithmetic(), object()]:
345
+
346
+ raises(TypeError, lambda : e + na)
347
+ raises(TypeError, lambda : na + e)
348
+ raises(TypeError, lambda : e - na)
349
+ raises(TypeError, lambda : na - e)
350
+ raises(TypeError, lambda : e * na)
351
+ raises(TypeError, lambda : na * e)
352
+ raises(TypeError, lambda : e / na)
353
+ raises(TypeError, lambda : na / e)
354
+ raises(TypeError, lambda : e // na)
355
+ raises(TypeError, lambda : na // e)
356
+ raises(TypeError, lambda : e % na)
357
+ raises(TypeError, lambda : na % e)
358
+ raises(TypeError, lambda : divmod(e, na))
359
+ raises(TypeError, lambda : divmod(na, e))
360
+ raises(TypeError, lambda : e ** na)
361
+ raises(TypeError, lambda : na ** e)
362
+ raises(TypeError, lambda : e > na)
363
+ raises(TypeError, lambda : na > e)
364
+ raises(TypeError, lambda : e < na)
365
+ raises(TypeError, lambda : na < e)
366
+ raises(TypeError, lambda : e >= na)
367
+ raises(TypeError, lambda : na >= e)
368
+ raises(TypeError, lambda : e <= na)
369
+ raises(TypeError, lambda : na <= e)
370
+
371
+
372
+ def test_relational():
373
+ from sympy.core.relational import Lt
374
+ assert (pi < 3) is S.false
375
+ assert (pi <= 3) is S.false
376
+ assert (pi > 3) is S.true
377
+ assert (pi >= 3) is S.true
378
+ assert (-pi < 3) is S.true
379
+ assert (-pi <= 3) is S.true
380
+ assert (-pi > 3) is S.false
381
+ assert (-pi >= 3) is S.false
382
+ r = Symbol('r', real=True)
383
+ assert (r - 2 < r - 3) is S.false
384
+ assert Lt(x + I, x + I + 2).func == Lt # issue 8288
385
+
386
+
387
+ def test_relational_assumptions():
388
+ m1 = Symbol("m1", nonnegative=False)
389
+ m2 = Symbol("m2", positive=False)
390
+ m3 = Symbol("m3", nonpositive=False)
391
+ m4 = Symbol("m4", negative=False)
392
+ assert (m1 < 0) == Lt(m1, 0)
393
+ assert (m2 <= 0) == Le(m2, 0)
394
+ assert (m3 > 0) == Gt(m3, 0)
395
+ assert (m4 >= 0) == Ge(m4, 0)
396
+ m1 = Symbol("m1", nonnegative=False, real=True)
397
+ m2 = Symbol("m2", positive=False, real=True)
398
+ m3 = Symbol("m3", nonpositive=False, real=True)
399
+ m4 = Symbol("m4", negative=False, real=True)
400
+ assert (m1 < 0) is S.true
401
+ assert (m2 <= 0) is S.true
402
+ assert (m3 > 0) is S.true
403
+ assert (m4 >= 0) is S.true
404
+ m1 = Symbol("m1", negative=True)
405
+ m2 = Symbol("m2", nonpositive=True)
406
+ m3 = Symbol("m3", positive=True)
407
+ m4 = Symbol("m4", nonnegative=True)
408
+ assert (m1 < 0) is S.true
409
+ assert (m2 <= 0) is S.true
410
+ assert (m3 > 0) is S.true
411
+ assert (m4 >= 0) is S.true
412
+ m1 = Symbol("m1", negative=False, real=True)
413
+ m2 = Symbol("m2", nonpositive=False, real=True)
414
+ m3 = Symbol("m3", positive=False, real=True)
415
+ m4 = Symbol("m4", nonnegative=False, real=True)
416
+ assert (m1 < 0) is S.false
417
+ assert (m2 <= 0) is S.false
418
+ assert (m3 > 0) is S.false
419
+ assert (m4 >= 0) is S.false
420
+
421
+
422
+ # See https://github.com/sympy/sympy/issues/17708
423
+ #def test_relational_noncommutative():
424
+ # from sympy import Lt, Gt, Le, Ge
425
+ # A, B = symbols('A,B', commutative=False)
426
+ # assert (A < B) == Lt(A, B)
427
+ # assert (A <= B) == Le(A, B)
428
+ # assert (A > B) == Gt(A, B)
429
+ # assert (A >= B) == Ge(A, B)
430
+
431
+
432
+ def test_basic_nostr():
433
+ for obj in basic_objs:
434
+ raises(TypeError, lambda: obj + '1')
435
+ raises(TypeError, lambda: obj - '1')
436
+ if obj == 2:
437
+ assert obj * '1' == '11'
438
+ else:
439
+ raises(TypeError, lambda: obj * '1')
440
+ raises(TypeError, lambda: obj / '1')
441
+ raises(TypeError, lambda: obj ** '1')
442
+
443
+
444
+ def test_series_expansion_for_uniform_order():
445
+ assert (1/x + y + x).series(x, 0, 0) == 1/x + O(1, x)
446
+ assert (1/x + y + x).series(x, 0, 1) == 1/x + y + O(x)
447
+ assert (1/x + 1 + x).series(x, 0, 0) == 1/x + O(1, x)
448
+ assert (1/x + 1 + x).series(x, 0, 1) == 1/x + 1 + O(x)
449
+ assert (1/x + x).series(x, 0, 0) == 1/x + O(1, x)
450
+ assert (1/x + y + y*x + x).series(x, 0, 0) == 1/x + O(1, x)
451
+ assert (1/x + y + y*x + x).series(x, 0, 1) == 1/x + y + O(x)
452
+
453
+
454
+ def test_leadterm():
455
+ assert (3 + 2*x**(log(3)/log(2) - 1)).leadterm(x) == (3, 0)
456
+
457
+ assert (1/x**2 + 1 + x + x**2).leadterm(x)[1] == -2
458
+ assert (1/x + 1 + x + x**2).leadterm(x)[1] == -1
459
+ assert (x**2 + 1/x).leadterm(x)[1] == -1
460
+ assert (1 + x**2).leadterm(x)[1] == 0
461
+ assert (x + 1).leadterm(x)[1] == 0
462
+ assert (x + x**2).leadterm(x)[1] == 1
463
+ assert (x**2).leadterm(x)[1] == 2
464
+
465
+
466
+ def test_as_leading_term():
467
+ assert (3 + 2*x**(log(3)/log(2) - 1)).as_leading_term(x) == 3
468
+ assert (1/x**2 + 1 + x + x**2).as_leading_term(x) == 1/x**2
469
+ assert (1/x + 1 + x + x**2).as_leading_term(x) == 1/x
470
+ assert (x**2 + 1/x).as_leading_term(x) == 1/x
471
+ assert (1 + x**2).as_leading_term(x) == 1
472
+ assert (x + 1).as_leading_term(x) == 1
473
+ assert (x + x**2).as_leading_term(x) == x
474
+ assert (x**2).as_leading_term(x) == x**2
475
+ assert (x + oo).as_leading_term(x) is oo
476
+
477
+ raises(ValueError, lambda: (x + 1).as_leading_term(1))
478
+
479
+ # https://github.com/sympy/sympy/issues/21177
480
+ e = -3*x + (x + Rational(3, 2) - sqrt(3)*S.ImaginaryUnit/2)**2\
481
+ - Rational(3, 2) + 3*sqrt(3)*S.ImaginaryUnit/2
482
+ assert e.as_leading_term(x) == \
483
+ (12*sqrt(3)*x - 12*S.ImaginaryUnit*x)/(4*sqrt(3) + 12*S.ImaginaryUnit)
484
+
485
+ # https://github.com/sympy/sympy/issues/21245
486
+ e = 1 - x - x**2
487
+ d = (1 + sqrt(5))/2
488
+ assert e.subs(x, y + 1/d).as_leading_term(y) == \
489
+ (-576*sqrt(5)*y - 1280*y)/(256*sqrt(5) + 576)
490
+
491
+
492
+ def test_leadterm2():
493
+ assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).leadterm(x) == \
494
+ (sin(1 + sin(1)), 0)
495
+
496
+
497
+ def test_leadterm3():
498
+ assert (y + z + x).leadterm(x) == (y + z, 0)
499
+
500
+
501
+ def test_as_leading_term2():
502
+ assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).as_leading_term(x) == \
503
+ sin(1 + sin(1))
504
+
505
+
506
+ def test_as_leading_term3():
507
+ assert (2 + pi + x).as_leading_term(x) == 2 + pi
508
+ assert (2*x + pi*x + x**2).as_leading_term(x) == 2*x + pi*x
509
+
510
+
511
+ def test_as_leading_term4():
512
+ # see issue 6843
513
+ n = Symbol('n', integer=True, positive=True)
514
+ r = -n**3/(2*n**2 + 4*n + 2) - n**2/(n**2 + 2*n + 1) + \
515
+ n**2/(n + 1) - n/(2*n**2 + 4*n + 2) + n/(n*x + x) + 2*n/(n + 1) - \
516
+ 1 + 1/(n*x + x) + 1/(n + 1) - 1/x
517
+ assert r.as_leading_term(x).cancel() == n/2
518
+
519
+
520
+ def test_as_leading_term_stub():
521
+ class foo(Function):
522
+ pass
523
+ assert foo(1/x).as_leading_term(x) == foo(1/x)
524
+ assert foo(1).as_leading_term(x) == foo(1)
525
+ raises(NotImplementedError, lambda: foo(x).as_leading_term(x))
526
+
527
+
528
+ def test_as_leading_term_deriv_integral():
529
+ # related to issue 11313
530
+ assert Derivative(x ** 3, x).as_leading_term(x) == 3*x**2
531
+ assert Derivative(x ** 3, y).as_leading_term(x) == 0
532
+
533
+ assert Integral(x ** 3, x).as_leading_term(x) == x**4/4
534
+ assert Integral(x ** 3, y).as_leading_term(x) == y*x**3
535
+
536
+ assert Derivative(exp(x), x).as_leading_term(x) == 1
537
+ assert Derivative(log(x), x).as_leading_term(x) == (1/x).as_leading_term(x)
538
+
539
+
540
+ def test_atoms():
541
+ assert x.atoms() == {x}
542
+ assert (1 + x).atoms() == {x, S.One}
543
+
544
+ assert (1 + 2*cos(x)).atoms(Symbol) == {x}
545
+ assert (1 + 2*cos(x)).atoms(Symbol, Number) == {S.One, S(2), x}
546
+
547
+ assert (2*(x**(y**x))).atoms() == {S(2), x, y}
548
+
549
+ assert S.Half.atoms() == {S.Half}
550
+ assert S.Half.atoms(Symbol) == set()
551
+
552
+ assert sin(oo).atoms(oo) == set()
553
+
554
+ assert Poly(0, x).atoms() == {S.Zero, x}
555
+ assert Poly(1, x).atoms() == {S.One, x}
556
+
557
+ assert Poly(x, x).atoms() == {x}
558
+ assert Poly(x, x, y).atoms() == {x, y}
559
+ assert Poly(x + y, x, y).atoms() == {x, y}
560
+ assert Poly(x + y, x, y, z).atoms() == {x, y, z}
561
+ assert Poly(x + y*t, x, y, z).atoms() == {t, x, y, z}
562
+
563
+ assert (I*pi).atoms(NumberSymbol) == {pi}
564
+ assert (I*pi).atoms(NumberSymbol, I) == \
565
+ (I*pi).atoms(I, NumberSymbol) == {pi, I}
566
+
567
+ assert exp(exp(x)).atoms(exp) == {exp(exp(x)), exp(x)}
568
+ assert (1 + x*(2 + y) + exp(3 + z)).atoms(Add) == \
569
+ {1 + x*(2 + y) + exp(3 + z), 2 + y, 3 + z}
570
+
571
+ # issue 6132
572
+ e = (f(x) + sin(x) + 2)
573
+ assert e.atoms(AppliedUndef) == \
574
+ {f(x)}
575
+ assert e.atoms(AppliedUndef, Function) == \
576
+ {f(x), sin(x)}
577
+ assert e.atoms(Function) == \
578
+ {f(x), sin(x)}
579
+ assert e.atoms(AppliedUndef, Number) == \
580
+ {f(x), S(2)}
581
+ assert e.atoms(Function, Number) == \
582
+ {S(2), sin(x), f(x)}
583
+
584
+
585
+ def test_is_polynomial():
586
+ k = Symbol('k', nonnegative=True, integer=True)
587
+
588
+ assert Rational(2).is_polynomial(x, y, z) is True
589
+ assert (S.Pi).is_polynomial(x, y, z) is True
590
+
591
+ assert x.is_polynomial(x) is True
592
+ assert x.is_polynomial(y) is True
593
+
594
+ assert (x**2).is_polynomial(x) is True
595
+ assert (x**2).is_polynomial(y) is True
596
+
597
+ assert (x**(-2)).is_polynomial(x) is False
598
+ assert (x**(-2)).is_polynomial(y) is True
599
+
600
+ assert (2**x).is_polynomial(x) is False
601
+ assert (2**x).is_polynomial(y) is True
602
+
603
+ assert (x**k).is_polynomial(x) is False
604
+ assert (x**k).is_polynomial(k) is False
605
+ assert (x**x).is_polynomial(x) is False
606
+ assert (k**k).is_polynomial(k) is False
607
+ assert (k**x).is_polynomial(k) is False
608
+
609
+ assert (x**(-k)).is_polynomial(x) is False
610
+ assert ((2*x)**k).is_polynomial(x) is False
611
+
612
+ assert (x**2 + 3*x - 8).is_polynomial(x) is True
613
+ assert (x**2 + 3*x - 8).is_polynomial(y) is True
614
+
615
+ assert (x**2 + 3*x - 8).is_polynomial() is True
616
+
617
+ assert sqrt(x).is_polynomial(x) is False
618
+ assert (sqrt(x)**3).is_polynomial(x) is False
619
+
620
+ assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(x) is True
621
+ assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(y) is False
622
+
623
+ assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial() is True
624
+ assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial() is False
625
+
626
+ assert (
627
+ (x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial(x, y) is True
628
+ assert (
629
+ (x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial(x, y) is False
630
+
631
+ assert (1/f(x) + 1).is_polynomial(f(x)) is False
632
+
633
+
634
+ def test_is_rational_function():
635
+ assert Integer(1).is_rational_function() is True
636
+ assert Integer(1).is_rational_function(x) is True
637
+
638
+ assert Rational(17, 54).is_rational_function() is True
639
+ assert Rational(17, 54).is_rational_function(x) is True
640
+
641
+ assert (12/x).is_rational_function() is True
642
+ assert (12/x).is_rational_function(x) is True
643
+
644
+ assert (x/y).is_rational_function() is True
645
+ assert (x/y).is_rational_function(x) is True
646
+ assert (x/y).is_rational_function(x, y) is True
647
+
648
+ assert (x**2 + 1/x/y).is_rational_function() is True
649
+ assert (x**2 + 1/x/y).is_rational_function(x) is True
650
+ assert (x**2 + 1/x/y).is_rational_function(x, y) is True
651
+
652
+ assert (sin(y)/x).is_rational_function() is False
653
+ assert (sin(y)/x).is_rational_function(y) is False
654
+ assert (sin(y)/x).is_rational_function(x) is True
655
+ assert (sin(y)/x).is_rational_function(x, y) is False
656
+
657
+ for i in _illegal:
658
+ assert not i.is_rational_function()
659
+ for d in (1, x):
660
+ assert not (i/d).is_rational_function()
661
+
662
+
663
+ def test_is_meromorphic():
664
+ f = a/x**2 + b + x + c*x**2
665
+ assert f.is_meromorphic(x, 0) is True
666
+ assert f.is_meromorphic(x, 1) is True
667
+ assert f.is_meromorphic(x, zoo) is True
668
+
669
+ g = 3 + 2*x**(log(3)/log(2) - 1)
670
+ assert g.is_meromorphic(x, 0) is False
671
+ assert g.is_meromorphic(x, 1) is True
672
+ assert g.is_meromorphic(x, zoo) is False
673
+
674
+ n = Symbol('n', integer=True)
675
+ e = sin(1/x)**n*x
676
+ assert e.is_meromorphic(x, 0) is False
677
+ assert e.is_meromorphic(x, 1) is True
678
+ assert e.is_meromorphic(x, zoo) is False
679
+
680
+ e = log(x)**pi
681
+ assert e.is_meromorphic(x, 0) is False
682
+ assert e.is_meromorphic(x, 1) is False
683
+ assert e.is_meromorphic(x, 2) is True
684
+ assert e.is_meromorphic(x, zoo) is False
685
+
686
+ assert (log(x)**a).is_meromorphic(x, 0) is False
687
+ assert (log(x)**a).is_meromorphic(x, 1) is False
688
+ assert (a**log(x)).is_meromorphic(x, 0) is None
689
+ assert (3**log(x)).is_meromorphic(x, 0) is False
690
+ assert (3**log(x)).is_meromorphic(x, 1) is True
691
+
692
+ def test_is_algebraic_expr():
693
+ assert sqrt(3).is_algebraic_expr(x) is True
694
+ assert sqrt(3).is_algebraic_expr() is True
695
+
696
+ eq = ((1 + x**2)/(1 - y**2))**(S.One/3)
697
+ assert eq.is_algebraic_expr(x) is True
698
+ assert eq.is_algebraic_expr(y) is True
699
+
700
+ assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(x) is True
701
+ assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(y) is True
702
+ assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr() is True
703
+
704
+ assert (cos(y)/sqrt(x)).is_algebraic_expr() is False
705
+ assert (cos(y)/sqrt(x)).is_algebraic_expr(x) is True
706
+ assert (cos(y)/sqrt(x)).is_algebraic_expr(y) is False
707
+ assert (cos(y)/sqrt(x)).is_algebraic_expr(x, y) is False
708
+
709
+
710
+ def test_SAGE1():
711
+ #see https://github.com/sympy/sympy/issues/3346
712
+ class MyInt:
713
+ def _sympy_(self):
714
+ return Integer(5)
715
+ m = MyInt()
716
+ e = Rational(2)*m
717
+ assert e == 10
718
+
719
+ raises(TypeError, lambda: Rational(2)*MyInt)
720
+
721
+
722
+ def test_SAGE2():
723
+ class MyInt:
724
+ def __int__(self):
725
+ return 5
726
+ assert sympify(MyInt()) == 5
727
+ e = Rational(2)*MyInt()
728
+ assert e == 10
729
+
730
+ raises(TypeError, lambda: Rational(2)*MyInt)
731
+
732
+
733
+ def test_SAGE3():
734
+ class MySymbol:
735
+ def __rmul__(self, other):
736
+ return ('mys', other, self)
737
+
738
+ o = MySymbol()
739
+ e = x*o
740
+
741
+ assert e == ('mys', x, o)
742
+
743
+
744
+ def test_len():
745
+ e = x*y
746
+ assert len(e.args) == 2
747
+ e = x + y + z
748
+ assert len(e.args) == 3
749
+
750
+
751
+ def test_doit():
752
+ a = Integral(x**2, x)
753
+
754
+ assert isinstance(a.doit(), Integral) is False
755
+
756
+ assert isinstance(a.doit(integrals=True), Integral) is False
757
+ assert isinstance(a.doit(integrals=False), Integral) is True
758
+
759
+ assert (2*Integral(x, x)).doit() == x**2
760
+
761
+
762
+ def test_attribute_error():
763
+ raises(AttributeError, lambda: x.cos())
764
+ raises(AttributeError, lambda: x.sin())
765
+ raises(AttributeError, lambda: x.exp())
766
+
767
+
768
+ def test_args():
769
+ assert (x*y).args in ((x, y), (y, x))
770
+ assert (x + y).args in ((x, y), (y, x))
771
+ assert (x*y + 1).args in ((x*y, 1), (1, x*y))
772
+ assert sin(x*y).args == (x*y,)
773
+ assert sin(x*y).args[0] == x*y
774
+ assert (x**y).args == (x, y)
775
+ assert (x**y).args[0] == x
776
+ assert (x**y).args[1] == y
777
+
778
+
779
+ def test_noncommutative_expand_issue_3757():
780
+ A, B, C = symbols('A,B,C', commutative=False)
781
+ assert A*B - B*A != 0
782
+ assert (A*(A + B)*B).expand() == A**2*B + A*B**2
783
+ assert (A*(A + B + C)*B).expand() == A**2*B + A*B**2 + A*C*B
784
+
785
+
786
+ def test_as_numer_denom():
787
+ a, b, c = symbols('a, b, c')
788
+
789
+ assert nan.as_numer_denom() == (nan, 1)
790
+ assert oo.as_numer_denom() == (oo, 1)
791
+ assert (-oo).as_numer_denom() == (-oo, 1)
792
+ assert zoo.as_numer_denom() == (zoo, 1)
793
+ assert (-zoo).as_numer_denom() == (zoo, 1)
794
+
795
+ assert x.as_numer_denom() == (x, 1)
796
+ assert (1/x).as_numer_denom() == (1, x)
797
+ assert (x/y).as_numer_denom() == (x, y)
798
+ assert (x/2).as_numer_denom() == (x, 2)
799
+ assert (x*y/z).as_numer_denom() == (x*y, z)
800
+ assert (x/(y*z)).as_numer_denom() == (x, y*z)
801
+ assert S.Half.as_numer_denom() == (1, 2)
802
+ assert (1/y**2).as_numer_denom() == (1, y**2)
803
+ assert (x/y**2).as_numer_denom() == (x, y**2)
804
+ assert ((x**2 + 1)/y).as_numer_denom() == (x**2 + 1, y)
805
+ assert (x*(y + 1)/y**7).as_numer_denom() == (x*(y + 1), y**7)
806
+ assert (x**-2).as_numer_denom() == (1, x**2)
807
+ assert (a/x + b/2/x + c/3/x).as_numer_denom() == \
808
+ (6*a + 3*b + 2*c, 6*x)
809
+ assert (a/x + b/2/x + c/3/y).as_numer_denom() == \
810
+ (2*c*x + y*(6*a + 3*b), 6*x*y)
811
+ assert (a/x + b/2/x + c/.5/x).as_numer_denom() == \
812
+ (2*a + b + 4.0*c, 2*x)
813
+ # this should take no more than a few seconds
814
+ assert int(log(Add(*[Dummy()/i/x for i in range(1, 705)]
815
+ ).as_numer_denom()[1]/x).n(4)) == 705
816
+ for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
817
+ assert (i + x/3).as_numer_denom() == \
818
+ (x + i, 3)
819
+ assert (S.Infinity + x/3 + y/4).as_numer_denom() == \
820
+ (4*x + 3*y + S.Infinity, 12)
821
+ assert (oo*x + zoo*y).as_numer_denom() == \
822
+ (zoo*y + oo*x, 1)
823
+
824
+ A, B, C = symbols('A,B,C', commutative=False)
825
+
826
+ assert (A*B*C**-1).as_numer_denom() == (A*B*C**-1, 1)
827
+ assert (A*B*C**-1/x).as_numer_denom() == (A*B*C**-1, x)
828
+ assert (C**-1*A*B).as_numer_denom() == (C**-1*A*B, 1)
829
+ assert (C**-1*A*B/x).as_numer_denom() == (C**-1*A*B, x)
830
+ assert ((A*B*C)**-1).as_numer_denom() == ((A*B*C)**-1, 1)
831
+ assert ((A*B*C)**-1/x).as_numer_denom() == ((A*B*C)**-1, x)
832
+
833
+ # the following morphs from Add to Mul during processing
834
+ assert Add(0, (x + y)/z/-2, evaluate=False).as_numer_denom(
835
+ ) == (-x - y, 2*z)
836
+
837
+
838
+ def test_trunc():
839
+ import math
840
+ x, y = symbols('x y')
841
+ assert math.trunc(2) == 2
842
+ assert math.trunc(4.57) == 4
843
+ assert math.trunc(-5.79) == -5
844
+ assert math.trunc(pi) == 3
845
+ assert math.trunc(log(7)) == 1
846
+ assert math.trunc(exp(5)) == 148
847
+ assert math.trunc(cos(pi)) == -1
848
+ assert math.trunc(sin(5)) == 0
849
+
850
+ raises(TypeError, lambda: math.trunc(x))
851
+ raises(TypeError, lambda: math.trunc(x + y**2))
852
+ raises(TypeError, lambda: math.trunc(oo))
853
+
854
+
855
+ def test_as_independent():
856
+ assert S.Zero.as_independent(x, as_Add=True) == (0, 0)
857
+ assert S.Zero.as_independent(x, as_Add=False) == (0, 0)
858
+ assert (2*x*sin(x) + y + x).as_independent(x) == (y, x + 2*x*sin(x))
859
+ assert (2*x*sin(x) + y + x).as_independent(y) == (x + 2*x*sin(x), y)
860
+
861
+ assert (2*x*sin(x) + y + x).as_independent(x, y) == (0, y + x + 2*x*sin(x))
862
+
863
+ assert (x*sin(x)*cos(y)).as_independent(x) == (cos(y), x*sin(x))
864
+ assert (x*sin(x)*cos(y)).as_independent(y) == (x*sin(x), cos(y))
865
+
866
+ assert (x*sin(x)*cos(y)).as_independent(x, y) == (1, x*sin(x)*cos(y))
867
+
868
+ assert (sin(x)).as_independent(x) == (1, sin(x))
869
+ assert (sin(x)).as_independent(y) == (sin(x), 1)
870
+
871
+ assert (2*sin(x)).as_independent(x) == (2, sin(x))
872
+ assert (2*sin(x)).as_independent(y) == (2*sin(x), 1)
873
+
874
+ # issue 4903 = 1766b
875
+ n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
876
+ assert (n1 + n1*n2).as_independent(n2) == (n1, n1*n2)
877
+ assert (n2*n1 + n1*n2).as_independent(n2) == (0, n1*n2 + n2*n1)
878
+ assert (n1*n2*n1).as_independent(n2) == (n1, n2*n1)
879
+ assert (n1*n2*n1).as_independent(n1) == (1, n1*n2*n1)
880
+
881
+ assert (3*x).as_independent(x, as_Add=True) == (0, 3*x)
882
+ assert (3*x).as_independent(x, as_Add=False) == (3, x)
883
+ assert (3 + x).as_independent(x, as_Add=True) == (3, x)
884
+ assert (3 + x).as_independent(x, as_Add=False) == (1, 3 + x)
885
+
886
+ # issue 5479
887
+ assert (3*x).as_independent(Symbol) == (3, x)
888
+
889
+ # issue 5648
890
+ assert (n1*x*y).as_independent(x) == (n1*y, x)
891
+ assert ((x + n1)*(x - y)).as_independent(x) == (1, (x + n1)*(x - y))
892
+ assert ((x + n1)*(x - y)).as_independent(y) == (x + n1, x - y)
893
+ assert (DiracDelta(x - n1)*DiracDelta(x - y)).as_independent(x) \
894
+ == (1, DiracDelta(x - n1)*DiracDelta(x - y))
895
+ assert (x*y*n1*n2*n3).as_independent(n2) == (x*y*n1, n2*n3)
896
+ assert (x*y*n1*n2*n3).as_independent(n1) == (x*y, n1*n2*n3)
897
+ assert (x*y*n1*n2*n3).as_independent(n3) == (x*y*n1*n2, n3)
898
+ assert (DiracDelta(x - n1)*DiracDelta(y - n1)*DiracDelta(x - n2)).as_independent(y) == \
899
+ (DiracDelta(x - n1)*DiracDelta(x - n2), DiracDelta(y - n1))
900
+
901
+ # issue 5784
902
+ assert (x + Integral(x, (x, 1, 2))).as_independent(x, strict=True) == \
903
+ (Integral(x, (x, 1, 2)), x)
904
+
905
+ eq = Add(x, -x, 2, -3, evaluate=False)
906
+ assert eq.as_independent(x) == (-1, Add(x, -x, evaluate=False))
907
+ eq = Mul(x, 1/x, 2, -3, evaluate=False)
908
+ assert eq.as_independent(x) == (-6, Mul(x, 1/x, evaluate=False))
909
+
910
+ assert (x*y).as_independent(z, as_Add=True) == (x*y, 0)
911
+
912
+ @XFAIL
913
+ def test_call_2():
914
+ # TODO UndefinedFunction does not subclass Expr
915
+ assert (2*f)(x) == 2*f(x)
916
+
917
+
918
+ def test_replace():
919
+ e = log(sin(x)) + tan(sin(x**2))
920
+
921
+ assert e.replace(sin, cos) == log(cos(x)) + tan(cos(x**2))
922
+ assert e.replace(
923
+ sin, lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2))
924
+
925
+ a = Wild('a')
926
+ b = Wild('b')
927
+
928
+ assert e.replace(sin(a), cos(a)) == log(cos(x)) + tan(cos(x**2))
929
+ assert e.replace(
930
+ sin(a), lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2))
931
+ # test exact
932
+ assert (2*x).replace(a*x + b, b - a, exact=True) == 2*x
933
+ assert (2*x).replace(a*x + b, b - a) == 2*x
934
+ assert (2*x).replace(a*x + b, b - a, exact=False) == 2/x
935
+ assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=True) == 2*x
936
+ assert (2*x).replace(a*x + b, lambda a, b: b - a) == 2*x
937
+ assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=False) == 2/x
938
+
939
+ g = 2*sin(x**3)
940
+
941
+ assert g.replace(
942
+ lambda expr: expr.is_Number, lambda expr: expr**2) == 4*sin(x**9)
943
+
944
+ assert cos(x).replace(cos, sin, map=True) == (sin(x), {cos(x): sin(x)})
945
+ assert sin(x).replace(cos, sin) == sin(x)
946
+
947
+ cond, func = lambda x: x.is_Mul, lambda x: 2*x
948
+ assert (x*y).replace(cond, func, map=True) == (2*x*y, {x*y: 2*x*y})
949
+ assert (x*(1 + x*y)).replace(cond, func, map=True) == \
950
+ (2*x*(2*x*y + 1), {x*(2*x*y + 1): 2*x*(2*x*y + 1), x*y: 2*x*y})
951
+ assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y, map=True) == \
952
+ (sin(x), {sin(x): sin(x)/y})
953
+ # if not simultaneous then y*sin(x) -> y*sin(x)/y = sin(x) -> sin(x)/y
954
+ assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y,
955
+ simultaneous=False) == sin(x)/y
956
+ assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e
957
+ ) == x**2/2 + O(x**3)
958
+ assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e,
959
+ simultaneous=False) == x**2/2 + O(x**3)
960
+ assert (x*(x*y + 3)).replace(lambda x: x.is_Mul, lambda x: 2 + x) == \
961
+ x*(x*y + 5) + 2
962
+ e = (x*y + 1)*(2*x*y + 1) + 1
963
+ assert e.replace(cond, func, map=True) == (
964
+ 2*((2*x*y + 1)*(4*x*y + 1)) + 1,
965
+ {2*x*y: 4*x*y, x*y: 2*x*y, (2*x*y + 1)*(4*x*y + 1):
966
+ 2*((2*x*y + 1)*(4*x*y + 1))})
967
+ assert x.replace(x, y) == y
968
+ assert (x + 1).replace(1, 2) == x + 2
969
+
970
+ # https://groups.google.com/forum/#!topic/sympy/8wCgeC95tz0
971
+ n1, n2, n3 = symbols('n1:4', commutative=False)
972
+ assert (n1*f(n2)).replace(f, lambda x: x) == n1*n2
973
+ assert (n3*f(n2)).replace(f, lambda x: x) == n3*n2
974
+
975
+ # issue 16725
976
+ assert S.Zero.replace(Wild('x'), 1) == 1
977
+ # let the user override the default decision of False
978
+ assert S.Zero.replace(Wild('x'), 1, exact=True) == 0
979
+
980
+
981
+ def test_find():
982
+ expr = (x + y + 2 + sin(3*x))
983
+
984
+ assert expr.find(lambda u: u.is_Integer) == {S(2), S(3)}
985
+ assert expr.find(lambda u: u.is_Symbol) == {x, y}
986
+
987
+ assert expr.find(lambda u: u.is_Integer, group=True) == {S(2): 1, S(3): 1}
988
+ assert expr.find(lambda u: u.is_Symbol, group=True) == {x: 2, y: 1}
989
+
990
+ assert expr.find(Integer) == {S(2), S(3)}
991
+ assert expr.find(Symbol) == {x, y}
992
+
993
+ assert expr.find(Integer, group=True) == {S(2): 1, S(3): 1}
994
+ assert expr.find(Symbol, group=True) == {x: 2, y: 1}
995
+
996
+ a = Wild('a')
997
+
998
+ expr = sin(sin(x)) + sin(x) + cos(x) + x
999
+
1000
+ assert expr.find(lambda u: type(u) is sin) == {sin(x), sin(sin(x))}
1001
+ assert expr.find(
1002
+ lambda u: type(u) is sin, group=True) == {sin(x): 2, sin(sin(x)): 1}
1003
+
1004
+ assert expr.find(sin(a)) == {sin(x), sin(sin(x))}
1005
+ assert expr.find(sin(a), group=True) == {sin(x): 2, sin(sin(x)): 1}
1006
+
1007
+ assert expr.find(sin) == {sin(x), sin(sin(x))}
1008
+ assert expr.find(sin, group=True) == {sin(x): 2, sin(sin(x)): 1}
1009
+
1010
+
1011
+ def test_count():
1012
+ expr = (x + y + 2 + sin(3*x))
1013
+
1014
+ assert expr.count(lambda u: u.is_Integer) == 2
1015
+ assert expr.count(lambda u: u.is_Symbol) == 3
1016
+
1017
+ assert expr.count(Integer) == 2
1018
+ assert expr.count(Symbol) == 3
1019
+ assert expr.count(2) == 1
1020
+
1021
+ a = Wild('a')
1022
+
1023
+ assert expr.count(sin) == 1
1024
+ assert expr.count(sin(a)) == 1
1025
+ assert expr.count(lambda u: type(u) is sin) == 1
1026
+
1027
+ assert f(x).count(f(x)) == 1
1028
+ assert f(x).diff(x).count(f(x)) == 1
1029
+ assert f(x).diff(x).count(x) == 2
1030
+
1031
+
1032
+ def test_has_basics():
1033
+ p = Wild('p')
1034
+
1035
+ assert sin(x).has(x)
1036
+ assert sin(x).has(sin)
1037
+ assert not sin(x).has(y)
1038
+ assert not sin(x).has(cos)
1039
+ assert f(x).has(x)
1040
+ assert f(x).has(f)
1041
+ assert not f(x).has(y)
1042
+ assert not f(x).has(g)
1043
+
1044
+ assert f(x).diff(x).has(x)
1045
+ assert f(x).diff(x).has(f)
1046
+ assert f(x).diff(x).has(Derivative)
1047
+ assert not f(x).diff(x).has(y)
1048
+ assert not f(x).diff(x).has(g)
1049
+ assert not f(x).diff(x).has(sin)
1050
+
1051
+ assert (x**2).has(Symbol)
1052
+ assert not (x**2).has(Wild)
1053
+ assert (2*p).has(Wild)
1054
+
1055
+ assert not x.has()
1056
+
1057
+
1058
+ def test_has_multiple():
1059
+ f = x**2*y + sin(2**t + log(z))
1060
+
1061
+ assert f.has(x)
1062
+ assert f.has(y)
1063
+ assert f.has(z)
1064
+ assert f.has(t)
1065
+
1066
+ assert not f.has(u)
1067
+
1068
+ assert f.has(x, y, z, t)
1069
+ assert f.has(x, y, z, t, u)
1070
+
1071
+ i = Integer(4400)
1072
+
1073
+ assert not i.has(x)
1074
+
1075
+ assert (i*x**i).has(x)
1076
+ assert not (i*y**i).has(x)
1077
+ assert (i*y**i).has(x, y)
1078
+ assert not (i*y**i).has(x, z)
1079
+
1080
+
1081
+ def test_has_piecewise():
1082
+ f = (x*y + 3/y)**(3 + 2)
1083
+ p = Piecewise((g(x), x < -1), (1, x <= 1), (f, True))
1084
+
1085
+ assert p.has(x)
1086
+ assert p.has(y)
1087
+ assert not p.has(z)
1088
+ assert p.has(1)
1089
+ assert p.has(3)
1090
+ assert not p.has(4)
1091
+ assert p.has(f)
1092
+ assert p.has(g)
1093
+ assert not p.has(h)
1094
+
1095
+
1096
+ def test_has_iterative():
1097
+ A, B, C = symbols('A,B,C', commutative=False)
1098
+ f = x*gamma(x)*sin(x)*exp(x*y)*A*B*C*cos(x*A*B)
1099
+
1100
+ assert f.has(x)
1101
+ assert f.has(x*y)
1102
+ assert f.has(x*sin(x))
1103
+ assert not f.has(x*sin(y))
1104
+ assert f.has(x*A)
1105
+ assert f.has(x*A*B)
1106
+ assert not f.has(x*A*C)
1107
+ assert f.has(x*A*B*C)
1108
+ assert not f.has(x*A*C*B)
1109
+ assert f.has(x*sin(x)*A*B*C)
1110
+ assert not f.has(x*sin(x)*A*C*B)
1111
+ assert not f.has(x*sin(y)*A*B*C)
1112
+ assert f.has(x*gamma(x))
1113
+ assert not f.has(x + sin(x))
1114
+
1115
+ assert (x & y & z).has(x & z)
1116
+
1117
+
1118
+ def test_has_integrals():
1119
+ f = Integral(x**2 + sin(x*y*z), (x, 0, x + y + z))
1120
+
1121
+ assert f.has(x + y)
1122
+ assert f.has(x + z)
1123
+ assert f.has(y + z)
1124
+
1125
+ assert f.has(x*y)
1126
+ assert f.has(x*z)
1127
+ assert f.has(y*z)
1128
+
1129
+ assert not f.has(2*x + y)
1130
+ assert not f.has(2*x*y)
1131
+
1132
+
1133
+ def test_has_tuple():
1134
+ assert Tuple(x, y).has(x)
1135
+ assert not Tuple(x, y).has(z)
1136
+ assert Tuple(f(x), g(x)).has(x)
1137
+ assert not Tuple(f(x), g(x)).has(y)
1138
+ assert Tuple(f(x), g(x)).has(f)
1139
+ assert Tuple(f(x), g(x)).has(f(x))
1140
+ # XXX to be deprecated
1141
+ #assert not Tuple(f, g).has(x)
1142
+ #assert Tuple(f, g).has(f)
1143
+ #assert not Tuple(f, g).has(h)
1144
+ assert Tuple(True).has(True)
1145
+ assert Tuple(True).has(S.true)
1146
+ assert not Tuple(True).has(1)
1147
+
1148
+
1149
+ def test_has_units():
1150
+ from sympy.physics.units import m, s
1151
+
1152
+ assert (x*m/s).has(x)
1153
+ assert (x*m/s).has(y, z) is False
1154
+
1155
+
1156
+ def test_has_polys():
1157
+ poly = Poly(x**2 + x*y*sin(z), x, y, t)
1158
+
1159
+ assert poly.has(x)
1160
+ assert poly.has(x, y, z)
1161
+ assert poly.has(x, y, z, t)
1162
+
1163
+
1164
+ def test_has_physics():
1165
+ assert FockState((x, y)).has(x)
1166
+
1167
+
1168
+ def test_as_poly_as_expr():
1169
+ f = x**2 + 2*x*y
1170
+
1171
+ assert f.as_poly().as_expr() == f
1172
+ assert f.as_poly(x, y).as_expr() == f
1173
+
1174
+ assert (f + sin(x)).as_poly(x, y) is None
1175
+
1176
+ p = Poly(f, x, y)
1177
+
1178
+ assert p.as_poly() == p
1179
+
1180
+ # https://github.com/sympy/sympy/issues/20610
1181
+ assert S(2).as_poly() is None
1182
+ assert sqrt(2).as_poly(extension=True) is None
1183
+
1184
+ raises(AttributeError, lambda: Tuple(x, x).as_poly(x))
1185
+ raises(AttributeError, lambda: Tuple(x ** 2, x, y).as_poly(x))
1186
+
1187
+
1188
+ def test_nonzero():
1189
+ assert bool(S.Zero) is False
1190
+ assert bool(S.One) is True
1191
+ assert bool(x) is True
1192
+ assert bool(x + y) is True
1193
+ assert bool(x - x) is False
1194
+ assert bool(x*y) is True
1195
+ assert bool(x*1) is True
1196
+ assert bool(x*0) is False
1197
+
1198
+
1199
+ def test_is_number():
1200
+ assert Float(3.14).is_number is True
1201
+ assert Integer(737).is_number is True
1202
+ assert Rational(3, 2).is_number is True
1203
+ assert Rational(8).is_number is True
1204
+ assert x.is_number is False
1205
+ assert (2*x).is_number is False
1206
+ assert (x + y).is_number is False
1207
+ assert log(2).is_number is True
1208
+ assert log(x).is_number is False
1209
+ assert (2 + log(2)).is_number is True
1210
+ assert (8 + log(2)).is_number is True
1211
+ assert (2 + log(x)).is_number is False
1212
+ assert (8 + log(2) + x).is_number is False
1213
+ assert (1 + x**2/x - x).is_number is True
1214
+ assert Tuple(Integer(1)).is_number is False
1215
+ assert Add(2, x).is_number is False
1216
+ assert Mul(3, 4).is_number is True
1217
+ assert Pow(log(2), 2).is_number is True
1218
+ assert oo.is_number is True
1219
+ g = WildFunction('g')
1220
+ assert g.is_number is False
1221
+ assert (2*g).is_number is False
1222
+ assert (x**2).subs(x, 3).is_number is True
1223
+
1224
+ # test extensibility of .is_number
1225
+ # on subinstances of Basic
1226
+ class A(Basic):
1227
+ pass
1228
+ a = A()
1229
+ assert a.is_number is False
1230
+
1231
+
1232
+ def test_as_coeff_add():
1233
+ assert S(2).as_coeff_add() == (2, ())
1234
+ assert S(3.0).as_coeff_add() == (0, (S(3.0),))
1235
+ assert S(-3.0).as_coeff_add() == (0, (S(-3.0),))
1236
+ assert x.as_coeff_add() == (0, (x,))
1237
+ assert (x - 1).as_coeff_add() == (-1, (x,))
1238
+ assert (x + 1).as_coeff_add() == (1, (x,))
1239
+ assert (x + 2).as_coeff_add() == (2, (x,))
1240
+ assert (x + y).as_coeff_add(y) == (x, (y,))
1241
+ assert (3*x).as_coeff_add(y) == (3*x, ())
1242
+ # don't do expansion
1243
+ e = (x + y)**2
1244
+ assert e.as_coeff_add(y) == (0, (e,))
1245
+
1246
+
1247
+ def test_as_coeff_mul():
1248
+ assert S(2).as_coeff_mul() == (2, ())
1249
+ assert S(3.0).as_coeff_mul() == (1, (S(3.0),))
1250
+ assert S(-3.0).as_coeff_mul() == (-1, (S(3.0),))
1251
+ assert S(-3.0).as_coeff_mul(rational=False) == (-S(3.0), ())
1252
+ assert x.as_coeff_mul() == (1, (x,))
1253
+ assert (-x).as_coeff_mul() == (-1, (x,))
1254
+ assert (2*x).as_coeff_mul() == (2, (x,))
1255
+ assert (x*y).as_coeff_mul(y) == (x, (y,))
1256
+ assert (3 + x).as_coeff_mul() == (1, (3 + x,))
1257
+ assert (3 + x).as_coeff_mul(y) == (3 + x, ())
1258
+ # don't do expansion
1259
+ e = exp(x + y)
1260
+ assert e.as_coeff_mul(y) == (1, (e,))
1261
+ e = 2**(x + y)
1262
+ assert e.as_coeff_mul(y) == (1, (e,))
1263
+ assert (1.1*x).as_coeff_mul(rational=False) == (1.1, (x,))
1264
+ assert (1.1*x).as_coeff_mul() == (1, (1.1, x))
1265
+ assert (-oo*x).as_coeff_mul(rational=True) == (-1, (oo, x))
1266
+
1267
+
1268
+ def test_as_coeff_exponent():
1269
+ assert (3*x**4).as_coeff_exponent(x) == (3, 4)
1270
+ assert (2*x**3).as_coeff_exponent(x) == (2, 3)
1271
+ assert (4*x**2).as_coeff_exponent(x) == (4, 2)
1272
+ assert (6*x**1).as_coeff_exponent(x) == (6, 1)
1273
+ assert (3*x**0).as_coeff_exponent(x) == (3, 0)
1274
+ assert (2*x**0).as_coeff_exponent(x) == (2, 0)
1275
+ assert (1*x**0).as_coeff_exponent(x) == (1, 0)
1276
+ assert (0*x**0).as_coeff_exponent(x) == (0, 0)
1277
+ assert (-1*x**0).as_coeff_exponent(x) == (-1, 0)
1278
+ assert (-2*x**0).as_coeff_exponent(x) == (-2, 0)
1279
+ assert (2*x**3 + pi*x**3).as_coeff_exponent(x) == (2 + pi, 3)
1280
+ assert (x*log(2)/(2*x + pi*x)).as_coeff_exponent(x) == \
1281
+ (log(2)/(2 + pi), 0)
1282
+ # issue 4784
1283
+ D = Derivative
1284
+ fx = D(f(x), x)
1285
+ assert fx.as_coeff_exponent(f(x)) == (fx, 0)
1286
+
1287
+
1288
+ def test_extractions():
1289
+ for base in (2, S.Exp1):
1290
+ assert Pow(base**x, 3, evaluate=False
1291
+ ).extract_multiplicatively(base**x) == base**(2*x)
1292
+ assert (base**(5*x)).extract_multiplicatively(
1293
+ base**(3*x)) == base**(2*x)
1294
+ assert ((x*y)**3).extract_multiplicatively(x**2 * y) == x*y**2
1295
+ assert ((x*y)**3).extract_multiplicatively(x**4 * y) is None
1296
+ assert (2*x).extract_multiplicatively(2) == x
1297
+ assert (2*x).extract_multiplicatively(3) is None
1298
+ assert (2*x).extract_multiplicatively(-1) is None
1299
+ assert (S.Half*x).extract_multiplicatively(3) == x/6
1300
+ assert (sqrt(x)).extract_multiplicatively(x) is None
1301
+ assert (sqrt(x)).extract_multiplicatively(1/x) is None
1302
+ assert x.extract_multiplicatively(-x) is None
1303
+ assert (-2 - 4*I).extract_multiplicatively(-2) == 1 + 2*I
1304
+ assert (-2 - 4*I).extract_multiplicatively(3) is None
1305
+ assert (-2*x - 4*y - 8).extract_multiplicatively(-2) == x + 2*y + 4
1306
+ assert (-2*x*y - 4*x**2*y).extract_multiplicatively(-2*y) == 2*x**2 + x
1307
+ assert (2*x*y + 4*x**2*y).extract_multiplicatively(2*y) == 2*x**2 + x
1308
+ assert (-4*y**2*x).extract_multiplicatively(-3*y) is None
1309
+ assert (2*x).extract_multiplicatively(1) == 2*x
1310
+ assert (-oo).extract_multiplicatively(5) is -oo
1311
+ assert (oo).extract_multiplicatively(5) is oo
1312
+
1313
+ assert ((x*y)**3).extract_additively(1) is None
1314
+ assert (x + 1).extract_additively(x) == 1
1315
+ assert (x + 1).extract_additively(2*x) is None
1316
+ assert (x + 1).extract_additively(-x) is None
1317
+ assert (-x + 1).extract_additively(2*x) is None
1318
+ assert (2*x + 3).extract_additively(x) == x + 3
1319
+ assert (2*x + 3).extract_additively(2) == 2*x + 1
1320
+ assert (2*x + 3).extract_additively(3) == 2*x
1321
+ assert (2*x + 3).extract_additively(-2) is None
1322
+ assert (2*x + 3).extract_additively(3*x) is None
1323
+ assert (2*x + 3).extract_additively(2*x) == 3
1324
+ assert x.extract_additively(0) == x
1325
+ assert S(2).extract_additively(x) is None
1326
+ assert S(2.).extract_additively(2.) is S.Zero
1327
+ assert S(2.).extract_additively(2) is S.Zero
1328
+ assert S(2*x + 3).extract_additively(x + 1) == x + 2
1329
+ assert S(2*x + 3).extract_additively(y + 1) is None
1330
+ assert S(2*x - 3).extract_additively(x + 1) is None
1331
+ assert S(2*x - 3).extract_additively(y + z) is None
1332
+ assert ((a + 1)*x*4 + y).extract_additively(x).expand() == \
1333
+ 4*a*x + 3*x + y
1334
+ assert ((a + 1)*x*4 + 3*y).extract_additively(x + 2*y).expand() == \
1335
+ 4*a*x + 3*x + y
1336
+ assert (y*(x + 1)).extract_additively(x + 1) is None
1337
+ assert ((y + 1)*(x + 1) + 3).extract_additively(x + 1) == \
1338
+ y*(x + 1) + 3
1339
+ assert ((x + y)*(x + 1) + x + y + 3).extract_additively(x + y) == \
1340
+ x*(x + y) + 3
1341
+ assert (x + y + 2*((x + y)*(x + 1)) + 3).extract_additively((x + y)*(x + 1)) == \
1342
+ x + y + (x + 1)*(x + y) + 3
1343
+ assert ((y + 1)*(x + 2*y + 1) + 3).extract_additively(y + 1) == \
1344
+ (x + 2*y)*(y + 1) + 3
1345
+ assert (-x - x*I).extract_additively(-x) == -I*x
1346
+ # extraction does not leave artificats, now
1347
+ assert (4*x*(y + 1) + y).extract_additively(x) == x*(4*y + 3) + y
1348
+
1349
+ n = Symbol("n", integer=True)
1350
+ assert (Integer(-3)).could_extract_minus_sign() is True
1351
+ assert (-n*x + x).could_extract_minus_sign() != \
1352
+ (n*x - x).could_extract_minus_sign()
1353
+ assert (x - y).could_extract_minus_sign() != \
1354
+ (-x + y).could_extract_minus_sign()
1355
+ assert (1 - x - y).could_extract_minus_sign() is True
1356
+ assert (1 - x + y).could_extract_minus_sign() is False
1357
+ assert ((-x - x*y)/y).could_extract_minus_sign() is False
1358
+ assert ((x + x*y)/(-y)).could_extract_minus_sign() is True
1359
+ assert ((x + x*y)/y).could_extract_minus_sign() is False
1360
+ assert ((-x - y)/(x + y)).could_extract_minus_sign() is False
1361
+
1362
+ class sign_invariant(Function, Expr):
1363
+ nargs = 1
1364
+ def __neg__(self):
1365
+ return self
1366
+ foo = sign_invariant(x)
1367
+ assert foo == -foo
1368
+ assert foo.could_extract_minus_sign() is False
1369
+ assert (x - y).could_extract_minus_sign() is False
1370
+ assert (-x + y).could_extract_minus_sign() is True
1371
+ assert (x - 1).could_extract_minus_sign() is False
1372
+ assert (1 - x).could_extract_minus_sign() is True
1373
+ assert (sqrt(2) - 1).could_extract_minus_sign() is True
1374
+ assert (1 - sqrt(2)).could_extract_minus_sign() is False
1375
+ # check that result is canonical
1376
+ eq = (3*x + 15*y).extract_multiplicatively(3)
1377
+ assert eq.args == eq.func(*eq.args).args
1378
+
1379
+
1380
+ def test_nan_extractions():
1381
+ for r in (1, 0, I, nan):
1382
+ assert nan.extract_additively(r) is None
1383
+ assert nan.extract_multiplicatively(r) is None
1384
+
1385
+
1386
+ def test_coeff():
1387
+ assert (x + 1).coeff(x + 1) == 1
1388
+ assert (3*x).coeff(0) == 0
1389
+ assert (z*(1 + x)*x**2).coeff(1 + x) == z*x**2
1390
+ assert (1 + 2*x*x**(1 + x)).coeff(x*x**(1 + x)) == 2
1391
+ assert (1 + 2*x**(y + z)).coeff(x**(y + z)) == 2
1392
+ assert (3 + 2*x + 4*x**2).coeff(1) == 0
1393
+ assert (3 + 2*x + 4*x**2).coeff(-1) == 0
1394
+ assert (3 + 2*x + 4*x**2).coeff(x) == 2
1395
+ assert (3 + 2*x + 4*x**2).coeff(x**2) == 4
1396
+ assert (3 + 2*x + 4*x**2).coeff(x**3) == 0
1397
+
1398
+ assert (-x/8 + x*y).coeff(x) == Rational(-1, 8) + y
1399
+ assert (-x/8 + x*y).coeff(-x) == S.One/8
1400
+ assert (4*x).coeff(2*x) == 0
1401
+ assert (2*x).coeff(2*x) == 1
1402
+ assert (-oo*x).coeff(x*oo) == -1
1403
+ assert (10*x).coeff(x, 0) == 0
1404
+ assert (10*x).coeff(10*x, 0) == 0
1405
+
1406
+ n1, n2 = symbols('n1 n2', commutative=False)
1407
+ assert (n1*n2).coeff(n1) == 1
1408
+ assert (n1*n2).coeff(n2) == n1
1409
+ assert (n1*n2 + x*n1).coeff(n1) == 1 # 1*n1*(n2+x)
1410
+ assert (n2*n1 + x*n1).coeff(n1) == n2 + x
1411
+ assert (n2*n1 + x*n1**2).coeff(n1) == n2
1412
+ assert (n1**x).coeff(n1) == 0
1413
+ assert (n1*n2 + n2*n1).coeff(n1) == 0
1414
+ assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=1) == n2
1415
+ assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=0) == 2
1416
+
1417
+ assert (2*f(x) + 3*f(x).diff(x)).coeff(f(x)) == 2
1418
+
1419
+ expr = z*(x + y)**2
1420
+ expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2
1421
+ assert expr.coeff(z) == (x + y)**2
1422
+ assert expr.coeff(x + y) == 0
1423
+ assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2
1424
+
1425
+ assert (x + y + 3*z).coeff(1) == x + y
1426
+ assert (-x + 2*y).coeff(-1) == x
1427
+ assert (x - 2*y).coeff(-1) == 2*y
1428
+ assert (3 + 2*x + 4*x**2).coeff(1) == 0
1429
+ assert (-x - 2*y).coeff(2) == -y
1430
+ assert (x + sqrt(2)*x).coeff(sqrt(2)) == x
1431
+ assert (3 + 2*x + 4*x**2).coeff(x) == 2
1432
+ assert (3 + 2*x + 4*x**2).coeff(x**2) == 4
1433
+ assert (3 + 2*x + 4*x**2).coeff(x**3) == 0
1434
+ assert (z*(x + y)**2).coeff((x + y)**2) == z
1435
+ assert (z*(x + y)**2).coeff(x + y) == 0
1436
+ assert (2 + 2*x + (x + 1)*y).coeff(x + 1) == y
1437
+
1438
+ assert (x + 2*y + 3).coeff(1) == x
1439
+ assert (x + 2*y + 3).coeff(x, 0) == 2*y + 3
1440
+ assert (x**2 + 2*y + 3*x).coeff(x**2, 0) == 2*y + 3*x
1441
+ assert x.coeff(0, 0) == 0
1442
+ assert x.coeff(x, 0) == 0
1443
+
1444
+ n, m, o, l = symbols('n m o l', commutative=False)
1445
+ assert n.coeff(n) == 1
1446
+ assert y.coeff(n) == 0
1447
+ assert (3*n).coeff(n) == 3
1448
+ assert (2 + n).coeff(x*m) == 0
1449
+ assert (2*x*n*m).coeff(x) == 2*n*m
1450
+ assert (2 + n).coeff(x*m*n + y) == 0
1451
+ assert (2*x*n*m).coeff(3*n) == 0
1452
+ assert (n*m + m*n*m).coeff(n) == 1 + m
1453
+ assert (n*m + m*n*m).coeff(n, right=True) == m # = (1 + m)*n*m
1454
+ assert (n*m + m*n).coeff(n) == 0
1455
+ assert (n*m + o*m*n).coeff(m*n) == o
1456
+ assert (n*m + o*m*n).coeff(m*n, right=True) == 1
1457
+ assert (n*m + n*m*n).coeff(n*m, right=True) == 1 + n # = n*m*(n + 1)
1458
+
1459
+ assert (x*y).coeff(z, 0) == x*y
1460
+
1461
+ assert (x*n + y*n + z*m).coeff(n) == x + y
1462
+ assert (n*m + n*o + o*l).coeff(n, right=True) == m + o
1463
+ assert (x*n*m*n + y*n*m*o + z*l).coeff(m, right=True) == x*n + y*o
1464
+ assert (x*n*m*n + x*n*m*o + z*l).coeff(m, right=True) == n + o
1465
+ assert (x*n*m*n + x*n*m*o + z*l).coeff(m) == x*n
1466
+
1467
+
1468
+ def test_coeff2():
1469
+ r, kappa = symbols('r, kappa')
1470
+ psi = Function("psi")
1471
+ g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
1472
+ g = g.expand()
1473
+ assert g.coeff(psi(r).diff(r)) == 2/r
1474
+
1475
+
1476
+ def test_coeff2_0():
1477
+ r, kappa = symbols('r, kappa')
1478
+ psi = Function("psi")
1479
+ g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
1480
+ g = g.expand()
1481
+
1482
+ assert g.coeff(psi(r).diff(r, 2)) == 1
1483
+
1484
+
1485
+ def test_coeff_expand():
1486
+ expr = z*(x + y)**2
1487
+ expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2
1488
+ assert expr.coeff(z) == (x + y)**2
1489
+ assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2
1490
+
1491
+
1492
+ def test_integrate():
1493
+ assert x.integrate(x) == x**2/2
1494
+ assert x.integrate((x, 0, 1)) == S.Half
1495
+
1496
+
1497
+ def test_as_base_exp():
1498
+ assert x.as_base_exp() == (x, S.One)
1499
+ assert (x*y*z).as_base_exp() == (x*y*z, S.One)
1500
+ assert (x + y + z).as_base_exp() == (x + y + z, S.One)
1501
+ assert ((x + y)**z).as_base_exp() == (x + y, z)
1502
+
1503
+
1504
+ def test_issue_4963():
1505
+ assert hasattr(Mul(x, y), "is_commutative")
1506
+ assert hasattr(Mul(x, y, evaluate=False), "is_commutative")
1507
+ assert hasattr(Pow(x, y), "is_commutative")
1508
+ assert hasattr(Pow(x, y, evaluate=False), "is_commutative")
1509
+ expr = Mul(Pow(2, 2, evaluate=False), 3, evaluate=False) + 1
1510
+ assert hasattr(expr, "is_commutative")
1511
+
1512
+
1513
+ def test_action_verbs():
1514
+ assert nsimplify(1/(exp(3*pi*x/5) + 1)) == \
1515
+ (1/(exp(3*pi*x/5) + 1)).nsimplify()
1516
+ assert ratsimp(1/x + 1/y) == (1/x + 1/y).ratsimp()
1517
+ assert trigsimp(log(x), deep=True) == (log(x)).trigsimp(deep=True)
1518
+ assert radsimp(1/(2 + sqrt(2))) == (1/(2 + sqrt(2))).radsimp()
1519
+ assert radsimp(1/(a + b*sqrt(c)), symbolic=False) == \
1520
+ (1/(a + b*sqrt(c))).radsimp(symbolic=False)
1521
+ assert powsimp(x**y*x**z*y**z, combine='all') == \
1522
+ (x**y*x**z*y**z).powsimp(combine='all')
1523
+ assert (x**t*y**t).powsimp(force=True) == (x*y)**t
1524
+ assert simplify(x**y*x**z*y**z) == (x**y*x**z*y**z).simplify()
1525
+ assert together(1/x + 1/y) == (1/x + 1/y).together()
1526
+ assert collect(a*x**2 + b*x**2 + a*x - b*x + c, x) == \
1527
+ (a*x**2 + b*x**2 + a*x - b*x + c).collect(x)
1528
+ assert apart(y/(y + 2)/(y + 1), y) == (y/(y + 2)/(y + 1)).apart(y)
1529
+ assert combsimp(y/(x + 2)/(x + 1)) == (y/(x + 2)/(x + 1)).combsimp()
1530
+ assert gammasimp(gamma(x)/gamma(x-5)) == (gamma(x)/gamma(x-5)).gammasimp()
1531
+ assert factor(x**2 + 5*x + 6) == (x**2 + 5*x + 6).factor()
1532
+ assert refine(sqrt(x**2)) == sqrt(x**2).refine()
1533
+ assert cancel((x**2 + 5*x + 6)/(x + 2)) == ((x**2 + 5*x + 6)/(x + 2)).cancel()
1534
+
1535
+
1536
+ def test_as_powers_dict():
1537
+ assert x.as_powers_dict() == {x: 1}
1538
+ assert (x**y*z).as_powers_dict() == {x: y, z: 1}
1539
+ assert Mul(2, 2, evaluate=False).as_powers_dict() == {S(2): S(2)}
1540
+ assert (x*y).as_powers_dict()[z] == 0
1541
+ assert (x + y).as_powers_dict()[z] == 0
1542
+
1543
+
1544
+ def test_as_coefficients_dict():
1545
+ check = [S.One, x, y, x*y, 1]
1546
+ assert [Add(3*x, 2*x, y, 3).as_coefficients_dict()[i] for i in check] == \
1547
+ [3, 5, 1, 0, 3]
1548
+ assert [Add(3*x, 2*x, y, 3, evaluate=False).as_coefficients_dict()[i]
1549
+ for i in check] == [3, 5, 1, 0, 3]
1550
+ assert [(3*x*y).as_coefficients_dict()[i] for i in check] == \
1551
+ [0, 0, 0, 3, 0]
1552
+ assert [(3.0*x*y).as_coefficients_dict()[i] for i in check] == \
1553
+ [0, 0, 0, 3.0, 0]
1554
+ assert (3.0*x*y).as_coefficients_dict()[3.0*x*y] == 0
1555
+ eq = x*(x + 1)*a + x*b + c/x
1556
+ assert eq.as_coefficients_dict(x) == {x: b, 1/x: c,
1557
+ x*(x + 1): a}
1558
+ assert eq.expand().as_coefficients_dict(x) == {x**2: a, x: a + b, 1/x: c}
1559
+ assert x.as_coefficients_dict() == {x: S.One}
1560
+
1561
+
1562
+ def test_args_cnc():
1563
+ A = symbols('A', commutative=False)
1564
+ assert (x + A).args_cnc() == \
1565
+ [[], [x + A]]
1566
+ assert (x + a).args_cnc() == \
1567
+ [[a + x], []]
1568
+ assert (x*a).args_cnc() == \
1569
+ [[a, x], []]
1570
+ assert (x*y*A*(A + 1)).args_cnc(cset=True) == \
1571
+ [{x, y}, [A, 1 + A]]
1572
+ assert Mul(x, x, evaluate=False).args_cnc(cset=True, warn=False) == \
1573
+ [{x}, []]
1574
+ assert Mul(x, x**2, evaluate=False).args_cnc(cset=True, warn=False) == \
1575
+ [{x, x**2}, []]
1576
+ raises(ValueError, lambda: Mul(x, x, evaluate=False).args_cnc(cset=True))
1577
+ assert Mul(x, y, x, evaluate=False).args_cnc() == \
1578
+ [[x, y, x], []]
1579
+ # always split -1 from leading number
1580
+ assert (-1.*x).args_cnc() == [[-1, 1.0, x], []]
1581
+
1582
+
1583
+ def test_new_rawargs():
1584
+ n = Symbol('n', commutative=False)
1585
+ a = x + n
1586
+ assert a.is_commutative is False
1587
+ assert a._new_rawargs(x).is_commutative
1588
+ assert a._new_rawargs(x, y).is_commutative
1589
+ assert a._new_rawargs(x, n).is_commutative is False
1590
+ assert a._new_rawargs(x, y, n).is_commutative is False
1591
+ m = x*n
1592
+ assert m.is_commutative is False
1593
+ assert m._new_rawargs(x).is_commutative
1594
+ assert m._new_rawargs(n).is_commutative is False
1595
+ assert m._new_rawargs(x, y).is_commutative
1596
+ assert m._new_rawargs(x, n).is_commutative is False
1597
+ assert m._new_rawargs(x, y, n).is_commutative is False
1598
+
1599
+ assert m._new_rawargs(x, n, reeval=False).is_commutative is False
1600
+ assert m._new_rawargs(S.One) is S.One
1601
+
1602
+
1603
+ def test_issue_5226():
1604
+ assert Add(evaluate=False) == 0
1605
+ assert Mul(evaluate=False) == 1
1606
+ assert Mul(x + y, evaluate=False).is_Add
1607
+
1608
+
1609
+ def test_free_symbols():
1610
+ # free_symbols should return the free symbols of an object
1611
+ assert S.One.free_symbols == set()
1612
+ assert x.free_symbols == {x}
1613
+ assert Integral(x, (x, 1, y)).free_symbols == {y}
1614
+ assert (-Integral(x, (x, 1, y))).free_symbols == {y}
1615
+ assert meter.free_symbols == set()
1616
+ assert (meter**x).free_symbols == {x}
1617
+
1618
+
1619
+ def test_has_free():
1620
+ assert x.has_free(x)
1621
+ assert not x.has_free(y)
1622
+ assert (x + y).has_free(x)
1623
+ assert (x + y).has_free(*(x, z))
1624
+ assert f(x).has_free(x)
1625
+ assert f(x).has_free(f(x))
1626
+ assert Integral(f(x), (f(x), 1, y)).has_free(y)
1627
+ assert not Integral(f(x), (f(x), 1, y)).has_free(x)
1628
+ assert not Integral(f(x), (f(x), 1, y)).has_free(f(x))
1629
+ # simple extraction
1630
+ assert (x + 1 + y).has_free(x + 1)
1631
+ assert not (x + 2 + y).has_free(x + 1)
1632
+ assert (2 + 3*x*y).has_free(3*x)
1633
+ raises(TypeError, lambda: x.has_free({x, y}))
1634
+ s = FiniteSet(1, 2)
1635
+ assert Piecewise((s, x > 3), (4, True)).has_free(s)
1636
+ assert not Piecewise((1, x > 3), (4, True)).has_free(s)
1637
+ # can't make set of these, but fallback will handle
1638
+ raises(TypeError, lambda: x.has_free(y, []))
1639
+
1640
+
1641
+ def test_has_xfree():
1642
+ assert (x + 1).has_xfree({x})
1643
+ assert ((x + 1)**2).has_xfree({x + 1})
1644
+ assert not (x + y + 1).has_xfree({x + 1})
1645
+ raises(TypeError, lambda: x.has_xfree(x))
1646
+ raises(TypeError, lambda: x.has_xfree([x]))
1647
+
1648
+
1649
+ def test_issue_5300():
1650
+ x = Symbol('x', commutative=False)
1651
+ assert x*sqrt(2)/sqrt(6) == x*sqrt(3)/3
1652
+
1653
+
1654
+ def test_floordiv():
1655
+ from sympy.functions.elementary.integers import floor
1656
+ assert x // y == floor(x / y)
1657
+
1658
+
1659
+ def test_as_coeff_Mul():
1660
+ assert Integer(3).as_coeff_Mul() == (Integer(3), Integer(1))
1661
+ assert Rational(3, 4).as_coeff_Mul() == (Rational(3, 4), Integer(1))
1662
+ assert Float(5.0).as_coeff_Mul() == (Float(5.0), Integer(1))
1663
+
1664
+ assert (Integer(3)*x).as_coeff_Mul() == (Integer(3), x)
1665
+ assert (Rational(3, 4)*x).as_coeff_Mul() == (Rational(3, 4), x)
1666
+ assert (Float(5.0)*x).as_coeff_Mul() == (Float(5.0), x)
1667
+
1668
+ assert (Integer(3)*x*y).as_coeff_Mul() == (Integer(3), x*y)
1669
+ assert (Rational(3, 4)*x*y).as_coeff_Mul() == (Rational(3, 4), x*y)
1670
+ assert (Float(5.0)*x*y).as_coeff_Mul() == (Float(5.0), x*y)
1671
+
1672
+ assert (x).as_coeff_Mul() == (S.One, x)
1673
+ assert (x*y).as_coeff_Mul() == (S.One, x*y)
1674
+ assert (-oo*x).as_coeff_Mul(rational=True) == (-1, oo*x)
1675
+
1676
+
1677
+ def test_as_coeff_Add():
1678
+ assert Integer(3).as_coeff_Add() == (Integer(3), Integer(0))
1679
+ assert Rational(3, 4).as_coeff_Add() == (Rational(3, 4), Integer(0))
1680
+ assert Float(5.0).as_coeff_Add() == (Float(5.0), Integer(0))
1681
+
1682
+ assert (Integer(3) + x).as_coeff_Add() == (Integer(3), x)
1683
+ assert (Rational(3, 4) + x).as_coeff_Add() == (Rational(3, 4), x)
1684
+ assert (Float(5.0) + x).as_coeff_Add() == (Float(5.0), x)
1685
+ assert (Float(5.0) + x).as_coeff_Add(rational=True) == (0, Float(5.0) + x)
1686
+
1687
+ assert (Integer(3) + x + y).as_coeff_Add() == (Integer(3), x + y)
1688
+ assert (Rational(3, 4) + x + y).as_coeff_Add() == (Rational(3, 4), x + y)
1689
+ assert (Float(5.0) + x + y).as_coeff_Add() == (Float(5.0), x + y)
1690
+
1691
+ assert (x).as_coeff_Add() == (S.Zero, x)
1692
+ assert (x*y).as_coeff_Add() == (S.Zero, x*y)
1693
+
1694
+
1695
+ def test_expr_sorting():
1696
+
1697
+ exprs = [1/x**2, 1/x, sqrt(sqrt(x)), sqrt(x), x, sqrt(x)**3, x**2]
1698
+ assert sorted(exprs, key=default_sort_key) == exprs
1699
+
1700
+ exprs = [x, 2*x, 2*x**2, 2*x**3, x**n, 2*x**n, sin(x), sin(x)**n,
1701
+ sin(x**2), cos(x), cos(x**2), tan(x)]
1702
+ assert sorted(exprs, key=default_sort_key) == exprs
1703
+
1704
+ exprs = [x + 1, x**2 + x + 1, x**3 + x**2 + x + 1]
1705
+ assert sorted(exprs, key=default_sort_key) == exprs
1706
+
1707
+ exprs = [S(4), x - 3*I/2, x + 3*I/2, x - 4*I + 1, x + 4*I + 1]
1708
+ assert sorted(exprs, key=default_sort_key) == exprs
1709
+
1710
+ exprs = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
1711
+ assert sorted(exprs, key=default_sort_key) == exprs
1712
+
1713
+ exprs = [f(x), g(x), exp(x), sin(x), cos(x), factorial(x)]
1714
+ assert sorted(exprs, key=default_sort_key) == exprs
1715
+
1716
+ exprs = [Tuple(x, y), Tuple(x, z), Tuple(x, y, z)]
1717
+ assert sorted(exprs, key=default_sort_key) == exprs
1718
+
1719
+ exprs = [[3], [1, 2]]
1720
+ assert sorted(exprs, key=default_sort_key) == exprs
1721
+
1722
+ exprs = [[1, 2], [2, 3]]
1723
+ assert sorted(exprs, key=default_sort_key) == exprs
1724
+
1725
+ exprs = [[1, 2], [1, 2, 3]]
1726
+ assert sorted(exprs, key=default_sort_key) == exprs
1727
+
1728
+ exprs = [{x: -y}, {x: y}]
1729
+ assert sorted(exprs, key=default_sort_key) == exprs
1730
+
1731
+ exprs = [{1}, {1, 2}]
1732
+ assert sorted(exprs, key=default_sort_key) == exprs
1733
+
1734
+ a, b = exprs = [Dummy('x'), Dummy('x')]
1735
+ assert sorted([b, a], key=default_sort_key) == exprs
1736
+
1737
+
1738
+ def test_as_ordered_factors():
1739
+
1740
+ assert x.as_ordered_factors() == [x]
1741
+ assert (2*x*x**n*sin(x)*cos(x)).as_ordered_factors() \
1742
+ == [Integer(2), x, x**n, sin(x), cos(x)]
1743
+
1744
+ args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
1745
+ expr = Mul(*args)
1746
+
1747
+ assert expr.as_ordered_factors() == args
1748
+
1749
+ A, B = symbols('A,B', commutative=False)
1750
+
1751
+ assert (A*B).as_ordered_factors() == [A, B]
1752
+ assert (B*A).as_ordered_factors() == [B, A]
1753
+
1754
+
1755
+ def test_as_ordered_terms():
1756
+
1757
+ assert x.as_ordered_terms() == [x]
1758
+ assert (sin(x)**2*cos(x) + sin(x)*cos(x)**2 + 1).as_ordered_terms() \
1759
+ == [sin(x)**2*cos(x), sin(x)*cos(x)**2, 1]
1760
+
1761
+ args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
1762
+ expr = Add(*args)
1763
+
1764
+ assert expr.as_ordered_terms() == args
1765
+
1766
+ assert (1 + 4*sqrt(3)*pi*x).as_ordered_terms() == [4*pi*x*sqrt(3), 1]
1767
+
1768
+ assert ( 2 + 3*I).as_ordered_terms() == [2, 3*I]
1769
+ assert (-2 + 3*I).as_ordered_terms() == [-2, 3*I]
1770
+ assert ( 2 - 3*I).as_ordered_terms() == [2, -3*I]
1771
+ assert (-2 - 3*I).as_ordered_terms() == [-2, -3*I]
1772
+
1773
+ assert ( 4 + 3*I).as_ordered_terms() == [4, 3*I]
1774
+ assert (-4 + 3*I).as_ordered_terms() == [-4, 3*I]
1775
+ assert ( 4 - 3*I).as_ordered_terms() == [4, -3*I]
1776
+ assert (-4 - 3*I).as_ordered_terms() == [-4, -3*I]
1777
+
1778
+ e = x**2*y**2 + x*y**4 + y + 2
1779
+
1780
+ assert e.as_ordered_terms(order="lex") == [x**2*y**2, x*y**4, y, 2]
1781
+ assert e.as_ordered_terms(order="grlex") == [x*y**4, x**2*y**2, y, 2]
1782
+ assert e.as_ordered_terms(order="rev-lex") == [2, y, x*y**4, x**2*y**2]
1783
+ assert e.as_ordered_terms(order="rev-grlex") == [2, y, x**2*y**2, x*y**4]
1784
+
1785
+ k = symbols('k')
1786
+ assert k.as_ordered_terms(data=True) == ([(k, ((1.0, 0.0), (1,), ()))], [k])
1787
+
1788
+
1789
+ def test_sort_key_atomic_expr():
1790
+ from sympy.physics.units import m, s
1791
+ assert sorted([-m, s], key=lambda arg: arg.sort_key()) == [-m, s]
1792
+
1793
+
1794
+ def test_eval_interval():
1795
+ assert exp(x)._eval_interval(*Tuple(x, 0, 1)) == exp(1) - exp(0)
1796
+
1797
+ # issue 4199
1798
+ a = x/y
1799
+ raises(NotImplementedError, lambda: a._eval_interval(x, S.Zero, oo)._eval_interval(y, oo, S.Zero))
1800
+ raises(NotImplementedError, lambda: a._eval_interval(x, S.Zero, oo)._eval_interval(y, S.Zero, oo))
1801
+ a = x - y
1802
+ raises(NotImplementedError, lambda: a._eval_interval(x, S.One, oo)._eval_interval(y, oo, S.One))
1803
+ raises(ValueError, lambda: x._eval_interval(x, None, None))
1804
+ a = -y*Heaviside(x - y)
1805
+ assert a._eval_interval(x, -oo, oo) == -y
1806
+ assert a._eval_interval(x, oo, -oo) == y
1807
+
1808
+
1809
+ def test_eval_interval_zoo():
1810
+ # Test that limit is used when zoo is returned
1811
+ assert Si(1/x)._eval_interval(x, S.Zero, S.One) == -pi/2 + Si(1)
1812
+
1813
+
1814
+ def test_primitive():
1815
+ assert (3*(x + 1)**2).primitive() == (3, (x + 1)**2)
1816
+ assert (6*x + 2).primitive() == (2, 3*x + 1)
1817
+ assert (x/2 + 3).primitive() == (S.Half, x + 6)
1818
+ eq = (6*x + 2)*(x/2 + 3)
1819
+ assert eq.primitive()[0] == 1
1820
+ eq = (2 + 2*x)**2
1821
+ assert eq.primitive()[0] == 1
1822
+ assert (4.0*x).primitive() == (1, 4.0*x)
1823
+ assert (4.0*x + y/2).primitive() == (S.Half, 8.0*x + y)
1824
+ assert (-2*x).primitive() == (2, -x)
1825
+ assert Add(5*z/7, 0.5*x, 3*y/2, evaluate=False).primitive() == \
1826
+ (S.One/14, 7.0*x + 21*y + 10*z)
1827
+ for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
1828
+ assert (i + x/3).primitive() == \
1829
+ (S.One/3, i + x)
1830
+ assert (S.Infinity + 2*x/3 + 4*y/7).primitive() == \
1831
+ (S.One/21, 14*x + 12*y + oo)
1832
+ assert S.Zero.primitive() == (S.One, S.Zero)
1833
+
1834
+
1835
+ def test_issue_5843():
1836
+ a = 1 + x
1837
+ assert (2*a).extract_multiplicatively(a) == 2
1838
+ assert (4*a).extract_multiplicatively(2*a) == 2
1839
+ assert ((3*a)*(2*a)).extract_multiplicatively(a) == 6*a
1840
+
1841
+
1842
+ def test_is_constant():
1843
+ from sympy.solvers.solvers import checksol
1844
+ assert Sum(x, (x, 1, 10)).is_constant() is True
1845
+ assert Sum(x, (x, 1, n)).is_constant() is False
1846
+ assert Sum(x, (x, 1, n)).is_constant(y) is True
1847
+ assert Sum(x, (x, 1, n)).is_constant(n) is False
1848
+ assert Sum(x, (x, 1, n)).is_constant(x) is True
1849
+ eq = a*cos(x)**2 + a*sin(x)**2 - a
1850
+ assert eq.is_constant() is True
1851
+ assert eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
1852
+ assert x.is_constant() is False
1853
+ assert x.is_constant(y) is True
1854
+ assert log(x/y).is_constant() is False
1855
+
1856
+ assert checksol(x, x, Sum(x, (x, 1, n))) is False
1857
+ assert checksol(x, x, Sum(x, (x, 1, n))) is False
1858
+ assert f(1).is_constant
1859
+ assert checksol(x, x, f(x)) is False
1860
+
1861
+ assert Pow(x, S.Zero, evaluate=False).is_constant() is True # == 1
1862
+ assert Pow(S.Zero, x, evaluate=False).is_constant() is False # == 0 or 1
1863
+ assert (2**x).is_constant() is False
1864
+ assert Pow(S(2), S(3), evaluate=False).is_constant() is True
1865
+
1866
+ z1, z2 = symbols('z1 z2', zero=True)
1867
+ assert (z1 + 2*z2).is_constant() is True
1868
+
1869
+ assert meter.is_constant() is True
1870
+ assert (3*meter).is_constant() is True
1871
+ assert (x*meter).is_constant() is False
1872
+
1873
+
1874
+ def test_equals():
1875
+ assert (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2).equals(0)
1876
+ assert (x**2 - 1).equals((x + 1)*(x - 1))
1877
+ assert (cos(x)**2 + sin(x)**2).equals(1)
1878
+ assert (a*cos(x)**2 + a*sin(x)**2).equals(a)
1879
+ r = sqrt(2)
1880
+ assert (-1/(r + r*x) + 1/r/(1 + x)).equals(0)
1881
+ assert factorial(x + 1).equals((x + 1)*factorial(x))
1882
+ assert sqrt(3).equals(2*sqrt(3)) is False
1883
+ assert (sqrt(5)*sqrt(3)).equals(sqrt(3)) is False
1884
+ assert (sqrt(5) + sqrt(3)).equals(0) is False
1885
+ assert (sqrt(5) + pi).equals(0) is False
1886
+ assert meter.equals(0) is False
1887
+ assert (3*meter**2).equals(0) is False
1888
+ eq = -(-1)**(S(3)/4)*6**(S.One/4) + (-6)**(S.One/4)*I
1889
+ if eq != 0: # if canonicalization makes this zero, skip the test
1890
+ assert eq.equals(0)
1891
+ assert sqrt(x).equals(0) is False
1892
+
1893
+ # from integrate(x*sqrt(1 + 2*x), x);
1894
+ # diff is zero only when assumptions allow
1895
+ i = 2*sqrt(2)*x**(S(5)/2)*(1 + 1/(2*x))**(S(5)/2)/5 + \
1896
+ 2*sqrt(2)*x**(S(3)/2)*(1 + 1/(2*x))**(S(5)/2)/(-6 - 3/x)
1897
+ ans = sqrt(2*x + 1)*(6*x**2 + x - 1)/15
1898
+ diff = i - ans
1899
+ assert diff.equals(0) is None # should be False, but previously this was False due to wrong intermediate result
1900
+ assert diff.subs(x, Rational(-1, 2)/2) == 7*sqrt(2)/120
1901
+ # there are regions for x for which the expression is True, for
1902
+ # example, when x < -1/2 or x > 0 the expression is zero
1903
+ p = Symbol('p', positive=True)
1904
+ assert diff.subs(x, p).equals(0) is True
1905
+ assert diff.subs(x, -1).equals(0) is True
1906
+
1907
+ # prove via minimal_polynomial or self-consistency
1908
+ eq = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3))
1909
+ assert eq.equals(0)
1910
+ q = 3**Rational(1, 3) + 3
1911
+ p = expand(q**3)**Rational(1, 3)
1912
+ assert (p - q).equals(0)
1913
+
1914
+ # issue 6829
1915
+ # eq = q*x + q/4 + x**4 + x**3 + 2*x**2 - S.One/3
1916
+ # z = eq.subs(x, solve(eq, x)[0])
1917
+ q = symbols('q')
1918
+ z = (q*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
1919
+ S(13)/12)/2 - sqrt((2*q - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
1920
+ S(2197)/13824)**(S.One/3) - S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 -
1921
+ S(2197)/13824)**(S.One/3) - S(13)/6)/2 - S.One/4) + q/4 + (-sqrt(-2*(-(q
1922
+ - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q
1923
+ - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
1924
+ S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
1925
+ S(13)/6)/2 - S.One/4)**4 + (-sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
1926
+ S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q -
1927
+ S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
1928
+ S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
1929
+ S(13)/6)/2 - S.One/4)**3 + 2*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
1930
+ S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q -
1931
+ S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
1932
+ S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
1933
+ S(13)/6)/2 - S.One/4)**2 - Rational(1, 3))
1934
+ assert z.equals(0)
1935
+
1936
+
1937
+ def test_random():
1938
+ from sympy.functions.combinatorial.numbers import lucas
1939
+ from sympy.simplify.simplify import posify
1940
+ assert posify(x)[0]._random() is not None
1941
+ assert lucas(n)._random(2, -2, 0, -1, 1) is None
1942
+
1943
+ # issue 8662
1944
+ assert Piecewise((Max(x, y), z))._random() is None
1945
+
1946
+
1947
+ def test_round():
1948
+ assert str(Float('0.1249999').round(2)) == '0.12'
1949
+ d20 = 12345678901234567890
1950
+ ans = S(d20).round(2)
1951
+ assert ans.is_Integer and ans == d20
1952
+ ans = S(d20).round(-2)
1953
+ assert ans.is_Integer and ans == 12345678901234567900
1954
+ assert str(S('1/7').round(4)) == '0.1429'
1955
+ assert str(S('.[12345]').round(4)) == '0.1235'
1956
+ assert str(S('.1349').round(2)) == '0.13'
1957
+ n = S(12345)
1958
+ ans = n.round()
1959
+ assert ans.is_Integer
1960
+ assert ans == n
1961
+ ans = n.round(1)
1962
+ assert ans.is_Integer
1963
+ assert ans == n
1964
+ ans = n.round(4)
1965
+ assert ans.is_Integer
1966
+ assert ans == n
1967
+ assert n.round(-1) == 12340
1968
+
1969
+ r = Float(str(n)).round(-4)
1970
+ assert r == 10000.0
1971
+
1972
+ assert n.round(-5) == 0
1973
+
1974
+ assert str((pi + sqrt(2)).round(2)) == '4.56'
1975
+ assert (10*(pi + sqrt(2))).round(-1) == 50.0
1976
+ raises(TypeError, lambda: round(x + 2, 2))
1977
+ assert str(S(2.3).round(1)) == '2.3'
1978
+ # rounding in SymPy (as in Decimal) should be
1979
+ # exact for the given precision; we check here
1980
+ # that when a 5 follows the last digit that
1981
+ # the rounded digit will be even.
1982
+ for i in range(-99, 100):
1983
+ # construct a decimal that ends in 5, e.g. 123 -> 0.1235
1984
+ s = str(abs(i))
1985
+ p = len(s) # we are going to round to the last digit of i
1986
+ n = '0.%s5' % s # put a 5 after i's digits
1987
+ j = p + 2 # 2 for '0.'
1988
+ if i < 0: # 1 for '-'
1989
+ j += 1
1990
+ n = '-' + n
1991
+ v = str(Float(n).round(p))[:j] # pertinent digits
1992
+ if v.endswith('.'):
1993
+ continue # it ends with 0 which is even
1994
+ L = int(v[-1]) # last digit
1995
+ assert L % 2 == 0, (n, '->', v)
1996
+
1997
+ assert (Float(.3, 3) + 2*pi).round() == 7
1998
+ assert (Float(.3, 3) + 2*pi*100).round() == 629
1999
+ assert (pi + 2*E*I).round() == 3 + 5*I
2000
+ # don't let request for extra precision give more than
2001
+ # what is known (in this case, only 3 digits)
2002
+ assert str((Float(.03, 3) + 2*pi/100).round(5)) == '0.0928'
2003
+ assert str((Float(.03, 3) + 2*pi/100).round(4)) == '0.0928'
2004
+
2005
+ assert S.Zero.round() == 0
2006
+
2007
+ a = (Add(1, Float('1.' + '9'*27, ''), evaluate=0))
2008
+ assert a.round(10) == Float('3.000000000000000000000000000', '')
2009
+ assert a.round(25) == Float('3.000000000000000000000000000', '')
2010
+ assert a.round(26) == Float('3.000000000000000000000000000', '')
2011
+ assert a.round(27) == Float('2.999999999999999999999999999', '')
2012
+ assert a.round(30) == Float('2.999999999999999999999999999', '')
2013
+
2014
+ # XXX: Should round set the precision of the result?
2015
+ # The previous version of the tests above is this but they only pass
2016
+ # because Floats with unequal precision compare equal:
2017
+ #
2018
+ # assert a.round(10) == Float('3.0000000000', '')
2019
+ # assert a.round(25) == Float('3.0000000000000000000000000', '')
2020
+ # assert a.round(26) == Float('3.00000000000000000000000000', '')
2021
+ # assert a.round(27) == Float('2.999999999999999999999999999', '')
2022
+ # assert a.round(30) == Float('2.999999999999999999999999999', '')
2023
+
2024
+ raises(TypeError, lambda: x.round())
2025
+ raises(TypeError, lambda: f(1).round())
2026
+
2027
+ # exact magnitude of 10
2028
+ assert str(S.One.round()) == '1'
2029
+ assert str(S(100).round()) == '100'
2030
+
2031
+ # applied to real and imaginary portions
2032
+ assert (2*pi + E*I).round() == 6 + 3*I
2033
+ assert (2*pi + I/10).round() == 6
2034
+ assert (pi/10 + 2*I).round() == 2*I
2035
+ # the lhs re and im parts are Float with dps of 2
2036
+ # and those on the right have dps of 15 so they won't compare
2037
+ # equal unless we use string or compare components (which will
2038
+ # then coerce the floats to the same precision) or re-create
2039
+ # the floats
2040
+ assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I'
2041
+ assert str((pi/10 + E*I).round(2).as_real_imag()) == '(0.31, 2.72)'
2042
+ assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I'
2043
+
2044
+ # issue 6914
2045
+ assert (I**(I + 3)).round(3) == Float('-0.208', '')*I
2046
+
2047
+ # issue 8720
2048
+ assert S(-123.6).round() == -124
2049
+ assert S(-1.5).round() == -2
2050
+ assert S(-100.5).round() == -100
2051
+ assert S(-1.5 - 10.5*I).round() == -2 - 10*I
2052
+
2053
+ # issue 7961
2054
+ assert str(S(0.006).round(2)) == '0.01'
2055
+ assert str(S(0.00106).round(4)) == '0.0011'
2056
+
2057
+ # issue 8147
2058
+ assert S.NaN.round() is S.NaN
2059
+ assert S.Infinity.round() is S.Infinity
2060
+ assert S.NegativeInfinity.round() is S.NegativeInfinity
2061
+ assert S.ComplexInfinity.round() is S.ComplexInfinity
2062
+
2063
+ # check that types match
2064
+ for i in range(2):
2065
+ fi = float(i)
2066
+ # 2 args
2067
+ assert all(type(round(i, p)) is int for p in (-1, 0, 1))
2068
+ assert all(S(i).round(p).is_Integer for p in (-1, 0, 1))
2069
+ assert all(type(round(fi, p)) is float for p in (-1, 0, 1))
2070
+ assert all(S(fi).round(p).is_Float for p in (-1, 0, 1))
2071
+ # 1 arg (p is None)
2072
+ assert type(round(i)) is int
2073
+ assert S(i).round().is_Integer
2074
+ assert type(round(fi)) is int
2075
+ assert S(fi).round().is_Integer
2076
+
2077
+
2078
+ def test_held_expression_UnevaluatedExpr():
2079
+ x = symbols("x")
2080
+ he = UnevaluatedExpr(1/x)
2081
+ e1 = x*he
2082
+
2083
+ assert isinstance(e1, Mul)
2084
+ assert e1.args == (x, he)
2085
+ assert e1.doit() == 1
2086
+ assert UnevaluatedExpr(Derivative(x, x)).doit(deep=False
2087
+ ) == Derivative(x, x)
2088
+ assert UnevaluatedExpr(Derivative(x, x)).doit() == 1
2089
+
2090
+ xx = Mul(x, x, evaluate=False)
2091
+ assert xx != x**2
2092
+
2093
+ ue2 = UnevaluatedExpr(xx)
2094
+ assert isinstance(ue2, UnevaluatedExpr)
2095
+ assert ue2.args == (xx,)
2096
+ assert ue2.doit() == x**2
2097
+ assert ue2.doit(deep=False) == xx
2098
+
2099
+ x2 = UnevaluatedExpr(2)*2
2100
+ assert type(x2) is Mul
2101
+ assert x2.args == (2, UnevaluatedExpr(2))
2102
+
2103
+ def test_round_exception_nostr():
2104
+ # Don't use the string form of the expression in the round exception, as
2105
+ # it's too slow
2106
+ s = Symbol('bad')
2107
+ try:
2108
+ s.round()
2109
+ except TypeError as e:
2110
+ assert 'bad' not in str(e)
2111
+ else:
2112
+ # Did not raise
2113
+ raise AssertionError("Did not raise")
2114
+
2115
+
2116
+ def test_extract_branch_factor():
2117
+ assert exp_polar(2.0*I*pi).extract_branch_factor() == (1, 1)
2118
+
2119
+
2120
+ def test_identity_removal():
2121
+ assert Add.make_args(x + 0) == (x,)
2122
+ assert Mul.make_args(x*1) == (x,)
2123
+
2124
+
2125
+ def test_float_0():
2126
+ assert Float(0.0) + 1 == Float(1.0)
2127
+
2128
+
2129
+ @XFAIL
2130
+ def test_float_0_fail():
2131
+ assert Float(0.0)*x == Float(0.0)
2132
+ assert (x + Float(0.0)).is_Add
2133
+
2134
+
2135
+ def test_issue_6325():
2136
+ ans = (b**2 + z**2 - (b*(a + b*t) + z*(c + t*z))**2/(
2137
+ (a + b*t)**2 + (c + t*z)**2))/sqrt((a + b*t)**2 + (c + t*z)**2)
2138
+ e = sqrt((a + b*t)**2 + (c + z*t)**2)
2139
+ assert diff(e, t, 2) == ans
2140
+ assert e.diff(t, 2) == ans
2141
+ assert diff(e, t, 2, simplify=False) != ans
2142
+
2143
+
2144
+ def test_issue_7426():
2145
+ f1 = a % c
2146
+ f2 = x % z
2147
+ assert f1.equals(f2) is None
2148
+
2149
+
2150
+ def test_issue_11122():
2151
+ x = Symbol('x', extended_positive=False)
2152
+ assert unchanged(Gt, x, 0) # (x > 0)
2153
+ # (x > 0) should remain unevaluated after PR #16956
2154
+
2155
+ x = Symbol('x', positive=False, real=True)
2156
+ assert (x > 0) is S.false
2157
+
2158
+
2159
+ def test_issue_10651():
2160
+ x = Symbol('x', real=True)
2161
+ e1 = (-1 + x)/(1 - x)
2162
+ e3 = (4*x**2 - 4)/((1 - x)*(1 + x))
2163
+ e4 = 1/(cos(x)**2) - (tan(x))**2
2164
+ x = Symbol('x', positive=True)
2165
+ e5 = (1 + x)/x
2166
+ assert e1.is_constant() is None
2167
+ assert e3.is_constant() is None
2168
+ assert e4.is_constant() is None
2169
+ assert e5.is_constant() is False
2170
+
2171
+
2172
+ def test_issue_10161():
2173
+ x = symbols('x', real=True)
2174
+ assert x*abs(x)*abs(x) == x**3
2175
+
2176
+
2177
+ def test_issue_10755():
2178
+ x = symbols('x')
2179
+ raises(TypeError, lambda: int(log(x)))
2180
+ raises(TypeError, lambda: log(x).round(2))
2181
+
2182
+
2183
+ def test_issue_11877():
2184
+ x = symbols('x')
2185
+ assert integrate(log(S.Half - x), (x, 0, S.Half)) == Rational(-1, 2) -log(2)/2
2186
+
2187
+
2188
+ def test_normal():
2189
+ x = symbols('x')
2190
+ e = Mul(S.Half, 1 + x, evaluate=False)
2191
+ assert e.normal() == e
2192
+
2193
+
2194
+ def test_expr():
2195
+ x = symbols('x')
2196
+ raises(TypeError, lambda: tan(x).series(x, 2, oo, "+"))
2197
+
2198
+
2199
+ def test_ExprBuilder():
2200
+ eb = ExprBuilder(Mul)
2201
+ eb.args.extend([x, x])
2202
+ assert eb.build() == x**2
2203
+
2204
+
2205
+ def test_issue_22020():
2206
+ from sympy.parsing.sympy_parser import parse_expr
2207
+ x = parse_expr("log((2*V/3-V)/C)/-(R+r)*C")
2208
+ y = parse_expr("log((2*V/3-V)/C)/-(R+r)*2")
2209
+ assert x.equals(y) is False
2210
+
2211
+
2212
+ def test_non_string_equality():
2213
+ # Expressions should not compare equal to strings
2214
+ x = symbols('x')
2215
+ one = sympify(1)
2216
+ assert (x == 'x') is False
2217
+ assert (x != 'x') is True
2218
+ assert (one == '1') is False
2219
+ assert (one != '1') is True
2220
+ assert (x + 1 == 'x + 1') is False
2221
+ assert (x + 1 != 'x + 1') is True
2222
+
2223
+ # Make sure == doesn't try to convert the resulting expression to a string
2224
+ # (e.g., by calling sympify() instead of _sympify())
2225
+
2226
+ class BadRepr:
2227
+ def __repr__(self):
2228
+ raise RuntimeError
2229
+
2230
+ assert (x == BadRepr()) is False
2231
+ assert (x != BadRepr()) is True
2232
+
2233
+
2234
+ def test_21494():
2235
+ from sympy.testing.pytest import warns_deprecated_sympy
2236
+
2237
+ with warns_deprecated_sympy():
2238
+ assert x.expr_free_symbols == {x}
2239
+
2240
+ with warns_deprecated_sympy():
2241
+ assert Basic().expr_free_symbols == set()
2242
+
2243
+ with warns_deprecated_sympy():
2244
+ assert S(2).expr_free_symbols == {S(2)}
2245
+
2246
+ with warns_deprecated_sympy():
2247
+ assert Indexed("A", x).expr_free_symbols == {Indexed("A", x)}
2248
+
2249
+ with warns_deprecated_sympy():
2250
+ assert Subs(x, x, 0).expr_free_symbols == set()
2251
+
2252
+
2253
+ def test_Expr__eq__iterable_handling():
2254
+ assert x != range(3)
2255
+
2256
+
2257
+ def test_format():
2258
+ assert '{:1.2f}'.format(S.Zero) == '0.00'
2259
+ assert '{:+3.0f}'.format(S(3)) == ' +3'
2260
+ assert '{:23.20f}'.format(pi) == ' 3.14159265358979323846'
2261
+ assert '{:50.48f}'.format(exp(sin(1))) == '2.319776824715853173956590377503266813254904772376'
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_exprtools.py ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for tools for manipulating of large commutative expressions. """
2
+
3
+ from sympy.concrete.summations import Sum
4
+ from sympy.core.add import Add
5
+ from sympy.core.basic import Basic
6
+ from sympy.core.containers import (Dict, Tuple)
7
+ from sympy.core.function import Function
8
+ from sympy.core.mul import Mul
9
+ from sympy.core.numbers import (I, Rational, oo)
10
+ from sympy.core.singleton import S
11
+ from sympy.core.symbol import (Dummy, Symbol, symbols)
12
+ from sympy.functions.elementary.exponential import (exp, log)
13
+ from sympy.functions.elementary.miscellaneous import (root, sqrt)
14
+ from sympy.functions.elementary.trigonometric import (cos, sin)
15
+ from sympy.integrals.integrals import Integral
16
+ from sympy.series.order import O
17
+ from sympy.sets.sets import Interval
18
+ from sympy.simplify.radsimp import collect
19
+ from sympy.simplify.simplify import simplify
20
+ from sympy.core.exprtools import (decompose_power, Factors, Term, _gcd_terms,
21
+ gcd_terms, factor_terms, factor_nc, _mask_nc,
22
+ _monotonic_sign)
23
+ from sympy.core.mul import _keep_coeff as _keep_coeff
24
+ from sympy.simplify.cse_opts import sub_pre
25
+ from sympy.testing.pytest import raises
26
+
27
+ from sympy.abc import a, b, t, x, y, z
28
+
29
+
30
+ def test_decompose_power():
31
+ assert decompose_power(x) == (x, 1)
32
+ assert decompose_power(x**2) == (x, 2)
33
+ assert decompose_power(x**(2*y)) == (x**y, 2)
34
+ assert decompose_power(x**(2*y/3)) == (x**(y/3), 2)
35
+ assert decompose_power(x**(y*Rational(2, 3))) == (x**(y/3), 2)
36
+
37
+
38
+ def test_Factors():
39
+ assert Factors() == Factors({}) == Factors(S.One)
40
+ assert Factors().as_expr() is S.One
41
+ assert Factors({x: 2, y: 3, sin(x): 4}).as_expr() == x**2*y**3*sin(x)**4
42
+ assert Factors(S.Infinity) == Factors({oo: 1})
43
+ assert Factors(S.NegativeInfinity) == Factors({oo: 1, -1: 1})
44
+ # issue #18059:
45
+ assert Factors((x**2)**S.Half).as_expr() == (x**2)**S.Half
46
+
47
+ a = Factors({x: 5, y: 3, z: 7})
48
+ b = Factors({ y: 4, z: 3, t: 10})
49
+
50
+ assert a.mul(b) == a*b == Factors({x: 5, y: 7, z: 10, t: 10})
51
+
52
+ assert a.div(b) == divmod(a, b) == \
53
+ (Factors({x: 5, z: 4}), Factors({y: 1, t: 10}))
54
+ assert a.quo(b) == a/b == Factors({x: 5, z: 4})
55
+ assert a.rem(b) == a % b == Factors({y: 1, t: 10})
56
+
57
+ assert a.pow(3) == a**3 == Factors({x: 15, y: 9, z: 21})
58
+ assert b.pow(3) == b**3 == Factors({y: 12, z: 9, t: 30})
59
+
60
+ assert a.gcd(b) == Factors({y: 3, z: 3})
61
+ assert a.lcm(b) == Factors({x: 5, y: 4, z: 7, t: 10})
62
+
63
+ a = Factors({x: 4, y: 7, t: 7})
64
+ b = Factors({z: 1, t: 3})
65
+
66
+ assert a.normal(b) == (Factors({x: 4, y: 7, t: 4}), Factors({z: 1}))
67
+
68
+ assert Factors(sqrt(2)*x).as_expr() == sqrt(2)*x
69
+
70
+ assert Factors(-I)*I == Factors()
71
+ assert Factors({S.NegativeOne: S(3)})*Factors({S.NegativeOne: S.One, I: S(5)}) == \
72
+ Factors(I)
73
+ assert Factors(sqrt(I)*I) == Factors(I**(S(3)/2)) == Factors({I: S(3)/2})
74
+ assert Factors({I: S(3)/2}).as_expr() == I**(S(3)/2)
75
+
76
+ assert Factors(S(2)**x).div(S(3)**x) == \
77
+ (Factors({S(2): x}), Factors({S(3): x}))
78
+ assert Factors(2**(2*x + 2)).div(S(8)) == \
79
+ (Factors({S(2): 2*x + 2}), Factors({S(8): S.One}))
80
+
81
+ # coverage
82
+ # /!\ things break if this is not True
83
+ assert Factors({S.NegativeOne: Rational(3, 2)}) == Factors({I: S.One, S.NegativeOne: S.One})
84
+ assert Factors({I: S.One, S.NegativeOne: Rational(1, 3)}).as_expr() == I*(-1)**Rational(1, 3)
85
+
86
+ assert Factors(-1.) == Factors({S.NegativeOne: S.One, S(1.): 1})
87
+ assert Factors(-2.) == Factors({S.NegativeOne: S.One, S(2.): 1})
88
+ assert Factors((-2.)**x) == Factors({S(-2.): x})
89
+ assert Factors(S(-2)) == Factors({S.NegativeOne: S.One, S(2): 1})
90
+ assert Factors(S.Half) == Factors({S(2): -S.One})
91
+ assert Factors(Rational(3, 2)) == Factors({S(3): S.One, S(2): S.NegativeOne})
92
+ assert Factors({I: S.One}) == Factors(I)
93
+ assert Factors({-1.0: 2, I: 1}) == Factors({S(1.0): 1, I: 1})
94
+ assert Factors({S.NegativeOne: Rational(-3, 2)}).as_expr() == I
95
+ A = symbols('A', commutative=False)
96
+ assert Factors(2*A**2) == Factors({S(2): 1, A**2: 1})
97
+ assert Factors(I) == Factors({I: S.One})
98
+ assert Factors(x).normal(S(2)) == (Factors(x), Factors(S(2)))
99
+ assert Factors(x).normal(S.Zero) == (Factors(), Factors(S.Zero))
100
+ raises(ZeroDivisionError, lambda: Factors(x).div(S.Zero))
101
+ assert Factors(x).mul(S(2)) == Factors(2*x)
102
+ assert Factors(x).mul(S.Zero).is_zero
103
+ assert Factors(x).mul(1/x).is_one
104
+ assert Factors(x**sqrt(2)**3).as_expr() == x**(2*sqrt(2))
105
+ assert Factors(x)**Factors(S(2)) == Factors(x**2)
106
+ assert Factors(x).gcd(S.Zero) == Factors(x)
107
+ assert Factors(x).lcm(S.Zero).is_zero
108
+ assert Factors(S.Zero).div(x) == (Factors(S.Zero), Factors())
109
+ assert Factors(x).div(x) == (Factors(), Factors())
110
+ assert Factors({x: .2})/Factors({x: .2}) == Factors()
111
+ assert Factors(x) != Factors()
112
+ assert Factors(S.Zero).normal(x) == (Factors(S.Zero), Factors())
113
+ n, d = x**(2 + y), x**2
114
+ f = Factors(n)
115
+ assert f.div(d) == f.normal(d) == (Factors(x**y), Factors())
116
+ assert f.gcd(d) == Factors()
117
+ d = x**y
118
+ assert f.div(d) == f.normal(d) == (Factors(x**2), Factors())
119
+ assert f.gcd(d) == Factors(d)
120
+ n = d = 2**x
121
+ f = Factors(n)
122
+ assert f.div(d) == f.normal(d) == (Factors(), Factors())
123
+ assert f.gcd(d) == Factors(d)
124
+ n, d = 2**x, 2**y
125
+ f = Factors(n)
126
+ assert f.div(d) == f.normal(d) == (Factors({S(2): x}), Factors({S(2): y}))
127
+ assert f.gcd(d) == Factors()
128
+
129
+ # extraction of constant only
130
+ n = x**(x + 3)
131
+ assert Factors(n).normal(x**-3) == (Factors({x: x + 6}), Factors({}))
132
+ assert Factors(n).normal(x**3) == (Factors({x: x}), Factors({}))
133
+ assert Factors(n).normal(x**4) == (Factors({x: x}), Factors({x: 1}))
134
+ assert Factors(n).normal(x**(y - 3)) == \
135
+ (Factors({x: x + 6}), Factors({x: y}))
136
+ assert Factors(n).normal(x**(y + 3)) == (Factors({x: x}), Factors({x: y}))
137
+ assert Factors(n).normal(x**(y + 4)) == \
138
+ (Factors({x: x}), Factors({x: y + 1}))
139
+
140
+ assert Factors(n).div(x**-3) == (Factors({x: x + 6}), Factors({}))
141
+ assert Factors(n).div(x**3) == (Factors({x: x}), Factors({}))
142
+ assert Factors(n).div(x**4) == (Factors({x: x}), Factors({x: 1}))
143
+ assert Factors(n).div(x**(y - 3)) == \
144
+ (Factors({x: x + 6}), Factors({x: y}))
145
+ assert Factors(n).div(x**(y + 3)) == (Factors({x: x}), Factors({x: y}))
146
+ assert Factors(n).div(x**(y + 4)) == \
147
+ (Factors({x: x}), Factors({x: y + 1}))
148
+
149
+ assert Factors(3 * x / 2) == Factors({3: 1, 2: -1, x: 1})
150
+ assert Factors(x * x / y) == Factors({x: 2, y: -1})
151
+ assert Factors(27 * x / y**9) == Factors({27: 1, x: 1, y: -9})
152
+
153
+
154
+ def test_Term():
155
+ a = Term(4*x*y**2/z/t**3)
156
+ b = Term(2*x**3*y**5/t**3)
157
+
158
+ assert a == Term(4, Factors({x: 1, y: 2}), Factors({z: 1, t: 3}))
159
+ assert b == Term(2, Factors({x: 3, y: 5}), Factors({t: 3}))
160
+
161
+ assert a.as_expr() == 4*x*y**2/z/t**3
162
+ assert b.as_expr() == 2*x**3*y**5/t**3
163
+
164
+ assert a.inv() == \
165
+ Term(S.One/4, Factors({z: 1, t: 3}), Factors({x: 1, y: 2}))
166
+ assert b.inv() == Term(S.Half, Factors({t: 3}), Factors({x: 3, y: 5}))
167
+
168
+ assert a.mul(b) == a*b == \
169
+ Term(8, Factors({x: 4, y: 7}), Factors({z: 1, t: 6}))
170
+ assert a.quo(b) == a/b == Term(2, Factors({}), Factors({x: 2, y: 3, z: 1}))
171
+
172
+ assert a.pow(3) == a**3 == \
173
+ Term(64, Factors({x: 3, y: 6}), Factors({z: 3, t: 9}))
174
+ assert b.pow(3) == b**3 == Term(8, Factors({x: 9, y: 15}), Factors({t: 9}))
175
+
176
+ assert a.pow(-3) == a**(-3) == \
177
+ Term(S.One/64, Factors({z: 3, t: 9}), Factors({x: 3, y: 6}))
178
+ assert b.pow(-3) == b**(-3) == \
179
+ Term(S.One/8, Factors({t: 9}), Factors({x: 9, y: 15}))
180
+
181
+ assert a.gcd(b) == Term(2, Factors({x: 1, y: 2}), Factors({t: 3}))
182
+ assert a.lcm(b) == Term(4, Factors({x: 3, y: 5}), Factors({z: 1, t: 3}))
183
+
184
+ a = Term(4*x*y**2/z/t**3)
185
+ b = Term(2*x**3*y**5*t**7)
186
+
187
+ assert a.mul(b) == Term(8, Factors({x: 4, y: 7, t: 4}), Factors({z: 1}))
188
+
189
+ assert Term((2*x + 2)**3) == Term(8, Factors({x + 1: 3}), Factors({}))
190
+ assert Term((2*x + 2)*(3*x + 6)**2) == \
191
+ Term(18, Factors({x + 1: 1, x + 2: 2}), Factors({}))
192
+
193
+
194
+ def test_gcd_terms():
195
+ f = 2*(x + 1)*(x + 4)/(5*x**2 + 5) + (2*x + 2)*(x + 5)/(x**2 + 1)/5 + \
196
+ (2*x + 2)*(x + 6)/(5*x**2 + 5)
197
+
198
+ assert _gcd_terms(f) == ((Rational(6, 5))*((1 + x)/(1 + x**2)), 5 + x, 1)
199
+ assert _gcd_terms(Add.make_args(f)) == \
200
+ ((Rational(6, 5))*((1 + x)/(1 + x**2)), 5 + x, 1)
201
+
202
+ newf = (Rational(6, 5))*((1 + x)*(5 + x)/(1 + x**2))
203
+ assert gcd_terms(f) == newf
204
+ args = Add.make_args(f)
205
+ # non-Basic sequences of terms treated as terms of Add
206
+ assert gcd_terms(list(args)) == newf
207
+ assert gcd_terms(tuple(args)) == newf
208
+ assert gcd_terms(set(args)) == newf
209
+ # but a Basic sequence is treated as a container
210
+ assert gcd_terms(Tuple(*args)) != newf
211
+ assert gcd_terms(Basic(Tuple(S(1), 3*y + 3*x*y), Tuple(S(1), S(3)))) == \
212
+ Basic(Tuple(S(1), 3*y*(x + 1)), Tuple(S(1), S(3)))
213
+ # but we shouldn't change keys of a dictionary or some may be lost
214
+ assert gcd_terms(Dict((x*(1 + y), S(2)), (x + x*y, y + x*y))) == \
215
+ Dict({x*(y + 1): S(2), x + x*y: y*(1 + x)})
216
+
217
+ assert gcd_terms((2*x + 2)**3 + (2*x + 2)**2) == 4*(x + 1)**2*(2*x + 3)
218
+
219
+ assert gcd_terms(0) == 0
220
+ assert gcd_terms(1) == 1
221
+ assert gcd_terms(x) == x
222
+ assert gcd_terms(2 + 2*x) == Mul(2, 1 + x, evaluate=False)
223
+ arg = x*(2*x + 4*y)
224
+ garg = 2*x*(x + 2*y)
225
+ assert gcd_terms(arg) == garg
226
+ assert gcd_terms(sin(arg)) == sin(garg)
227
+
228
+ # issue 6139-like
229
+ alpha, alpha1, alpha2, alpha3 = symbols('alpha:4')
230
+ a = alpha**2 - alpha*x**2 + alpha + x**3 - x*(alpha + 1)
231
+ rep = (alpha, (1 + sqrt(5))/2 + alpha1*x + alpha2*x**2 + alpha3*x**3)
232
+ s = (a/(x - alpha)).subs(*rep).series(x, 0, 1)
233
+ assert simplify(collect(s, x)) == -sqrt(5)/2 - Rational(3, 2) + O(x)
234
+
235
+ # issue 5917
236
+ assert _gcd_terms([S.Zero, S.Zero]) == (0, 0, 1)
237
+ assert _gcd_terms([2*x + 4]) == (2, x + 2, 1)
238
+
239
+ eq = x/(x + 1/x)
240
+ assert gcd_terms(eq, fraction=False) == eq
241
+ eq = x/2/y + 1/x/y
242
+ assert gcd_terms(eq, fraction=True, clear=True) == \
243
+ (x**2 + 2)/(2*x*y)
244
+ assert gcd_terms(eq, fraction=True, clear=False) == \
245
+ (x**2/2 + 1)/(x*y)
246
+ assert gcd_terms(eq, fraction=False, clear=True) == \
247
+ (x + 2/x)/(2*y)
248
+ assert gcd_terms(eq, fraction=False, clear=False) == \
249
+ (x/2 + 1/x)/y
250
+
251
+
252
+ def test_factor_terms():
253
+ A = Symbol('A', commutative=False)
254
+ assert factor_terms(9*(x + x*y + 1) + (3*x + 3)**(2 + 2*x)) == \
255
+ 9*x*y + 9*x + _keep_coeff(S(3), x + 1)**_keep_coeff(S(2), x + 1) + 9
256
+ assert factor_terms(9*(x + x*y + 1) + (3)**(2 + 2*x)) == \
257
+ _keep_coeff(S(9), 3**(2*x) + x*y + x + 1)
258
+ assert factor_terms(3**(2 + 2*x) + a*3**(2 + 2*x)) == \
259
+ 9*3**(2*x)*(a + 1)
260
+ assert factor_terms(x + x*A) == \
261
+ x*(1 + A)
262
+ assert factor_terms(sin(x + x*A)) == \
263
+ sin(x*(1 + A))
264
+ assert factor_terms((3*x + 3)**((2 + 2*x)/3)) == \
265
+ _keep_coeff(S(3), x + 1)**_keep_coeff(Rational(2, 3), x + 1)
266
+ assert factor_terms(x + (x*y + x)**(3*x + 3)) == \
267
+ x + (x*(y + 1))**_keep_coeff(S(3), x + 1)
268
+ assert factor_terms(a*(x + x*y) + b*(x*2 + y*x*2)) == \
269
+ x*(a + 2*b)*(y + 1)
270
+ i = Integral(x, (x, 0, oo))
271
+ assert factor_terms(i) == i
272
+
273
+ assert factor_terms(x/2 + y) == x/2 + y
274
+ # fraction doesn't apply to integer denominators
275
+ assert factor_terms(x/2 + y, fraction=True) == x/2 + y
276
+ # clear *does* apply to the integer denominators
277
+ assert factor_terms(x/2 + y, clear=True) == Mul(S.Half, x + 2*y, evaluate=False)
278
+
279
+ # check radical extraction
280
+ eq = sqrt(2) + sqrt(10)
281
+ assert factor_terms(eq) == eq
282
+ assert factor_terms(eq, radical=True) == sqrt(2)*(1 + sqrt(5))
283
+ eq = root(-6, 3) + root(6, 3)
284
+ assert factor_terms(eq, radical=True) == 6**(S.One/3)*(1 + (-1)**(S.One/3))
285
+
286
+ eq = [x + x*y]
287
+ ans = [x*(y + 1)]
288
+ for c in [list, tuple, set]:
289
+ assert factor_terms(c(eq)) == c(ans)
290
+ assert factor_terms(Tuple(x + x*y)) == Tuple(x*(y + 1))
291
+ assert factor_terms(Interval(0, 1)) == Interval(0, 1)
292
+ e = 1/sqrt(a/2 + 1)
293
+ assert factor_terms(e, clear=False) == 1/sqrt(a/2 + 1)
294
+ assert factor_terms(e, clear=True) == sqrt(2)/sqrt(a + 2)
295
+
296
+ eq = x/(x + 1/x) + 1/(x**2 + 1)
297
+ assert factor_terms(eq, fraction=False) == eq
298
+ assert factor_terms(eq, fraction=True) == 1
299
+
300
+ assert factor_terms((1/(x**3 + x**2) + 2/x**2)*y) == \
301
+ y*(2 + 1/(x + 1))/x**2
302
+
303
+ # if not True, then processesing for this in factor_terms is not necessary
304
+ assert gcd_terms(-x - y) == -x - y
305
+ assert factor_terms(-x - y) == Mul(-1, x + y, evaluate=False)
306
+
307
+ # if not True, then "special" processesing in factor_terms is not necessary
308
+ assert gcd_terms(exp(Mul(-1, x + 1))) == exp(-x - 1)
309
+ e = exp(-x - 2) + x
310
+ assert factor_terms(e) == exp(Mul(-1, x + 2, evaluate=False)) + x
311
+ assert factor_terms(e, sign=False) == e
312
+ assert factor_terms(exp(-4*x - 2) - x) == -x + exp(Mul(-2, 2*x + 1, evaluate=False))
313
+
314
+ # sum/integral tests
315
+ for F in (Sum, Integral):
316
+ assert factor_terms(F(x, (y, 1, 10))) == x * F(1, (y, 1, 10))
317
+ assert factor_terms(F(x, (y, 1, 10)) + x) == x * (1 + F(1, (y, 1, 10)))
318
+ assert factor_terms(F(x*y + x*y**2, (y, 1, 10))) == x*F(y*(y + 1), (y, 1, 10))
319
+
320
+ # expressions involving Pow terms with base 0
321
+ assert factor_terms(0**(x - 2) - 1) == 0**(x - 2) - 1
322
+ assert factor_terms(0**(x + 2) - 1) == 0**(x + 2) - 1
323
+ assert factor_terms((0**(x + 2) - 1).subs(x,-2)) == 0
324
+
325
+
326
+ def test_xreplace():
327
+ e = Mul(2, 1 + x, evaluate=False)
328
+ assert e.xreplace({}) == e
329
+ assert e.xreplace({y: x}) == e
330
+
331
+
332
+ def test_factor_nc():
333
+ x, y = symbols('x,y')
334
+ k = symbols('k', integer=True)
335
+ n, m, o = symbols('n,m,o', commutative=False)
336
+
337
+ # mul and multinomial expansion is needed
338
+ from sympy.core.function import _mexpand
339
+ e = x*(1 + y)**2
340
+ assert _mexpand(e) == x + x*2*y + x*y**2
341
+
342
+ def factor_nc_test(e):
343
+ ex = _mexpand(e)
344
+ assert ex.is_Add
345
+ f = factor_nc(ex)
346
+ assert not f.is_Add and _mexpand(f) == ex
347
+
348
+ factor_nc_test(x*(1 + y))
349
+ factor_nc_test(n*(x + 1))
350
+ factor_nc_test(n*(x + m))
351
+ factor_nc_test((x + m)*n)
352
+ factor_nc_test(n*m*(x*o + n*o*m)*n)
353
+ s = Sum(x, (x, 1, 2))
354
+ factor_nc_test(x*(1 + s))
355
+ factor_nc_test(x*(1 + s)*s)
356
+ factor_nc_test(x*(1 + sin(s)))
357
+ factor_nc_test((1 + n)**2)
358
+
359
+ factor_nc_test((x + n)*(x + m)*(x + y))
360
+ factor_nc_test(x*(n*m + 1))
361
+ factor_nc_test(x*(n*m + x))
362
+ factor_nc_test(x*(x*n*m + 1))
363
+ factor_nc_test(n*(m/x + o))
364
+ factor_nc_test(m*(n + o/2))
365
+ factor_nc_test(x*n*(x*m + 1))
366
+ factor_nc_test(x*(m*n + x*n*m))
367
+ factor_nc_test(n*(1 - m)*n**2)
368
+
369
+ factor_nc_test((n + m)**2)
370
+ factor_nc_test((n - m)*(n + m)**2)
371
+ factor_nc_test((n + m)**2*(n - m))
372
+ factor_nc_test((m - n)*(n + m)**2*(n - m))
373
+
374
+ assert factor_nc(n*(n + n*m)) == n**2*(1 + m)
375
+ assert factor_nc(m*(m*n + n*m*n**2)) == m*(m + n*m*n)*n
376
+ eq = m*sin(n) - sin(n)*m
377
+ assert factor_nc(eq) == eq
378
+
379
+ # for coverage:
380
+ from sympy.physics.secondquant import Commutator
381
+ from sympy.polys.polytools import factor
382
+ eq = 1 + x*Commutator(m, n)
383
+ assert factor_nc(eq) == eq
384
+ eq = x*Commutator(m, n) + x*Commutator(m, o)*Commutator(m, n)
385
+ assert factor(eq) == x*(1 + Commutator(m, o))*Commutator(m, n)
386
+
387
+ # issue 6534
388
+ assert (2*n + 2*m).factor() == 2*(n + m)
389
+
390
+ # issue 6701
391
+ _n = symbols('nz', zero=False, commutative=False)
392
+ assert factor_nc(_n**k + _n**(k + 1)) == _n**k*(1 + _n)
393
+ assert factor_nc((m*n)**k + (m*n)**(k + 1)) == (1 + m*n)*(m*n)**k
394
+
395
+ # issue 6918
396
+ assert factor_nc(-n*(2*x**2 + 2*x)) == -2*n*x*(x + 1)
397
+
398
+
399
+ def test_issue_6360():
400
+ a, b = symbols("a b")
401
+ apb = a + b
402
+ eq = apb + apb**2*(-2*a - 2*b)
403
+ assert factor_terms(sub_pre(eq)) == a + b - 2*(a + b)**3
404
+
405
+
406
+ def test_issue_7903():
407
+ a = symbols(r'a', real=True)
408
+ t = exp(I*cos(a)) + exp(-I*sin(a))
409
+ assert t.simplify()
410
+
411
+ def test_issue_8263():
412
+ F, G = symbols('F, G', commutative=False, cls=Function)
413
+ x, y = symbols('x, y')
414
+ expr, dummies, _ = _mask_nc(F(x)*G(y) - G(y)*F(x))
415
+ for v in dummies.values():
416
+ assert not v.is_commutative
417
+ assert not expr.is_zero
418
+
419
+ def test_monotonic_sign():
420
+ F = _monotonic_sign
421
+ x = symbols('x')
422
+ assert F(x) is None
423
+ assert F(-x) is None
424
+ assert F(Dummy(prime=True)) == 2
425
+ assert F(Dummy(prime=True, odd=True)) == 3
426
+ assert F(Dummy(composite=True)) == 4
427
+ assert F(Dummy(composite=True, odd=True)) == 9
428
+ assert F(Dummy(positive=True, integer=True)) == 1
429
+ assert F(Dummy(positive=True, even=True)) == 2
430
+ assert F(Dummy(positive=True, even=True, prime=False)) == 4
431
+ assert F(Dummy(negative=True, integer=True)) == -1
432
+ assert F(Dummy(negative=True, even=True)) == -2
433
+ assert F(Dummy(zero=True)) == 0
434
+ assert F(Dummy(nonnegative=True)) == 0
435
+ assert F(Dummy(nonpositive=True)) == 0
436
+
437
+ assert F(Dummy(positive=True) + 1).is_positive
438
+ assert F(Dummy(positive=True, integer=True) - 1).is_nonnegative
439
+ assert F(Dummy(positive=True) - 1) is None
440
+ assert F(Dummy(negative=True) + 1) is None
441
+ assert F(Dummy(negative=True, integer=True) - 1).is_nonpositive
442
+ assert F(Dummy(negative=True) - 1).is_negative
443
+ assert F(-Dummy(positive=True) + 1) is None
444
+ assert F(-Dummy(positive=True, integer=True) - 1).is_negative
445
+ assert F(-Dummy(positive=True) - 1).is_negative
446
+ assert F(-Dummy(negative=True) + 1).is_positive
447
+ assert F(-Dummy(negative=True, integer=True) - 1).is_nonnegative
448
+ assert F(-Dummy(negative=True) - 1) is None
449
+ x = Dummy(negative=True)
450
+ assert F(x**3).is_nonpositive
451
+ assert F(x**3 + log(2)*x - 1).is_negative
452
+ x = Dummy(positive=True)
453
+ assert F(-x**3).is_nonpositive
454
+
455
+ p = Dummy(positive=True)
456
+ assert F(1/p).is_positive
457
+ assert F(p/(p + 1)).is_positive
458
+ p = Dummy(nonnegative=True)
459
+ assert F(p/(p + 1)).is_nonnegative
460
+ p = Dummy(positive=True)
461
+ assert F(-1/p).is_negative
462
+ p = Dummy(nonpositive=True)
463
+ assert F(p/(-p + 1)).is_nonpositive
464
+
465
+ p = Dummy(positive=True, integer=True)
466
+ q = Dummy(positive=True, integer=True)
467
+ assert F(-2/p/q).is_negative
468
+ assert F(-2/(p - 1)/q) is None
469
+
470
+ assert F((p - 1)*q + 1).is_positive
471
+ assert F(-(p - 1)*q - 1).is_negative
472
+
473
+ def test_issue_17256():
474
+ from sympy.sets.fancysets import Range
475
+ x = Symbol('x')
476
+ s1 = Sum(x + 1, (x, 1, 9))
477
+ s2 = Sum(x + 1, (x, Range(1, 10)))
478
+ a = Symbol('a')
479
+ r1 = s1.xreplace({x:a})
480
+ r2 = s2.xreplace({x:a})
481
+
482
+ assert r1.doit() == r2.doit()
483
+ s1 = Sum(x + 1, (x, 0, 9))
484
+ s2 = Sum(x + 1, (x, Range(10)))
485
+ a = Symbol('a')
486
+ r1 = s1.xreplace({x:a})
487
+ r2 = s2.xreplace({x:a})
488
+ assert r1 == r2
489
+
490
+ def test_issue_21623():
491
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
492
+ M = MatrixSymbol('X', 2, 2)
493
+ assert gcd_terms(M[0,0], 1) == M[0,0]
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_facts.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.facts import (deduce_alpha_implications,
2
+ apply_beta_to_alpha_route, rules_2prereq, FactRules, FactKB)
3
+ from sympy.core.logic import And, Not
4
+ from sympy.testing.pytest import raises
5
+
6
+ T = True
7
+ F = False
8
+ U = None
9
+
10
+
11
+ def test_deduce_alpha_implications():
12
+ def D(i):
13
+ I = deduce_alpha_implications(i)
14
+ P = rules_2prereq({
15
+ (k, True): {(v, True) for v in S} for k, S in I.items()})
16
+ return I, P
17
+
18
+ # transitivity
19
+ I, P = D([('a', 'b'), ('b', 'c')])
20
+ assert I == {'a': {'b', 'c'}, 'b': {'c'}, Not('b'):
21
+ {Not('a')}, Not('c'): {Not('a'), Not('b')}}
22
+ assert P == {'a': {'b', 'c'}, 'b': {'a', 'c'}, 'c': {'a', 'b'}}
23
+
24
+ # Duplicate entry
25
+ I, P = D([('a', 'b'), ('b', 'c'), ('b', 'c')])
26
+ assert I == {'a': {'b', 'c'}, 'b': {'c'}, Not('b'): {Not('a')}, Not('c'): {Not('a'), Not('b')}}
27
+ assert P == {'a': {'b', 'c'}, 'b': {'a', 'c'}, 'c': {'a', 'b'}}
28
+
29
+ # see if it is tolerant to cycles
30
+ assert D([('a', 'a'), ('a', 'a')]) == ({}, {})
31
+ assert D([('a', 'b'), ('b', 'a')]) == (
32
+ {'a': {'b'}, 'b': {'a'}, Not('a'): {Not('b')}, Not('b'): {Not('a')}},
33
+ {'a': {'b'}, 'b': {'a'}})
34
+
35
+ # see if it catches inconsistency
36
+ raises(ValueError, lambda: D([('a', Not('a'))]))
37
+ raises(ValueError, lambda: D([('a', 'b'), ('b', Not('a'))]))
38
+ raises(ValueError, lambda: D([('a', 'b'), ('b', 'c'), ('b', 'na'),
39
+ ('na', Not('a'))]))
40
+
41
+ # see if it handles implications with negations
42
+ I, P = D([('a', Not('b')), ('c', 'b')])
43
+ assert I == {'a': {Not('b'), Not('c')}, 'b': {Not('a')}, 'c': {'b', Not('a')}, Not('b'): {Not('c')}}
44
+ assert P == {'a': {'b', 'c'}, 'b': {'a', 'c'}, 'c': {'a', 'b'}}
45
+ I, P = D([(Not('a'), 'b'), ('a', 'c')])
46
+ assert I == {'a': {'c'}, Not('a'): {'b'}, Not('b'): {'a',
47
+ 'c'}, Not('c'): {Not('a'), 'b'},}
48
+ assert P == {'a': {'b', 'c'}, 'b': {'a', 'c'}, 'c': {'a', 'b'}}
49
+
50
+
51
+ # Long deductions
52
+ I, P = D([('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')])
53
+ assert I == {'a': {'b', 'c', 'd', 'e'}, 'b': {'c', 'd', 'e'},
54
+ 'c': {'d', 'e'}, 'd': {'e'}, Not('b'): {Not('a')},
55
+ Not('c'): {Not('a'), Not('b')}, Not('d'): {Not('a'), Not('b'),
56
+ Not('c')}, Not('e'): {Not('a'), Not('b'), Not('c'), Not('d')}}
57
+ assert P == {'a': {'b', 'c', 'd', 'e'}, 'b': {'a', 'c', 'd',
58
+ 'e'}, 'c': {'a', 'b', 'd', 'e'}, 'd': {'a', 'b', 'c', 'e'},
59
+ 'e': {'a', 'b', 'c', 'd'}}
60
+
61
+ # something related to real-world
62
+ I, P = D([('rat', 'real'), ('int', 'rat')])
63
+
64
+ assert I == {'int': {'rat', 'real'}, 'rat': {'real'},
65
+ Not('real'): {Not('rat'), Not('int')}, Not('rat'): {Not('int')}}
66
+ assert P == {'rat': {'int', 'real'}, 'real': {'int', 'rat'},
67
+ 'int': {'rat', 'real'}}
68
+
69
+
70
+ # TODO move me to appropriate place
71
+ def test_apply_beta_to_alpha_route():
72
+ APPLY = apply_beta_to_alpha_route
73
+
74
+ # indicates empty alpha-chain with attached beta-rule #bidx
75
+ def Q(bidx):
76
+ return (set(), [bidx])
77
+
78
+ # x -> a &(a,b) -> x -- x -> a
79
+ A = {'x': {'a'}}
80
+ B = [(And('a', 'b'), 'x')]
81
+ assert APPLY(A, B) == {'x': ({'a'}, []), 'a': Q(0), 'b': Q(0)}
82
+
83
+ # x -> a &(a,!x) -> b -- x -> a
84
+ A = {'x': {'a'}}
85
+ B = [(And('a', Not('x')), 'b')]
86
+ assert APPLY(A, B) == {'x': ({'a'}, []), Not('x'): Q(0), 'a': Q(0)}
87
+
88
+ # x -> a b &(a,b) -> c -- x -> a b c
89
+ A = {'x': {'a', 'b'}}
90
+ B = [(And('a', 'b'), 'c')]
91
+ assert APPLY(A, B) == \
92
+ {'x': ({'a', 'b', 'c'}, []), 'a': Q(0), 'b': Q(0)}
93
+
94
+ # x -> a &(a,b) -> y -- x -> a [#0]
95
+ A = {'x': {'a'}}
96
+ B = [(And('a', 'b'), 'y')]
97
+ assert APPLY(A, B) == {'x': ({'a'}, [0]), 'a': Q(0), 'b': Q(0)}
98
+
99
+ # x -> a b c &(a,b) -> c -- x -> a b c
100
+ A = {'x': {'a', 'b', 'c'}}
101
+ B = [(And('a', 'b'), 'c')]
102
+ assert APPLY(A, B) == \
103
+ {'x': ({'a', 'b', 'c'}, []), 'a': Q(0), 'b': Q(0)}
104
+
105
+ # x -> a b &(a,b,c) -> y -- x -> a b [#0]
106
+ A = {'x': {'a', 'b'}}
107
+ B = [(And('a', 'b', 'c'), 'y')]
108
+ assert APPLY(A, B) == \
109
+ {'x': ({'a', 'b'}, [0]), 'a': Q(0), 'b': Q(0), 'c': Q(0)}
110
+
111
+ # x -> a b &(a,b) -> c -- x -> a b c d
112
+ # c -> d c -> d
113
+ A = {'x': {'a', 'b'}, 'c': {'d'}}
114
+ B = [(And('a', 'b'), 'c')]
115
+ assert APPLY(A, B) == {'x': ({'a', 'b', 'c', 'd'}, []),
116
+ 'c': ({'d'}, []), 'a': Q(0), 'b': Q(0)}
117
+
118
+ # x -> a b &(a,b) -> c -- x -> a b c d e
119
+ # c -> d &(c,d) -> e c -> d e
120
+ A = {'x': {'a', 'b'}, 'c': {'d'}}
121
+ B = [(And('a', 'b'), 'c'), (And('c', 'd'), 'e')]
122
+ assert APPLY(A, B) == {'x': ({'a', 'b', 'c', 'd', 'e'}, []),
123
+ 'c': ({'d', 'e'}, []), 'a': Q(0), 'b': Q(0), 'd': Q(1)}
124
+
125
+ # x -> a b &(a,y) -> z -- x -> a b y z
126
+ # &(a,b) -> y
127
+ A = {'x': {'a', 'b'}}
128
+ B = [(And('a', 'y'), 'z'), (And('a', 'b'), 'y')]
129
+ assert APPLY(A, B) == {'x': ({'a', 'b', 'y', 'z'}, []),
130
+ 'a': (set(), [0, 1]), 'y': Q(0), 'b': Q(1)}
131
+
132
+ # x -> a b &(a,!b) -> c -- x -> a b
133
+ A = {'x': {'a', 'b'}}
134
+ B = [(And('a', Not('b')), 'c')]
135
+ assert APPLY(A, B) == \
136
+ {'x': ({'a', 'b'}, []), 'a': Q(0), Not('b'): Q(0)}
137
+
138
+ # !x -> !a !b &(!a,b) -> c -- !x -> !a !b
139
+ A = {Not('x'): {Not('a'), Not('b')}}
140
+ B = [(And(Not('a'), 'b'), 'c')]
141
+ assert APPLY(A, B) == \
142
+ {Not('x'): ({Not('a'), Not('b')}, []), Not('a'): Q(0), 'b': Q(0)}
143
+
144
+ # x -> a b &(b,c) -> !a -- x -> a b
145
+ A = {'x': {'a', 'b'}}
146
+ B = [(And('b', 'c'), Not('a'))]
147
+ assert APPLY(A, B) == {'x': ({'a', 'b'}, []), 'b': Q(0), 'c': Q(0)}
148
+
149
+ # x -> a b &(a, b) -> c -- x -> a b c p
150
+ # c -> p a
151
+ A = {'x': {'a', 'b'}, 'c': {'p', 'a'}}
152
+ B = [(And('a', 'b'), 'c')]
153
+ assert APPLY(A, B) == {'x': ({'a', 'b', 'c', 'p'}, []),
154
+ 'c': ({'p', 'a'}, []), 'a': Q(0), 'b': Q(0)}
155
+
156
+
157
+ def test_FactRules_parse():
158
+ f = FactRules('a -> b')
159
+ assert f.prereq == {'b': {'a'}, 'a': {'b'}}
160
+
161
+ f = FactRules('a -> !b')
162
+ assert f.prereq == {'b': {'a'}, 'a': {'b'}}
163
+
164
+ f = FactRules('!a -> b')
165
+ assert f.prereq == {'b': {'a'}, 'a': {'b'}}
166
+
167
+ f = FactRules('!a -> !b')
168
+ assert f.prereq == {'b': {'a'}, 'a': {'b'}}
169
+
170
+ f = FactRules('!z == nz')
171
+ assert f.prereq == {'z': {'nz'}, 'nz': {'z'}}
172
+
173
+
174
+ def test_FactRules_parse2():
175
+ raises(ValueError, lambda: FactRules('a -> !a'))
176
+
177
+
178
+ def test_FactRules_deduce():
179
+ f = FactRules(['a -> b', 'b -> c', 'b -> d', 'c -> e'])
180
+
181
+ def D(facts):
182
+ kb = FactKB(f)
183
+ kb.deduce_all_facts(facts)
184
+ return kb
185
+
186
+ assert D({'a': T}) == {'a': T, 'b': T, 'c': T, 'd': T, 'e': T}
187
+ assert D({'b': T}) == { 'b': T, 'c': T, 'd': T, 'e': T}
188
+ assert D({'c': T}) == { 'c': T, 'e': T}
189
+ assert D({'d': T}) == { 'd': T }
190
+ assert D({'e': T}) == { 'e': T}
191
+
192
+ assert D({'a': F}) == {'a': F }
193
+ assert D({'b': F}) == {'a': F, 'b': F }
194
+ assert D({'c': F}) == {'a': F, 'b': F, 'c': F }
195
+ assert D({'d': F}) == {'a': F, 'b': F, 'd': F }
196
+
197
+ assert D({'a': U}) == {'a': U} # XXX ok?
198
+
199
+
200
+ def test_FactRules_deduce2():
201
+ # pos/neg/zero, but the rules are not sufficient to derive all relations
202
+ f = FactRules(['pos -> !neg', 'pos -> !z'])
203
+
204
+ def D(facts):
205
+ kb = FactKB(f)
206
+ kb.deduce_all_facts(facts)
207
+ return kb
208
+
209
+ assert D({'pos': T}) == {'pos': T, 'neg': F, 'z': F}
210
+ assert D({'pos': F}) == {'pos': F }
211
+ assert D({'neg': T}) == {'pos': F, 'neg': T }
212
+ assert D({'neg': F}) == { 'neg': F }
213
+ assert D({'z': T}) == {'pos': F, 'z': T}
214
+ assert D({'z': F}) == { 'z': F}
215
+
216
+ # pos/neg/zero. rules are sufficient to derive all relations
217
+ f = FactRules(['pos -> !neg', 'neg -> !pos', 'pos -> !z', 'neg -> !z'])
218
+
219
+ assert D({'pos': T}) == {'pos': T, 'neg': F, 'z': F}
220
+ assert D({'pos': F}) == {'pos': F }
221
+ assert D({'neg': T}) == {'pos': F, 'neg': T, 'z': F}
222
+ assert D({'neg': F}) == { 'neg': F }
223
+ assert D({'z': T}) == {'pos': F, 'neg': F, 'z': T}
224
+ assert D({'z': F}) == { 'z': F}
225
+
226
+
227
+ def test_FactRules_deduce_multiple():
228
+ # deduction that involves _several_ starting points
229
+ f = FactRules(['real == pos | npos'])
230
+
231
+ def D(facts):
232
+ kb = FactKB(f)
233
+ kb.deduce_all_facts(facts)
234
+ return kb
235
+
236
+ assert D({'real': T}) == {'real': T}
237
+ assert D({'real': F}) == {'real': F, 'pos': F, 'npos': F}
238
+ assert D({'pos': T}) == {'real': T, 'pos': T}
239
+ assert D({'npos': T}) == {'real': T, 'npos': T}
240
+
241
+ # --- key tests below ---
242
+ assert D({'pos': F, 'npos': F}) == {'real': F, 'pos': F, 'npos': F}
243
+ assert D({'real': T, 'pos': F}) == {'real': T, 'pos': F, 'npos': T}
244
+ assert D({'real': T, 'npos': F}) == {'real': T, 'pos': T, 'npos': F}
245
+
246
+ assert D({'pos': T, 'npos': F}) == {'real': T, 'pos': T, 'npos': F}
247
+ assert D({'pos': F, 'npos': T}) == {'real': T, 'pos': F, 'npos': T}
248
+
249
+
250
+ def test_FactRules_deduce_multiple2():
251
+ f = FactRules(['real == neg | zero | pos'])
252
+
253
+ def D(facts):
254
+ kb = FactKB(f)
255
+ kb.deduce_all_facts(facts)
256
+ return kb
257
+
258
+ assert D({'real': T}) == {'real': T}
259
+ assert D({'real': F}) == {'real': F, 'neg': F, 'zero': F, 'pos': F}
260
+ assert D({'neg': T}) == {'real': T, 'neg': T}
261
+ assert D({'zero': T}) == {'real': T, 'zero': T}
262
+ assert D({'pos': T}) == {'real': T, 'pos': T}
263
+
264
+ # --- key tests below ---
265
+ assert D({'neg': F, 'zero': F, 'pos': F}) == {'real': F, 'neg': F,
266
+ 'zero': F, 'pos': F}
267
+ assert D({'real': T, 'neg': F}) == {'real': T, 'neg': F}
268
+ assert D({'real': T, 'zero': F}) == {'real': T, 'zero': F}
269
+ assert D({'real': T, 'pos': F}) == {'real': T, 'pos': F}
270
+
271
+ assert D({'real': T, 'zero': F, 'pos': F}) == {'real': T,
272
+ 'neg': T, 'zero': F, 'pos': F}
273
+ assert D({'real': T, 'neg': F, 'pos': F}) == {'real': T,
274
+ 'neg': F, 'zero': T, 'pos': F}
275
+ assert D({'real': T, 'neg': F, 'zero': F }) == {'real': T,
276
+ 'neg': F, 'zero': F, 'pos': T}
277
+
278
+ assert D({'neg': T, 'zero': F, 'pos': F}) == {'real': T, 'neg': T,
279
+ 'zero': F, 'pos': F}
280
+ assert D({'neg': F, 'zero': T, 'pos': F}) == {'real': T, 'neg': F,
281
+ 'zero': T, 'pos': F}
282
+ assert D({'neg': F, 'zero': F, 'pos': T}) == {'real': T, 'neg': F,
283
+ 'zero': F, 'pos': T}
284
+
285
+
286
+ def test_FactRules_deduce_base():
287
+ # deduction that starts from base
288
+
289
+ f = FactRules(['real == neg | zero | pos',
290
+ 'neg -> real & !zero & !pos',
291
+ 'pos -> real & !zero & !neg'])
292
+ base = FactKB(f)
293
+
294
+ base.deduce_all_facts({'real': T, 'neg': F})
295
+ assert base == {'real': T, 'neg': F}
296
+
297
+ base.deduce_all_facts({'zero': F})
298
+ assert base == {'real': T, 'neg': F, 'zero': F, 'pos': T}
299
+
300
+
301
+ def test_FactRules_deduce_staticext():
302
+ # verify that static beta-extensions deduction takes place
303
+ f = FactRules(['real == neg | zero | pos',
304
+ 'neg -> real & !zero & !pos',
305
+ 'pos -> real & !zero & !neg',
306
+ 'nneg == real & !neg',
307
+ 'npos == real & !pos'])
308
+
309
+ assert ('npos', True) in f.full_implications[('neg', True)]
310
+ assert ('nneg', True) in f.full_implications[('pos', True)]
311
+ assert ('nneg', True) in f.full_implications[('zero', True)]
312
+ assert ('npos', True) in f.full_implications[('zero', True)]
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_function.py ADDED
@@ -0,0 +1,1455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.basic import Basic, _aresame
3
+ from sympy.core.cache import clear_cache
4
+ from sympy.core.containers import Dict, Tuple
5
+ from sympy.core.expr import Expr, unchanged
6
+ from sympy.core.function import (Subs, Function, diff, Lambda, expand,
7
+ nfloat, Derivative)
8
+ from sympy.core.numbers import E, Float, zoo, Rational, pi, I, oo, nan
9
+ from sympy.core.power import Pow
10
+ from sympy.core.relational import Eq
11
+ from sympy.core.singleton import S
12
+ from sympy.core.symbol import symbols, Dummy, Symbol
13
+ from sympy.functions.elementary.complexes import im, re
14
+ from sympy.functions.elementary.exponential import log, exp
15
+ from sympy.functions.elementary.miscellaneous import sqrt
16
+ from sympy.functions.elementary.piecewise import Piecewise
17
+ from sympy.functions.elementary.trigonometric import sin, cos, acos
18
+ from sympy.functions.special.error_functions import expint
19
+ from sympy.functions.special.gamma_functions import loggamma, polygamma
20
+ from sympy.matrices.dense import Matrix
21
+ from sympy.printing.str import sstr
22
+ from sympy.series.order import O
23
+ from sympy.tensor.indexed import Indexed
24
+ from sympy.core.function import (PoleError, _mexpand, arity,
25
+ BadSignatureError, BadArgumentsError)
26
+ from sympy.core.parameters import _exp_is_pow
27
+ from sympy.core.sympify import sympify, SympifyError
28
+ from sympy.matrices import MutableMatrix, ImmutableMatrix
29
+ from sympy.sets.sets import FiniteSet
30
+ from sympy.solvers.solveset import solveset
31
+ from sympy.tensor.array import NDimArray
32
+ from sympy.utilities.iterables import subsets, variations
33
+ from sympy.testing.pytest import XFAIL, raises, warns_deprecated_sympy, _both_exp_pow
34
+
35
+ from sympy.abc import t, w, x, y, z
36
+ f, g, h = symbols('f g h', cls=Function)
37
+ _xi_1, _xi_2, _xi_3 = [Dummy() for i in range(3)]
38
+
39
+ def test_f_expand_complex():
40
+ x = Symbol('x', real=True)
41
+
42
+ assert f(x).expand(complex=True) == I*im(f(x)) + re(f(x))
43
+ assert exp(x).expand(complex=True) == exp(x)
44
+ assert exp(I*x).expand(complex=True) == cos(x) + I*sin(x)
45
+ assert exp(z).expand(complex=True) == cos(im(z))*exp(re(z)) + \
46
+ I*sin(im(z))*exp(re(z))
47
+
48
+
49
+ def test_bug1():
50
+ e = sqrt(-log(w))
51
+ assert e.subs(log(w), -x) == sqrt(x)
52
+
53
+ e = sqrt(-5*log(w))
54
+ assert e.subs(log(w), -x) == sqrt(5*x)
55
+
56
+
57
+ def test_general_function():
58
+ nu = Function('nu')
59
+
60
+ e = nu(x)
61
+ edx = e.diff(x)
62
+ edy = e.diff(y)
63
+ edxdx = e.diff(x).diff(x)
64
+ edxdy = e.diff(x).diff(y)
65
+ assert e == nu(x)
66
+ assert edx != nu(x)
67
+ assert edx == diff(nu(x), x)
68
+ assert edy == 0
69
+ assert edxdx == diff(diff(nu(x), x), x)
70
+ assert edxdy == 0
71
+
72
+ def test_general_function_nullary():
73
+ nu = Function('nu')
74
+
75
+ e = nu()
76
+ edx = e.diff(x)
77
+ edxdx = e.diff(x).diff(x)
78
+ assert e == nu()
79
+ assert edx != nu()
80
+ assert edx == 0
81
+ assert edxdx == 0
82
+
83
+
84
+ def test_derivative_subs_bug():
85
+ e = diff(g(x), x)
86
+ assert e.subs(g(x), f(x)) != e
87
+ assert e.subs(g(x), f(x)) == Derivative(f(x), x)
88
+ assert e.subs(g(x), -f(x)) == Derivative(-f(x), x)
89
+
90
+ assert e.subs(x, y) == Derivative(g(y), y)
91
+
92
+
93
+ def test_derivative_subs_self_bug():
94
+ d = diff(f(x), x)
95
+
96
+ assert d.subs(d, y) == y
97
+
98
+
99
+ def test_derivative_linearity():
100
+ assert diff(-f(x), x) == -diff(f(x), x)
101
+ assert diff(8*f(x), x) == 8*diff(f(x), x)
102
+ assert diff(8*f(x), x) != 7*diff(f(x), x)
103
+ assert diff(8*f(x)*x, x) == 8*f(x) + 8*x*diff(f(x), x)
104
+ assert diff(8*f(x)*y*x, x).expand() == 8*y*f(x) + 8*y*x*diff(f(x), x)
105
+
106
+
107
+ def test_derivative_evaluate():
108
+ assert Derivative(sin(x), x) != diff(sin(x), x)
109
+ assert Derivative(sin(x), x).doit() == diff(sin(x), x)
110
+
111
+ assert Derivative(Derivative(f(x), x), x) == diff(f(x), x, x)
112
+ assert Derivative(sin(x), x, 0) == sin(x)
113
+ assert Derivative(sin(x), (x, y), (x, -y)) == sin(x)
114
+
115
+
116
+ def test_diff_symbols():
117
+ assert diff(f(x, y, z), x, y, z) == Derivative(f(x, y, z), x, y, z)
118
+ assert diff(f(x, y, z), x, x, x) == Derivative(f(x, y, z), x, x, x) == Derivative(f(x, y, z), (x, 3))
119
+ assert diff(f(x, y, z), x, 3) == Derivative(f(x, y, z), x, 3)
120
+
121
+ # issue 5028
122
+ assert [diff(-z + x/y, sym) for sym in (z, x, y)] == [-1, 1/y, -x/y**2]
123
+ assert diff(f(x, y, z), x, y, z, 2) == Derivative(f(x, y, z), x, y, z, z)
124
+ assert diff(f(x, y, z), x, y, z, 2, evaluate=False) == \
125
+ Derivative(f(x, y, z), x, y, z, z)
126
+ assert Derivative(f(x, y, z), x, y, z)._eval_derivative(z) == \
127
+ Derivative(f(x, y, z), x, y, z, z)
128
+ assert Derivative(Derivative(f(x, y, z), x), y)._eval_derivative(z) == \
129
+ Derivative(f(x, y, z), x, y, z)
130
+
131
+ raises(TypeError, lambda: cos(x).diff((x, y)).variables)
132
+ assert cos(x).diff((x, y))._wrt_variables == [x]
133
+
134
+ # issue 23222
135
+ assert sympify("a*x+b").diff("x") == sympify("a")
136
+
137
+ def test_Function():
138
+ class myfunc(Function):
139
+ @classmethod
140
+ def eval(cls): # zero args
141
+ return
142
+
143
+ assert myfunc.nargs == FiniteSet(0)
144
+ assert myfunc().nargs == FiniteSet(0)
145
+ raises(TypeError, lambda: myfunc(x).nargs)
146
+
147
+ class myfunc(Function):
148
+ @classmethod
149
+ def eval(cls, x): # one arg
150
+ return
151
+
152
+ assert myfunc.nargs == FiniteSet(1)
153
+ assert myfunc(x).nargs == FiniteSet(1)
154
+ raises(TypeError, lambda: myfunc(x, y).nargs)
155
+
156
+ class myfunc(Function):
157
+ @classmethod
158
+ def eval(cls, *x): # star args
159
+ return
160
+
161
+ assert myfunc.nargs == S.Naturals0
162
+ assert myfunc(x).nargs == S.Naturals0
163
+
164
+
165
+ def test_nargs():
166
+ f = Function('f')
167
+ assert f.nargs == S.Naturals0
168
+ assert f(1).nargs == S.Naturals0
169
+ assert Function('f', nargs=2)(1, 2).nargs == FiniteSet(2)
170
+ assert sin.nargs == FiniteSet(1)
171
+ assert sin(2).nargs == FiniteSet(1)
172
+ assert log.nargs == FiniteSet(1, 2)
173
+ assert log(2).nargs == FiniteSet(1, 2)
174
+ assert Function('f', nargs=2).nargs == FiniteSet(2)
175
+ assert Function('f', nargs=0).nargs == FiniteSet(0)
176
+ assert Function('f', nargs=(0, 1)).nargs == FiniteSet(0, 1)
177
+ assert Function('f', nargs=None).nargs == S.Naturals0
178
+ raises(ValueError, lambda: Function('f', nargs=()))
179
+
180
+ def test_nargs_inheritance():
181
+ class f1(Function):
182
+ nargs = 2
183
+ class f2(f1):
184
+ pass
185
+ class f3(f2):
186
+ pass
187
+ class f4(f3):
188
+ nargs = 1,2
189
+ class f5(f4):
190
+ pass
191
+ class f6(f5):
192
+ pass
193
+ class f7(f6):
194
+ nargs=None
195
+ class f8(f7):
196
+ pass
197
+ class f9(f8):
198
+ pass
199
+ class f10(f9):
200
+ nargs = 1
201
+ class f11(f10):
202
+ pass
203
+ assert f1.nargs == FiniteSet(2)
204
+ assert f2.nargs == FiniteSet(2)
205
+ assert f3.nargs == FiniteSet(2)
206
+ assert f4.nargs == FiniteSet(1, 2)
207
+ assert f5.nargs == FiniteSet(1, 2)
208
+ assert f6.nargs == FiniteSet(1, 2)
209
+ assert f7.nargs == S.Naturals0
210
+ assert f8.nargs == S.Naturals0
211
+ assert f9.nargs == S.Naturals0
212
+ assert f10.nargs == FiniteSet(1)
213
+ assert f11.nargs == FiniteSet(1)
214
+
215
+ def test_arity():
216
+ f = lambda x, y: 1
217
+ assert arity(f) == 2
218
+ def f(x, y, z=None):
219
+ pass
220
+ assert arity(f) == (2, 3)
221
+ assert arity(lambda *x: x) is None
222
+ assert arity(log) == (1, 2)
223
+
224
+
225
+ def test_Lambda():
226
+ e = Lambda(x, x**2)
227
+ assert e(4) == 16
228
+ assert e(x) == x**2
229
+ assert e(y) == y**2
230
+
231
+ assert Lambda((), 42)() == 42
232
+ assert unchanged(Lambda, (), 42)
233
+ assert Lambda((), 42) != Lambda((), 43)
234
+ assert Lambda((), f(x))() == f(x)
235
+ assert Lambda((), 42).nargs == FiniteSet(0)
236
+
237
+ assert unchanged(Lambda, (x,), x**2)
238
+ assert Lambda(x, x**2) == Lambda((x,), x**2)
239
+ assert Lambda(x, x**2) != Lambda(x, x**2 + 1)
240
+ assert Lambda((x, y), x**y) != Lambda((y, x), y**x)
241
+ assert Lambda((x, y), x**y) != Lambda((x, y), y**x)
242
+
243
+ assert Lambda((x, y), x**y)(x, y) == x**y
244
+ assert Lambda((x, y), x**y)(3, 3) == 3**3
245
+ assert Lambda((x, y), x**y)(x, 3) == x**3
246
+ assert Lambda((x, y), x**y)(3, y) == 3**y
247
+ assert Lambda(x, f(x))(x) == f(x)
248
+ assert Lambda(x, x**2)(e(x)) == x**4
249
+ assert e(e(x)) == x**4
250
+
251
+ x1, x2 = (Indexed('x', i) for i in (1, 2))
252
+ assert Lambda((x1, x2), x1 + x2)(x, y) == x + y
253
+
254
+ assert Lambda((x, y), x + y).nargs == FiniteSet(2)
255
+
256
+ p = x, y, z, t
257
+ assert Lambda(p, t*(x + y + z))(*p) == t * (x + y + z)
258
+
259
+ eq = Lambda(x, 2*x) + Lambda(y, 2*y)
260
+ assert eq != 2*Lambda(x, 2*x)
261
+ assert eq.as_dummy() == 2*Lambda(x, 2*x).as_dummy()
262
+ assert Lambda(x, 2*x) not in [ Lambda(x, x) ]
263
+ raises(BadSignatureError, lambda: Lambda(1, x))
264
+ assert Lambda(x, 1)(1) is S.One
265
+
266
+ raises(BadSignatureError, lambda: Lambda((x, x), x + 2))
267
+ raises(BadSignatureError, lambda: Lambda(((x, x), y), x))
268
+ raises(BadSignatureError, lambda: Lambda(((y, x), x), x))
269
+ raises(BadSignatureError, lambda: Lambda(((y, 1), 2), x))
270
+
271
+ with warns_deprecated_sympy():
272
+ assert Lambda([x, y], x+y) == Lambda((x, y), x+y)
273
+
274
+ flam = Lambda(((x, y),), x + y)
275
+ assert flam((2, 3)) == 5
276
+ flam = Lambda(((x, y), z), x + y + z)
277
+ assert flam((2, 3), 1) == 6
278
+ flam = Lambda((((x, y), z),), x + y + z)
279
+ assert flam(((2, 3), 1)) == 6
280
+ raises(BadArgumentsError, lambda: flam(1, 2, 3))
281
+ flam = Lambda( (x,), (x, x))
282
+ assert flam(1,) == (1, 1)
283
+ assert flam((1,)) == ((1,), (1,))
284
+ flam = Lambda( ((x,),), (x, x))
285
+ raises(BadArgumentsError, lambda: flam(1))
286
+ assert flam((1,)) == (1, 1)
287
+
288
+ # Previously TypeError was raised so this is potentially needed for
289
+ # backwards compatibility.
290
+ assert issubclass(BadSignatureError, TypeError)
291
+ assert issubclass(BadArgumentsError, TypeError)
292
+
293
+ # These are tested to see they don't raise:
294
+ hash(Lambda(x, 2*x))
295
+ hash(Lambda(x, x)) # IdentityFunction subclass
296
+
297
+
298
+ def test_IdentityFunction():
299
+ assert Lambda(x, x) is Lambda(y, y) is S.IdentityFunction
300
+ assert Lambda(x, 2*x) is not S.IdentityFunction
301
+ assert Lambda((x, y), x) is not S.IdentityFunction
302
+
303
+
304
+ def test_Lambda_symbols():
305
+ assert Lambda(x, 2*x).free_symbols == set()
306
+ assert Lambda(x, x*y).free_symbols == {y}
307
+ assert Lambda((), 42).free_symbols == set()
308
+ assert Lambda((), x*y).free_symbols == {x,y}
309
+
310
+
311
+ def test_functionclas_symbols():
312
+ assert f.free_symbols == set()
313
+
314
+
315
+ def test_Lambda_arguments():
316
+ raises(TypeError, lambda: Lambda(x, 2*x)(x, y))
317
+ raises(TypeError, lambda: Lambda((x, y), x + y)(x))
318
+ raises(TypeError, lambda: Lambda((), 42)(x))
319
+
320
+
321
+ def test_Lambda_equality():
322
+ assert Lambda((x, y), 2*x) == Lambda((x, y), 2*x)
323
+ # these, of course, should never be equal
324
+ assert Lambda(x, 2*x) != Lambda((x, y), 2*x)
325
+ assert Lambda(x, 2*x) != 2*x
326
+ # But it is tempting to want expressions that differ only
327
+ # in bound symbols to compare the same. But this is not what
328
+ # Python's `==` is intended to do; two objects that compare
329
+ # as equal means that they are indistibguishable and cache to the
330
+ # same value. We wouldn't want to expression that are
331
+ # mathematically the same but written in different variables to be
332
+ # interchanged else what is the point of allowing for different
333
+ # variable names?
334
+ assert Lambda(x, 2*x) != Lambda(y, 2*y)
335
+
336
+
337
+ def test_Subs():
338
+ assert Subs(1, (), ()) is S.One
339
+ # check null subs influence on hashing
340
+ assert Subs(x, y, z) != Subs(x, y, 1)
341
+ # neutral subs works
342
+ assert Subs(x, x, 1).subs(x, y).has(y)
343
+ # self mapping var/point
344
+ assert Subs(Derivative(f(x), (x, 2)), x, x).doit() == f(x).diff(x, x)
345
+ assert Subs(x, x, 0).has(x) # it's a structural answer
346
+ assert not Subs(x, x, 0).free_symbols
347
+ assert Subs(Subs(x + y, x, 2), y, 1) == Subs(x + y, (x, y), (2, 1))
348
+ assert Subs(x, (x,), (0,)) == Subs(x, x, 0)
349
+ assert Subs(x, x, 0) == Subs(y, y, 0)
350
+ assert Subs(x, x, 0).subs(x, 1) == Subs(x, x, 0)
351
+ assert Subs(y, x, 0).subs(y, 1) == Subs(1, x, 0)
352
+ assert Subs(f(x), x, 0).doit() == f(0)
353
+ assert Subs(f(x**2), x**2, 0).doit() == f(0)
354
+ assert Subs(f(x, y, z), (x, y, z), (0, 1, 1)) != \
355
+ Subs(f(x, y, z), (x, y, z), (0, 0, 1))
356
+ assert Subs(x, y, 2).subs(x, y).doit() == 2
357
+ assert Subs(f(x, y), (x, y, z), (0, 1, 1)) != \
358
+ Subs(f(x, y) + z, (x, y, z), (0, 1, 0))
359
+ assert Subs(f(x, y), (x, y), (0, 1)).doit() == f(0, 1)
360
+ assert Subs(Subs(f(x, y), x, 0), y, 1).doit() == f(0, 1)
361
+ raises(ValueError, lambda: Subs(f(x, y), (x, y), (0, 0, 1)))
362
+ raises(ValueError, lambda: Subs(f(x, y), (x, x, y), (0, 0, 1)))
363
+
364
+ assert len(Subs(f(x, y), (x, y), (0, 1)).variables) == 2
365
+ assert Subs(f(x, y), (x, y), (0, 1)).point == Tuple(0, 1)
366
+
367
+ assert Subs(f(x), x, 0) == Subs(f(y), y, 0)
368
+ assert Subs(f(x, y), (x, y), (0, 1)) == Subs(f(x, y), (y, x), (1, 0))
369
+ assert Subs(f(x)*y, (x, y), (0, 1)) == Subs(f(y)*x, (y, x), (0, 1))
370
+ assert Subs(f(x)*y, (x, y), (1, 1)) == Subs(f(y)*x, (x, y), (1, 1))
371
+
372
+ assert Subs(f(x), x, 0).subs(x, 1).doit() == f(0)
373
+ assert Subs(f(x), x, y).subs(y, 0) == Subs(f(x), x, 0)
374
+ assert Subs(y*f(x), x, y).subs(y, 2) == Subs(2*f(x), x, 2)
375
+ assert (2 * Subs(f(x), x, 0)).subs(Subs(f(x), x, 0), y) == 2*y
376
+
377
+ assert Subs(f(x), x, 0).free_symbols == set()
378
+ assert Subs(f(x, y), x, z).free_symbols == {y, z}
379
+
380
+ assert Subs(f(x).diff(x), x, 0).doit(), Subs(f(x).diff(x), x, 0)
381
+ assert Subs(1 + f(x).diff(x), x, 0).doit(), 1 + Subs(f(x).diff(x), x, 0)
382
+ assert Subs(y*f(x, y).diff(x), (x, y), (0, 2)).doit() == \
383
+ 2*Subs(Derivative(f(x, 2), x), x, 0)
384
+ assert Subs(y**2*f(x), x, 0).diff(y) == 2*y*f(0)
385
+
386
+ e = Subs(y**2*f(x), x, y)
387
+ assert e.diff(y) == e.doit().diff(y) == y**2*Derivative(f(y), y) + 2*y*f(y)
388
+
389
+ assert Subs(f(x), x, 0) + Subs(f(x), x, 0) == 2*Subs(f(x), x, 0)
390
+ e1 = Subs(z*f(x), x, 1)
391
+ e2 = Subs(z*f(y), y, 1)
392
+ assert e1 + e2 == 2*e1
393
+ assert e1.__hash__() == e2.__hash__()
394
+ assert Subs(z*f(x + 1), x, 1) not in [ e1, e2 ]
395
+ assert Derivative(f(x), x).subs(x, g(x)) == Derivative(f(g(x)), g(x))
396
+ assert Derivative(f(x), x).subs(x, x + y) == Subs(Derivative(f(x), x),
397
+ x, x + y)
398
+ assert Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).n(2) == \
399
+ Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).evalf(2) == \
400
+ z + Rational('1/2').n(2)*f(0)
401
+
402
+ assert f(x).diff(x).subs(x, 0).subs(x, y) == f(x).diff(x).subs(x, 0)
403
+ assert (x*f(x).diff(x).subs(x, 0)).subs(x, y) == y*f(x).diff(x).subs(x, 0)
404
+ assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x)
405
+ ).doit() == 2*exp(x)
406
+ assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x)
407
+ ).doit(deep=False) == 2*Derivative(exp(x), x)
408
+ assert Derivative(f(x, g(x)), x).doit() == Derivative(
409
+ f(x, g(x)), g(x))*Derivative(g(x), x) + Subs(Derivative(
410
+ f(y, g(x)), y), y, x)
411
+
412
+ def test_doitdoit():
413
+ done = Derivative(f(x, g(x)), x, g(x)).doit()
414
+ assert done == done.doit()
415
+
416
+
417
+ @XFAIL
418
+ def test_Subs2():
419
+ # this reflects a limitation of subs(), probably won't fix
420
+ assert Subs(f(x), x**2, x).doit() == f(sqrt(x))
421
+
422
+
423
+ def test_expand_function():
424
+ assert expand(x + y) == x + y
425
+ assert expand(x + y, complex=True) == I*im(x) + I*im(y) + re(x) + re(y)
426
+ assert expand((x + y)**11, modulus=11) == x**11 + y**11
427
+
428
+
429
+ def test_function_comparable():
430
+ assert sin(x).is_comparable is False
431
+ assert cos(x).is_comparable is False
432
+
433
+ assert sin(Float('0.1')).is_comparable is True
434
+ assert cos(Float('0.1')).is_comparable is True
435
+
436
+ assert sin(E).is_comparable is True
437
+ assert cos(E).is_comparable is True
438
+
439
+ assert sin(Rational(1, 3)).is_comparable is True
440
+ assert cos(Rational(1, 3)).is_comparable is True
441
+
442
+
443
+ def test_function_comparable_infinities():
444
+ assert sin(oo).is_comparable is False
445
+ assert sin(-oo).is_comparable is False
446
+ assert sin(zoo).is_comparable is False
447
+ assert sin(nan).is_comparable is False
448
+
449
+
450
+ def test_deriv1():
451
+ # These all require derivatives evaluated at a point (issue 4719) to work.
452
+ # See issue 4624
453
+ assert f(2*x).diff(x) == 2*Subs(Derivative(f(x), x), x, 2*x)
454
+ assert (f(x)**3).diff(x) == 3*f(x)**2*f(x).diff(x)
455
+ assert (f(2*x)**3).diff(x) == 6*f(2*x)**2*Subs(
456
+ Derivative(f(x), x), x, 2*x)
457
+
458
+ assert f(2 + x).diff(x) == Subs(Derivative(f(x), x), x, x + 2)
459
+ assert f(2 + 3*x).diff(x) == 3*Subs(
460
+ Derivative(f(x), x), x, 3*x + 2)
461
+ assert f(3*sin(x)).diff(x) == 3*cos(x)*Subs(
462
+ Derivative(f(x), x), x, 3*sin(x))
463
+
464
+ # See issue 8510
465
+ assert f(x, x + z).diff(x) == (
466
+ Subs(Derivative(f(y, x + z), y), y, x) +
467
+ Subs(Derivative(f(x, y), y), y, x + z))
468
+ assert f(x, x**2).diff(x) == (
469
+ 2*x*Subs(Derivative(f(x, y), y), y, x**2) +
470
+ Subs(Derivative(f(y, x**2), y), y, x))
471
+ # but Subs is not always necessary
472
+ assert f(x, g(y)).diff(g(y)) == Derivative(f(x, g(y)), g(y))
473
+
474
+
475
+ def test_deriv2():
476
+ assert (x**3).diff(x) == 3*x**2
477
+ assert (x**3).diff(x, evaluate=False) != 3*x**2
478
+ assert (x**3).diff(x, evaluate=False) == Derivative(x**3, x)
479
+
480
+ assert diff(x**3, x) == 3*x**2
481
+ assert diff(x**3, x, evaluate=False) != 3*x**2
482
+ assert diff(x**3, x, evaluate=False) == Derivative(x**3, x)
483
+
484
+
485
+ def test_func_deriv():
486
+ assert f(x).diff(x) == Derivative(f(x), x)
487
+ # issue 4534
488
+ assert f(x, y).diff(x, y) - f(x, y).diff(y, x) == 0
489
+ assert Derivative(f(x, y), x, y).args[1:] == ((x, 1), (y, 1))
490
+ assert Derivative(f(x, y), y, x).args[1:] == ((y, 1), (x, 1))
491
+ assert (Derivative(f(x, y), x, y) - Derivative(f(x, y), y, x)).doit() == 0
492
+
493
+
494
+ def test_suppressed_evaluation():
495
+ a = sin(0, evaluate=False)
496
+ assert a != 0
497
+ assert a.func is sin
498
+ assert a.args == (0,)
499
+
500
+
501
+ def test_function_evalf():
502
+ def eq(a, b, eps):
503
+ return abs(a - b) < eps
504
+ assert eq(sin(1).evalf(15), Float("0.841470984807897"), 1e-13)
505
+ assert eq(
506
+ sin(2).evalf(25), Float("0.9092974268256816953960199", 25), 1e-23)
507
+ assert eq(sin(1 + I).evalf(
508
+ 15), Float("1.29845758141598") + Float("0.634963914784736")*I, 1e-13)
509
+ assert eq(exp(1 + I).evalf(15), Float(
510
+ "1.46869393991588") + Float("2.28735528717884239")*I, 1e-13)
511
+ assert eq(exp(-0.5 + 1.5*I).evalf(15), Float(
512
+ "0.0429042815937374") + Float("0.605011292285002")*I, 1e-13)
513
+ assert eq(log(pi + sqrt(2)*I).evalf(
514
+ 15), Float("1.23699044022052") + Float("0.422985442737893")*I, 1e-13)
515
+ assert eq(cos(100).evalf(15), Float("0.86231887228768"), 1e-13)
516
+
517
+
518
+ def test_extensibility_eval():
519
+ class MyFunc(Function):
520
+ @classmethod
521
+ def eval(cls, *args):
522
+ return (0, 0, 0)
523
+ assert MyFunc(0) == (0, 0, 0)
524
+
525
+
526
+ @_both_exp_pow
527
+ def test_function_non_commutative():
528
+ x = Symbol('x', commutative=False)
529
+ assert f(x).is_commutative is False
530
+ assert sin(x).is_commutative is False
531
+ assert exp(x).is_commutative is False
532
+ assert log(x).is_commutative is False
533
+ assert f(x).is_complex is False
534
+ assert sin(x).is_complex is False
535
+ assert exp(x).is_complex is False
536
+ assert log(x).is_complex is False
537
+
538
+
539
+ def test_function_complex():
540
+ x = Symbol('x', complex=True)
541
+ xzf = Symbol('x', complex=True, zero=False)
542
+ assert f(x).is_commutative is True
543
+ assert sin(x).is_commutative is True
544
+ assert exp(x).is_commutative is True
545
+ assert log(x).is_commutative is True
546
+ assert f(x).is_complex is None
547
+ assert sin(x).is_complex is True
548
+ assert exp(x).is_complex is True
549
+ assert log(x).is_complex is None
550
+ assert log(xzf).is_complex is True
551
+
552
+
553
+ def test_function__eval_nseries():
554
+ n = Symbol('n')
555
+
556
+ assert sin(x)._eval_nseries(x, 2, None) == x + O(x**2)
557
+ assert sin(x + 1)._eval_nseries(x, 2, None) == x*cos(1) + sin(1) + O(x**2)
558
+ assert sin(pi*(1 - x))._eval_nseries(x, 2, None) == pi*x + O(x**2)
559
+ assert acos(1 - x**2)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(x**2) + O(x**2)
560
+ assert polygamma(n, x + 1)._eval_nseries(x, 2, None) == \
561
+ polygamma(n, 1) + polygamma(n + 1, 1)*x + O(x**2)
562
+ raises(PoleError, lambda: sin(1/x)._eval_nseries(x, 2, None))
563
+ assert acos(1 - x)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(x) + sqrt(2)*x**(S(3)/2)/12 + O(x**2)
564
+ assert acos(1 + x)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(-x) + sqrt(2)*(-x)**(S(3)/2)/12 + O(x**2)
565
+ assert loggamma(1/x)._eval_nseries(x, 0, None) == \
566
+ log(x)/2 - log(x)/x - 1/x + O(1, x)
567
+ assert loggamma(log(1/x)).nseries(x, n=1, logx=y) == loggamma(-y)
568
+
569
+ # issue 6725:
570
+ assert expint(Rational(3, 2), -x)._eval_nseries(x, 5, None) == \
571
+ 2 - 2*sqrt(pi)*sqrt(-x) - 2*x + x**2 + x**3/3 + x**4/12 + 4*I*x**(S(3)/2)*sqrt(-x)/3 + \
572
+ 2*I*x**(S(5)/2)*sqrt(-x)/5 + 2*I*x**(S(7)/2)*sqrt(-x)/21 + O(x**5)
573
+ assert sin(sqrt(x))._eval_nseries(x, 3, None) == \
574
+ sqrt(x) - x**Rational(3, 2)/6 + x**Rational(5, 2)/120 + O(x**3)
575
+
576
+ # issue 19065:
577
+ s1 = f(x,y).series(y, n=2)
578
+ assert {i.name for i in s1.atoms(Symbol)} == {'x', 'xi', 'y'}
579
+ xi = Symbol('xi')
580
+ s2 = f(xi, y).series(y, n=2)
581
+ assert {i.name for i in s2.atoms(Symbol)} == {'xi', 'xi0', 'y'}
582
+
583
+ def test_doit():
584
+ n = Symbol('n', integer=True)
585
+ f = Sum(2 * n * x, (n, 1, 3))
586
+ d = Derivative(f, x)
587
+ assert d.doit() == 12
588
+ assert d.doit(deep=False) == Sum(2*n, (n, 1, 3))
589
+
590
+
591
+ def test_evalf_default():
592
+ from sympy.functions.special.gamma_functions import polygamma
593
+ assert type(sin(4.0)) == Float
594
+ assert type(re(sin(I + 1.0))) == Float
595
+ assert type(im(sin(I + 1.0))) == Float
596
+ assert type(sin(4)) == sin
597
+ assert type(polygamma(2.0, 4.0)) == Float
598
+ assert type(sin(Rational(1, 4))) == sin
599
+
600
+
601
+ def test_issue_5399():
602
+ args = [x, y, S(2), S.Half]
603
+
604
+ def ok(a):
605
+ """Return True if the input args for diff are ok"""
606
+ if not a:
607
+ return False
608
+ if a[0].is_Symbol is False:
609
+ return False
610
+ s_at = [i for i in range(len(a)) if a[i].is_Symbol]
611
+ n_at = [i for i in range(len(a)) if not a[i].is_Symbol]
612
+ # every symbol is followed by symbol or int
613
+ # every number is followed by a symbol
614
+ return (all(a[i + 1].is_Symbol or a[i + 1].is_Integer
615
+ for i in s_at if i + 1 < len(a)) and
616
+ all(a[i + 1].is_Symbol
617
+ for i in n_at if i + 1 < len(a)))
618
+ eq = x**10*y**8
619
+ for a in subsets(args):
620
+ for v in variations(a, len(a)):
621
+ if ok(v):
622
+ eq.diff(*v) # does not raise
623
+ else:
624
+ raises(ValueError, lambda: eq.diff(*v))
625
+
626
+
627
+ def test_derivative_numerically():
628
+ z0 = x._random()
629
+ assert abs(Derivative(sin(x), x).doit_numerically(z0) - cos(z0)) < 1e-15
630
+
631
+
632
+ def test_fdiff_argument_index_error():
633
+ from sympy.core.function import ArgumentIndexError
634
+
635
+ class myfunc(Function):
636
+ nargs = 1 # define since there is no eval routine
637
+
638
+ def fdiff(self, idx):
639
+ raise ArgumentIndexError
640
+ mf = myfunc(x)
641
+ assert mf.diff(x) == Derivative(mf, x)
642
+ raises(TypeError, lambda: myfunc(x, x))
643
+
644
+
645
+ def test_deriv_wrt_function():
646
+ x = f(t)
647
+ xd = diff(x, t)
648
+ xdd = diff(xd, t)
649
+ y = g(t)
650
+ yd = diff(y, t)
651
+
652
+ assert diff(x, t) == xd
653
+ assert diff(2 * x + 4, t) == 2 * xd
654
+ assert diff(2 * x + 4 + y, t) == 2 * xd + yd
655
+ assert diff(2 * x + 4 + y * x, t) == 2 * xd + x * yd + xd * y
656
+ assert diff(2 * x + 4 + y * x, x) == 2 + y
657
+ assert (diff(4 * x**2 + 3 * x + x * y, t) == 3 * xd + x * yd + xd * y +
658
+ 8 * x * xd)
659
+ assert (diff(4 * x**2 + 3 * xd + x * y, t) == 3 * xdd + x * yd + xd * y +
660
+ 8 * x * xd)
661
+ assert diff(4 * x**2 + 3 * xd + x * y, xd) == 3
662
+ assert diff(4 * x**2 + 3 * xd + x * y, xdd) == 0
663
+ assert diff(sin(x), t) == xd * cos(x)
664
+ assert diff(exp(x), t) == xd * exp(x)
665
+ assert diff(sqrt(x), t) == xd / (2 * sqrt(x))
666
+
667
+
668
+ def test_diff_wrt_value():
669
+ assert Expr()._diff_wrt is False
670
+ assert x._diff_wrt is True
671
+ assert f(x)._diff_wrt is True
672
+ assert Derivative(f(x), x)._diff_wrt is True
673
+ assert Derivative(x**2, x)._diff_wrt is False
674
+
675
+
676
+ def test_diff_wrt():
677
+ fx = f(x)
678
+ dfx = diff(f(x), x)
679
+ ddfx = diff(f(x), x, x)
680
+
681
+ assert diff(sin(fx) + fx**2, fx) == cos(fx) + 2*fx
682
+ assert diff(sin(dfx) + dfx**2, dfx) == cos(dfx) + 2*dfx
683
+ assert diff(sin(ddfx) + ddfx**2, ddfx) == cos(ddfx) + 2*ddfx
684
+ assert diff(fx**2, dfx) == 0
685
+ assert diff(fx**2, ddfx) == 0
686
+ assert diff(dfx**2, fx) == 0
687
+ assert diff(dfx**2, ddfx) == 0
688
+ assert diff(ddfx**2, dfx) == 0
689
+
690
+ assert diff(fx*dfx*ddfx, fx) == dfx*ddfx
691
+ assert diff(fx*dfx*ddfx, dfx) == fx*ddfx
692
+ assert diff(fx*dfx*ddfx, ddfx) == fx*dfx
693
+
694
+ assert diff(f(x), x).diff(f(x)) == 0
695
+ assert (sin(f(x)) - cos(diff(f(x), x))).diff(f(x)) == cos(f(x))
696
+
697
+ assert diff(sin(fx), fx, x) == diff(sin(fx), x, fx)
698
+
699
+ # Chain rule cases
700
+ assert f(g(x)).diff(x) == \
701
+ Derivative(g(x), x)*Derivative(f(g(x)), g(x))
702
+ assert diff(f(g(x), h(y)), x) == \
703
+ Derivative(g(x), x)*Derivative(f(g(x), h(y)), g(x))
704
+ assert diff(f(g(x), h(x)), x) == (
705
+ Derivative(f(g(x), h(x)), g(x))*Derivative(g(x), x) +
706
+ Derivative(f(g(x), h(x)), h(x))*Derivative(h(x), x))
707
+ assert f(
708
+ sin(x)).diff(x) == cos(x)*Subs(Derivative(f(x), x), x, sin(x))
709
+
710
+ assert diff(f(g(x)), g(x)) == Derivative(f(g(x)), g(x))
711
+
712
+
713
+ def test_diff_wrt_func_subs():
714
+ assert f(g(x)).diff(x).subs(g, Lambda(x, 2*x)).doit() == f(2*x).diff(x)
715
+
716
+
717
+ def test_subs_in_derivative():
718
+ expr = sin(x*exp(y))
719
+ u = Function('u')
720
+ v = Function('v')
721
+ assert Derivative(expr, y).subs(expr, y) == Derivative(y, y)
722
+ assert Derivative(expr, y).subs(y, x).doit() == \
723
+ Derivative(expr, y).doit().subs(y, x)
724
+ assert Derivative(f(x, y), y).subs(y, x) == Subs(Derivative(f(x, y), y), y, x)
725
+ assert Derivative(f(x, y), y).subs(x, y) == Subs(Derivative(f(x, y), y), x, y)
726
+ assert Derivative(f(x, y), y).subs(y, g(x, y)) == Subs(Derivative(f(x, y), y), y, g(x, y)).doit()
727
+ assert Derivative(f(x, y), y).subs(x, g(x, y)) == Subs(Derivative(f(x, y), y), x, g(x, y))
728
+ assert Derivative(f(x, y), g(y)).subs(x, g(x, y)) == Derivative(f(g(x, y), y), g(y))
729
+ assert Derivative(f(u(x), h(y)), h(y)).subs(h(y), g(x, y)) == \
730
+ Subs(Derivative(f(u(x), h(y)), h(y)), h(y), g(x, y)).doit()
731
+ assert Derivative(f(x, y), y).subs(y, z) == Derivative(f(x, z), z)
732
+ assert Derivative(f(x, y), y).subs(y, g(y)) == Derivative(f(x, g(y)), g(y))
733
+ assert Derivative(f(g(x), h(y)), h(y)).subs(h(y), u(y)) == \
734
+ Derivative(f(g(x), u(y)), u(y))
735
+ assert Derivative(f(x, f(x, x)), f(x, x)).subs(
736
+ f, Lambda((x, y), x + y)) == Subs(
737
+ Derivative(z + x, z), z, 2*x)
738
+ assert Subs(Derivative(f(f(x)), x), f, cos).doit() == sin(x)*sin(cos(x))
739
+ assert Subs(Derivative(f(f(x)), f(x)), f, cos).doit() == -sin(cos(x))
740
+ # Issue 13791. No comparison (it's a long formula) but this used to raise an exception.
741
+ assert isinstance(v(x, y, u(x, y)).diff(y).diff(x).diff(y), Expr)
742
+ # This is also related to issues 13791 and 13795; issue 15190
743
+ F = Lambda((x, y), exp(2*x + 3*y))
744
+ abstract = f(x, f(x, x)).diff(x, 2)
745
+ concrete = F(x, F(x, x)).diff(x, 2)
746
+ assert (abstract.subs(f, F).doit() - concrete).simplify() == 0
747
+ # don't introduce a new symbol if not necessary
748
+ assert x in f(x).diff(x).subs(x, 0).atoms()
749
+ # case (4)
750
+ assert Derivative(f(x,f(x,y)), x, y).subs(x, g(y)
751
+ ) == Subs(Derivative(f(x, f(x, y)), x, y), x, g(y))
752
+
753
+ assert Derivative(f(x, x), x).subs(x, 0
754
+ ) == Subs(Derivative(f(x, x), x), x, 0)
755
+ # issue 15194
756
+ assert Derivative(f(y, g(x)), (x, z)).subs(z, x
757
+ ) == Derivative(f(y, g(x)), (x, x))
758
+
759
+ df = f(x).diff(x)
760
+ assert df.subs(df, 1) is S.One
761
+ assert df.diff(df) is S.One
762
+ dxy = Derivative(f(x, y), x, y)
763
+ dyx = Derivative(f(x, y), y, x)
764
+ assert dxy.subs(Derivative(f(x, y), y, x), 1) is S.One
765
+ assert dxy.diff(dyx) is S.One
766
+ assert Derivative(f(x, y), x, 2, y, 3).subs(
767
+ dyx, g(x, y)) == Derivative(g(x, y), x, 1, y, 2)
768
+ assert Derivative(f(x, x - y), y).subs(x, x + y) == Subs(
769
+ Derivative(f(x, x - y), y), x, x + y)
770
+
771
+
772
+ def test_diff_wrt_not_allowed():
773
+ # issue 7027 included
774
+ for wrt in (
775
+ cos(x), re(x), x**2, x*y, 1 + x,
776
+ Derivative(cos(x), x), Derivative(f(f(x)), x)):
777
+ raises(ValueError, lambda: diff(f(x), wrt))
778
+ # if we don't differentiate wrt then don't raise error
779
+ assert diff(exp(x*y), x*y, 0) == exp(x*y)
780
+
781
+
782
+ def test_diff_wrt_intlike():
783
+ class Two:
784
+ def __int__(self):
785
+ return 2
786
+
787
+ assert cos(x).diff(x, Two()) == -cos(x)
788
+
789
+
790
+ def test_klein_gordon_lagrangian():
791
+ m = Symbol('m')
792
+ phi = f(x, t)
793
+
794
+ L = -(diff(phi, t)**2 - diff(phi, x)**2 - m**2*phi**2)/2
795
+ eqna = Eq(
796
+ diff(L, phi) - diff(L, diff(phi, x), x) - diff(L, diff(phi, t), t), 0)
797
+ eqnb = Eq(diff(phi, t, t) - diff(phi, x, x) + m**2*phi, 0)
798
+ assert eqna == eqnb
799
+
800
+
801
+ def test_sho_lagrangian():
802
+ m = Symbol('m')
803
+ k = Symbol('k')
804
+ x = f(t)
805
+
806
+ L = m*diff(x, t)**2/2 - k*x**2/2
807
+ eqna = Eq(diff(L, x), diff(L, diff(x, t), t))
808
+ eqnb = Eq(-k*x, m*diff(x, t, t))
809
+ assert eqna == eqnb
810
+
811
+ assert diff(L, x, t) == diff(L, t, x)
812
+ assert diff(L, diff(x, t), t) == m*diff(x, t, 2)
813
+ assert diff(L, t, diff(x, t)) == -k*x + m*diff(x, t, 2)
814
+
815
+
816
+ def test_straight_line():
817
+ F = f(x)
818
+ Fd = F.diff(x)
819
+ L = sqrt(1 + Fd**2)
820
+ assert diff(L, F) == 0
821
+ assert diff(L, Fd) == Fd/sqrt(1 + Fd**2)
822
+
823
+
824
+ def test_sort_variable():
825
+ vsort = Derivative._sort_variable_count
826
+ def vsort0(*v, reverse=False):
827
+ return [i[0] for i in vsort([(i, 0) for i in (
828
+ reversed(v) if reverse else v)])]
829
+
830
+ for R in range(2):
831
+ assert vsort0(y, x, reverse=R) == [x, y]
832
+ assert vsort0(f(x), x, reverse=R) == [x, f(x)]
833
+ assert vsort0(f(y), f(x), reverse=R) == [f(x), f(y)]
834
+ assert vsort0(g(x), f(y), reverse=R) == [f(y), g(x)]
835
+ assert vsort0(f(x, y), f(x), reverse=R) == [f(x), f(x, y)]
836
+ fx = f(x).diff(x)
837
+ assert vsort0(fx, y, reverse=R) == [y, fx]
838
+ fy = f(y).diff(y)
839
+ assert vsort0(fy, fx, reverse=R) == [fx, fy]
840
+ fxx = fx.diff(x)
841
+ assert vsort0(fxx, fx, reverse=R) == [fx, fxx]
842
+ assert vsort0(Basic(x), f(x), reverse=R) == [f(x), Basic(x)]
843
+ assert vsort0(Basic(y), Basic(x), reverse=R) == [Basic(x), Basic(y)]
844
+ assert vsort0(Basic(y, z), Basic(x), reverse=R) == [
845
+ Basic(x), Basic(y, z)]
846
+ assert vsort0(fx, x, reverse=R) == [
847
+ x, fx] if R else [fx, x]
848
+ assert vsort0(Basic(x), x, reverse=R) == [
849
+ x, Basic(x)] if R else [Basic(x), x]
850
+ assert vsort0(Basic(f(x)), f(x), reverse=R) == [
851
+ f(x), Basic(f(x))] if R else [Basic(f(x)), f(x)]
852
+ assert vsort0(Basic(x, z), Basic(x), reverse=R) == [
853
+ Basic(x), Basic(x, z)] if R else [Basic(x, z), Basic(x)]
854
+ assert vsort([]) == []
855
+ assert _aresame(vsort([(x, 1)]), [Tuple(x, 1)])
856
+ assert vsort([(x, y), (x, z)]) == [(x, y + z)]
857
+ assert vsort([(y, 1), (x, 1 + y)]) == [(x, 1 + y), (y, 1)]
858
+ # coverage complete; legacy tests below
859
+ assert vsort([(x, 3), (y, 2), (z, 1)]) == [(x, 3), (y, 2), (z, 1)]
860
+ assert vsort([(h(x), 1), (g(x), 1), (f(x), 1)]) == [
861
+ (f(x), 1), (g(x), 1), (h(x), 1)]
862
+ assert vsort([(z, 1), (y, 2), (x, 3), (h(x), 1), (g(x), 1),
863
+ (f(x), 1)]) == [(x, 3), (y, 2), (z, 1), (f(x), 1), (g(x), 1),
864
+ (h(x), 1)]
865
+ assert vsort([(x, 1), (f(x), 1), (y, 1), (f(y), 1)]) == [(x, 1),
866
+ (y, 1), (f(x), 1), (f(y), 1)]
867
+ assert vsort([(y, 1), (x, 2), (g(x), 1), (f(x), 1), (z, 1),
868
+ (h(x), 1), (y, 2), (x, 1)]) == [(x, 3), (y, 3), (z, 1),
869
+ (f(x), 1), (g(x), 1), (h(x), 1)]
870
+ assert vsort([(z, 1), (y, 1), (f(x), 1), (x, 1), (f(x), 1),
871
+ (g(x), 1)]) == [(x, 1), (y, 1), (z, 1), (f(x), 2), (g(x), 1)]
872
+ assert vsort([(z, 1), (y, 2), (f(x), 1), (x, 2), (f(x), 2),
873
+ (g(x), 1), (z, 2), (z, 1), (y, 1), (x, 1)]) == [(x, 3), (y, 3),
874
+ (z, 4), (f(x), 3), (g(x), 1)]
875
+ assert vsort(((y, 2), (x, 1), (y, 1), (x, 1))) == [(x, 2), (y, 3)]
876
+ assert isinstance(vsort([(x, 3), (y, 2), (z, 1)])[0], Tuple)
877
+ assert vsort([(x, 1), (f(x), 1), (x, 1)]) == [(x, 2), (f(x), 1)]
878
+ assert vsort([(y, 2), (x, 3), (z, 1)]) == [(x, 3), (y, 2), (z, 1)]
879
+ assert vsort([(h(y), 1), (g(x), 1), (f(x), 1)]) == [
880
+ (f(x), 1), (g(x), 1), (h(y), 1)]
881
+ assert vsort([(x, 1), (y, 1), (x, 1)]) == [(x, 2), (y, 1)]
882
+ assert vsort([(f(x), 1), (f(y), 1), (f(x), 1)]) == [
883
+ (f(x), 2), (f(y), 1)]
884
+ dfx = f(x).diff(x)
885
+ self = [(dfx, 1), (x, 1)]
886
+ assert vsort(self) == self
887
+ assert vsort([
888
+ (dfx, 1), (y, 1), (f(x), 1), (x, 1), (f(y), 1), (x, 1)]) == [
889
+ (y, 1), (f(x), 1), (f(y), 1), (dfx, 1), (x, 2)]
890
+ dfy = f(y).diff(y)
891
+ assert vsort([(dfy, 1), (dfx, 1)]) == [(dfx, 1), (dfy, 1)]
892
+ d2fx = dfx.diff(x)
893
+ assert vsort([(d2fx, 1), (dfx, 1)]) == [(dfx, 1), (d2fx, 1)]
894
+
895
+
896
+ def test_multiple_derivative():
897
+ # Issue #15007
898
+ assert f(x, y).diff(y, y, x, y, x
899
+ ) == Derivative(f(x, y), (x, 2), (y, 3))
900
+
901
+
902
+ def test_unhandled():
903
+ class MyExpr(Expr):
904
+ def _eval_derivative(self, s):
905
+ if not s.name.startswith('xi'):
906
+ return self
907
+ else:
908
+ return None
909
+
910
+ eq = MyExpr(f(x), y, z)
911
+ assert diff(eq, x, y, f(x), z) == Derivative(eq, f(x))
912
+ assert diff(eq, f(x), x) == Derivative(eq, f(x))
913
+ assert f(x, y).diff(x,(y, z)) == Derivative(f(x, y), x, (y, z))
914
+ assert f(x, y).diff(x,(y, 0)) == Derivative(f(x, y), x)
915
+
916
+
917
+ def test_nfloat():
918
+ from sympy.core.basic import _aresame
919
+ from sympy.polys.rootoftools import rootof
920
+
921
+ x = Symbol("x")
922
+ eq = x**Rational(4, 3) + 4*x**(S.One/3)/3
923
+ assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(S.One/3))
924
+ assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3))
925
+ eq = x**Rational(4, 3) + 4*x**(x/3)/3
926
+ assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(x/3))
927
+ big = 12345678901234567890
928
+ # specify precision to match value used in nfloat
929
+ Float_big = Float(big, 15)
930
+ assert _aresame(nfloat(big), Float_big)
931
+ assert _aresame(nfloat(big*x), Float_big*x)
932
+ assert _aresame(nfloat(x**big, exponent=True), x**Float_big)
933
+ assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2)))
934
+
935
+ # issue 6342
936
+ f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4')
937
+ assert not any(a.free_symbols for a in solveset(f.subs(x, -0.139)))
938
+
939
+ # issue 6632
940
+ assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \
941
+ 9.99999999800000e-11
942
+
943
+ # issue 7122
944
+ eq = cos(3*x**4 + y)*rootof(x**5 + 3*x**3 + 1, 0)
945
+ assert str(nfloat(eq, exponent=False, n=1)) == '-0.7*cos(3.0*x**4 + y)'
946
+
947
+ # issue 10933
948
+ for ti in (dict, Dict):
949
+ d = ti({S.Half: S.Half})
950
+ n = nfloat(d)
951
+ assert isinstance(n, ti)
952
+ assert _aresame(list(n.items()).pop(), (S.Half, Float(.5)))
953
+ for ti in (dict, Dict):
954
+ d = ti({S.Half: S.Half})
955
+ n = nfloat(d, dkeys=True)
956
+ assert isinstance(n, ti)
957
+ assert _aresame(list(n.items()).pop(), (Float(.5), Float(.5)))
958
+ d = [S.Half]
959
+ n = nfloat(d)
960
+ assert type(n) is list
961
+ assert _aresame(n[0], Float(.5))
962
+ assert _aresame(nfloat(Eq(x, S.Half)).rhs, Float(.5))
963
+ assert _aresame(nfloat(S(True)), S(True))
964
+ assert _aresame(nfloat(Tuple(S.Half))[0], Float(.5))
965
+ assert nfloat(Eq((3 - I)**2/2 + I, 0)) == S.false
966
+ # pass along kwargs
967
+ assert nfloat([{S.Half: x}], dkeys=True) == [{Float(0.5): x}]
968
+
969
+ # Issue 17706
970
+ A = MutableMatrix([[1, 2], [3, 4]])
971
+ B = MutableMatrix(
972
+ [[Float('1.0', precision=53), Float('2.0', precision=53)],
973
+ [Float('3.0', precision=53), Float('4.0', precision=53)]])
974
+ assert _aresame(nfloat(A), B)
975
+ A = ImmutableMatrix([[1, 2], [3, 4]])
976
+ B = ImmutableMatrix(
977
+ [[Float('1.0', precision=53), Float('2.0', precision=53)],
978
+ [Float('3.0', precision=53), Float('4.0', precision=53)]])
979
+ assert _aresame(nfloat(A), B)
980
+
981
+ # issue 22524
982
+ f = Function('f')
983
+ assert not nfloat(f(2)).atoms(Float)
984
+
985
+
986
+ def test_issue_7068():
987
+ from sympy.abc import a, b
988
+ f = Function('f')
989
+ y1 = Dummy('y')
990
+ y2 = Dummy('y')
991
+ func1 = f(a + y1 * b)
992
+ func2 = f(a + y2 * b)
993
+ func1_y = func1.diff(y1)
994
+ func2_y = func2.diff(y2)
995
+ assert func1_y != func2_y
996
+ z1 = Subs(f(a), a, y1)
997
+ z2 = Subs(f(a), a, y2)
998
+ assert z1 != z2
999
+
1000
+
1001
+ def test_issue_7231():
1002
+ from sympy.abc import a
1003
+ ans1 = f(x).series(x, a)
1004
+ res = (f(a) + (-a + x)*Subs(Derivative(f(y), y), y, a) +
1005
+ (-a + x)**2*Subs(Derivative(f(y), y, y), y, a)/2 +
1006
+ (-a + x)**3*Subs(Derivative(f(y), y, y, y),
1007
+ y, a)/6 +
1008
+ (-a + x)**4*Subs(Derivative(f(y), y, y, y, y),
1009
+ y, a)/24 +
1010
+ (-a + x)**5*Subs(Derivative(f(y), y, y, y, y, y),
1011
+ y, a)/120 + O((-a + x)**6, (x, a)))
1012
+ assert res == ans1
1013
+ ans2 = f(x).series(x, a)
1014
+ assert res == ans2
1015
+
1016
+
1017
+ def test_issue_7687():
1018
+ from sympy.core.function import Function
1019
+ from sympy.abc import x
1020
+ f = Function('f')(x)
1021
+ ff = Function('f')(x)
1022
+ match_with_cache = ff.matches(f)
1023
+ assert isinstance(f, type(ff))
1024
+ clear_cache()
1025
+ ff = Function('f')(x)
1026
+ assert isinstance(f, type(ff))
1027
+ assert match_with_cache == ff.matches(f)
1028
+
1029
+
1030
+ def test_issue_7688():
1031
+ from sympy.core.function import Function, UndefinedFunction
1032
+
1033
+ f = Function('f') # actually an UndefinedFunction
1034
+ clear_cache()
1035
+ class A(UndefinedFunction):
1036
+ pass
1037
+ a = A('f')
1038
+ assert isinstance(a, type(f))
1039
+
1040
+
1041
+ def test_mexpand():
1042
+ from sympy.abc import x
1043
+ assert _mexpand(None) is None
1044
+ assert _mexpand(1) is S.One
1045
+ assert _mexpand(x*(x + 1)**2) == (x*(x + 1)**2).expand()
1046
+
1047
+
1048
+ def test_issue_8469():
1049
+ # This should not take forever to run
1050
+ N = 40
1051
+ def g(w, theta):
1052
+ return 1/(1+exp(w-theta))
1053
+
1054
+ ws = symbols(['w%i'%i for i in range(N)])
1055
+ import functools
1056
+ expr = functools.reduce(g, ws)
1057
+ assert isinstance(expr, Pow)
1058
+
1059
+
1060
+ def test_issue_12996():
1061
+ # foo=True imitates the sort of arguments that Derivative can get
1062
+ # from Integral when it passes doit to the expression
1063
+ assert Derivative(im(x), x).doit(foo=True) == Derivative(im(x), x)
1064
+
1065
+
1066
+ def test_should_evalf():
1067
+ # This should not take forever to run (see #8506)
1068
+ assert isinstance(sin((1.0 + 1.0*I)**10000 + 1), sin)
1069
+
1070
+
1071
+ def test_Derivative_as_finite_difference():
1072
+ # Central 1st derivative at gridpoint
1073
+ x, h = symbols('x h', real=True)
1074
+ dfdx = f(x).diff(x)
1075
+ assert (dfdx.as_finite_difference([x-2, x-1, x, x+1, x+2]) -
1076
+ (S.One/12*(f(x-2)-f(x+2)) + Rational(2, 3)*(f(x+1)-f(x-1)))).simplify() == 0
1077
+
1078
+ # Central 1st derivative "half-way"
1079
+ assert (dfdx.as_finite_difference() -
1080
+ (f(x + S.Half)-f(x - S.Half))).simplify() == 0
1081
+ assert (dfdx.as_finite_difference(h) -
1082
+ (f(x + h/S(2))-f(x - h/S(2)))/h).simplify() == 0
1083
+ assert (dfdx.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) -
1084
+ (S(9)/(8*2*h)*(f(x+h) - f(x-h)) +
1085
+ S.One/(24*2*h)*(f(x - 3*h) - f(x + 3*h)))).simplify() == 0
1086
+
1087
+ # One sided 1st derivative at gridpoint
1088
+ assert (dfdx.as_finite_difference([0, 1, 2], 0) -
1089
+ (Rational(-3, 2)*f(0) + 2*f(1) - f(2)/2)).simplify() == 0
1090
+ assert (dfdx.as_finite_difference([x, x+h], x) -
1091
+ (f(x+h) - f(x))/h).simplify() == 0
1092
+ assert (dfdx.as_finite_difference([x-h, x, x+h], x-h) -
1093
+ (-S(3)/(2*h)*f(x-h) + 2/h*f(x) -
1094
+ S.One/(2*h)*f(x+h))).simplify() == 0
1095
+
1096
+ # One sided 1st derivative "half-way"
1097
+ assert (dfdx.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h, x + 7*h])
1098
+ - 1/(2*h)*(-S(11)/(12)*f(x-h) + S(17)/(24)*f(x+h)
1099
+ + Rational(3, 8)*f(x + 3*h) - Rational(5, 24)*f(x + 5*h)
1100
+ + S.One/24*f(x + 7*h))).simplify() == 0
1101
+
1102
+ d2fdx2 = f(x).diff(x, 2)
1103
+ # Central 2nd derivative at gridpoint
1104
+ assert (d2fdx2.as_finite_difference([x-h, x, x+h]) -
1105
+ h**-2 * (f(x-h) + f(x+h) - 2*f(x))).simplify() == 0
1106
+
1107
+ assert (d2fdx2.as_finite_difference([x - 2*h, x-h, x, x+h, x + 2*h]) -
1108
+ h**-2 * (Rational(-1, 12)*(f(x - 2*h) + f(x + 2*h)) +
1109
+ Rational(4, 3)*(f(x+h) + f(x-h)) - Rational(5, 2)*f(x))).simplify() == 0
1110
+
1111
+ # Central 2nd derivative "half-way"
1112
+ assert (d2fdx2.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) -
1113
+ (2*h)**-2 * (S.Half*(f(x - 3*h) + f(x + 3*h)) -
1114
+ S.Half*(f(x+h) + f(x-h)))).simplify() == 0
1115
+
1116
+ # One sided 2nd derivative at gridpoint
1117
+ assert (d2fdx2.as_finite_difference([x, x+h, x + 2*h, x + 3*h]) -
1118
+ h**-2 * (2*f(x) - 5*f(x+h) +
1119
+ 4*f(x+2*h) - f(x+3*h))).simplify() == 0
1120
+
1121
+ # One sided 2nd derivative at "half-way"
1122
+ assert (d2fdx2.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h]) -
1123
+ (2*h)**-2 * (Rational(3, 2)*f(x-h) - Rational(7, 2)*f(x+h) + Rational(5, 2)*f(x + 3*h) -
1124
+ S.Half*f(x + 5*h))).simplify() == 0
1125
+
1126
+ d3fdx3 = f(x).diff(x, 3)
1127
+ # Central 3rd derivative at gridpoint
1128
+ assert (d3fdx3.as_finite_difference() -
1129
+ (-f(x - Rational(3, 2)) + 3*f(x - S.Half) -
1130
+ 3*f(x + S.Half) + f(x + Rational(3, 2)))).simplify() == 0
1131
+
1132
+ assert (d3fdx3.as_finite_difference(
1133
+ [x - 3*h, x - 2*h, x-h, x, x+h, x + 2*h, x + 3*h]) -
1134
+ h**-3 * (S.One/8*(f(x - 3*h) - f(x + 3*h)) - f(x - 2*h) +
1135
+ f(x + 2*h) + Rational(13, 8)*(f(x-h) - f(x+h)))).simplify() == 0
1136
+
1137
+ # Central 3rd derivative at "half-way"
1138
+ assert (d3fdx3.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) -
1139
+ (2*h)**-3 * (f(x + 3*h)-f(x - 3*h) +
1140
+ 3*(f(x-h)-f(x+h)))).simplify() == 0
1141
+
1142
+ # One sided 3rd derivative at gridpoint
1143
+ assert (d3fdx3.as_finite_difference([x, x+h, x + 2*h, x + 3*h]) -
1144
+ h**-3 * (f(x + 3*h)-f(x) + 3*(f(x+h)-f(x + 2*h)))).simplify() == 0
1145
+
1146
+ # One sided 3rd derivative at "half-way"
1147
+ assert (d3fdx3.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h]) -
1148
+ (2*h)**-3 * (f(x + 5*h)-f(x-h) +
1149
+ 3*(f(x+h)-f(x + 3*h)))).simplify() == 0
1150
+
1151
+ # issue 11007
1152
+ y = Symbol('y', real=True)
1153
+ d2fdxdy = f(x, y).diff(x, y)
1154
+
1155
+ ref0 = Derivative(f(x + S.Half, y), y) - Derivative(f(x - S.Half, y), y)
1156
+ assert (d2fdxdy.as_finite_difference(wrt=x) - ref0).simplify() == 0
1157
+
1158
+ half = S.Half
1159
+ xm, xp, ym, yp = x-half, x+half, y-half, y+half
1160
+ ref2 = f(xm, ym) + f(xp, yp) - f(xp, ym) - f(xm, yp)
1161
+ assert (d2fdxdy.as_finite_difference() - ref2).simplify() == 0
1162
+
1163
+
1164
+ def test_issue_11159():
1165
+ # Tests Application._eval_subs
1166
+ with _exp_is_pow(False):
1167
+ expr1 = E
1168
+ expr0 = expr1 * expr1
1169
+ expr1 = expr0.subs(expr1,expr0)
1170
+ assert expr0 == expr1
1171
+ with _exp_is_pow(True):
1172
+ expr1 = E
1173
+ expr0 = expr1 * expr1
1174
+ expr2 = expr0.subs(expr1, expr0)
1175
+ assert expr2 == E ** 4
1176
+
1177
+
1178
+ def test_issue_12005():
1179
+ e1 = Subs(Derivative(f(x), x), x, x)
1180
+ assert e1.diff(x) == Derivative(f(x), x, x)
1181
+ e2 = Subs(Derivative(f(x), x), x, x**2 + 1)
1182
+ assert e2.diff(x) == 2*x*Subs(Derivative(f(x), x, x), x, x**2 + 1)
1183
+ e3 = Subs(Derivative(f(x) + y**2 - y, y), y, y**2)
1184
+ assert e3.diff(y) == 4*y
1185
+ e4 = Subs(Derivative(f(x + y), y), y, (x**2))
1186
+ assert e4.diff(y) is S.Zero
1187
+ e5 = Subs(Derivative(f(x), x), (y, z), (y, z))
1188
+ assert e5.diff(x) == Derivative(f(x), x, x)
1189
+ assert f(g(x)).diff(g(x), g(x)) == Derivative(f(g(x)), g(x), g(x))
1190
+
1191
+
1192
+ def test_issue_13843():
1193
+ x = symbols('x')
1194
+ f = Function('f')
1195
+ m, n = symbols('m n', integer=True)
1196
+ assert Derivative(Derivative(f(x), (x, m)), (x, n)) == Derivative(f(x), (x, m + n))
1197
+ assert Derivative(Derivative(f(x), (x, m+5)), (x, n+3)) == Derivative(f(x), (x, m + n + 8))
1198
+
1199
+ assert Derivative(f(x), (x, n)).doit() == Derivative(f(x), (x, n))
1200
+
1201
+
1202
+ def test_order_could_be_zero():
1203
+ x, y = symbols('x, y')
1204
+ n = symbols('n', integer=True, nonnegative=True)
1205
+ m = symbols('m', integer=True, positive=True)
1206
+ assert diff(y, (x, n)) == Piecewise((y, Eq(n, 0)), (0, True))
1207
+ assert diff(y, (x, n + 1)) is S.Zero
1208
+ assert diff(y, (x, m)) is S.Zero
1209
+
1210
+
1211
+ def test_undefined_function_eq():
1212
+ f = Function('f')
1213
+ f2 = Function('f')
1214
+ g = Function('g')
1215
+ f_real = Function('f', is_real=True)
1216
+
1217
+ # This test may only be meaningful if the cache is turned off
1218
+ assert f == f2
1219
+ assert hash(f) == hash(f2)
1220
+ assert f == f
1221
+
1222
+ assert f != g
1223
+
1224
+ assert f != f_real
1225
+
1226
+
1227
+ def test_function_assumptions():
1228
+ x = Symbol('x')
1229
+ f = Function('f')
1230
+ f_real = Function('f', real=True)
1231
+ f_real1 = Function('f', real=1)
1232
+ f_real_inherit = Function(Symbol('f', real=True))
1233
+
1234
+ assert f_real == f_real1 # assumptions are sanitized
1235
+ assert f != f_real
1236
+ assert f(x) != f_real(x)
1237
+
1238
+ assert f(x).is_real is None
1239
+ assert f_real(x).is_real is True
1240
+ assert f_real_inherit(x).is_real is True and f_real_inherit.name == 'f'
1241
+
1242
+ # Can also do it this way, but it won't be equal to f_real because of the
1243
+ # way UndefinedFunction.__new__ works. Any non-recognized assumptions
1244
+ # are just added literally as something which is used in the hash
1245
+ f_real2 = Function('f', is_real=True)
1246
+ assert f_real2(x).is_real is True
1247
+
1248
+
1249
+ def test_undef_fcn_float_issue_6938():
1250
+ f = Function('ceil')
1251
+ assert not f(0.3).is_number
1252
+ f = Function('sin')
1253
+ assert not f(0.3).is_number
1254
+ assert not f(pi).evalf().is_number
1255
+ x = Symbol('x')
1256
+ assert not f(x).evalf(subs={x:1.2}).is_number
1257
+
1258
+
1259
+ def test_undefined_function_eval():
1260
+ # Issue 15170. Make sure UndefinedFunction with eval defined works
1261
+ # properly.
1262
+
1263
+ fdiff = lambda self, argindex=1: cos(self.args[argindex - 1])
1264
+ eval = classmethod(lambda cls, t: None)
1265
+ _imp_ = classmethod(lambda cls, t: sin(t))
1266
+
1267
+ temp = Function('temp', fdiff=fdiff, eval=eval, _imp_=_imp_)
1268
+
1269
+ expr = temp(t)
1270
+ assert sympify(expr) == expr
1271
+ assert type(sympify(expr)).fdiff.__name__ == "<lambda>"
1272
+ assert expr.diff(t) == cos(t)
1273
+
1274
+
1275
+ def test_issue_15241():
1276
+ F = f(x)
1277
+ Fx = F.diff(x)
1278
+ assert (F + x*Fx).diff(x, Fx) == 2
1279
+ assert (F + x*Fx).diff(Fx, x) == 1
1280
+ assert (x*F + x*Fx*F).diff(F, x) == x*Fx.diff(x) + Fx + 1
1281
+ assert (x*F + x*Fx*F).diff(x, F) == x*Fx.diff(x) + Fx + 1
1282
+ y = f(x)
1283
+ G = f(y)
1284
+ Gy = G.diff(y)
1285
+ assert (G + y*Gy).diff(y, Gy) == 2
1286
+ assert (G + y*Gy).diff(Gy, y) == 1
1287
+ assert (y*G + y*Gy*G).diff(G, y) == y*Gy.diff(y) + Gy + 1
1288
+ assert (y*G + y*Gy*G).diff(y, G) == y*Gy.diff(y) + Gy + 1
1289
+
1290
+
1291
+ def test_issue_15226():
1292
+ assert Subs(Derivative(f(y), x, y), y, g(x)).doit() != 0
1293
+
1294
+
1295
+ def test_issue_7027():
1296
+ for wrt in (cos(x), re(x), Derivative(cos(x), x)):
1297
+ raises(ValueError, lambda: diff(f(x), wrt))
1298
+
1299
+
1300
+ def test_derivative_quick_exit():
1301
+ assert f(x).diff(y) == 0
1302
+ assert f(x).diff(y, f(x)) == 0
1303
+ assert f(x).diff(x, f(y)) == 0
1304
+ assert f(f(x)).diff(x, f(x), f(y)) == 0
1305
+ assert f(f(x)).diff(x, f(x), y) == 0
1306
+ assert f(x).diff(g(x)) == 0
1307
+ assert f(x).diff(x, f(x).diff(x)) == 1
1308
+ df = f(x).diff(x)
1309
+ assert f(x).diff(df) == 0
1310
+ dg = g(x).diff(x)
1311
+ assert dg.diff(df).doit() == 0
1312
+
1313
+
1314
+ def test_issue_15084_13166():
1315
+ eq = f(x, g(x))
1316
+ assert eq.diff((g(x), y)) == Derivative(f(x, g(x)), (g(x), y))
1317
+ # issue 13166
1318
+ assert eq.diff(x, 2).doit() == (
1319
+ (Derivative(f(x, g(x)), (g(x), 2))*Derivative(g(x), x) +
1320
+ Subs(Derivative(f(x, _xi_2), _xi_2, x), _xi_2, g(x)))*Derivative(g(x),
1321
+ x) + Derivative(f(x, g(x)), g(x))*Derivative(g(x), (x, 2)) +
1322
+ Derivative(g(x), x)*Subs(Derivative(f(_xi_1, g(x)), _xi_1, g(x)),
1323
+ _xi_1, x) + Subs(Derivative(f(_xi_1, g(x)), (_xi_1, 2)), _xi_1, x))
1324
+ # issue 6681
1325
+ assert diff(f(x, t, g(x, t)), x).doit() == (
1326
+ Derivative(f(x, t, g(x, t)), g(x, t))*Derivative(g(x, t), x) +
1327
+ Subs(Derivative(f(_xi_1, t, g(x, t)), _xi_1), _xi_1, x))
1328
+ # make sure the order doesn't matter when using diff
1329
+ assert eq.diff(x, g(x)) == eq.diff(g(x), x)
1330
+
1331
+
1332
+ def test_negative_counts():
1333
+ # issue 13873
1334
+ raises(ValueError, lambda: sin(x).diff(x, -1))
1335
+
1336
+
1337
+ def test_Derivative__new__():
1338
+ raises(TypeError, lambda: f(x).diff((x, 2), 0))
1339
+ assert f(x, y).diff([(x, y), 0]) == f(x, y)
1340
+ assert f(x, y).diff([(x, y), 1]) == NDimArray([
1341
+ Derivative(f(x, y), x), Derivative(f(x, y), y)])
1342
+ assert f(x,y).diff(y, (x, z), y, x) == Derivative(
1343
+ f(x, y), (x, z + 1), (y, 2))
1344
+ assert Matrix([x]).diff(x, 2) == Matrix([0]) # is_zero exit
1345
+
1346
+
1347
+ def test_issue_14719_10150():
1348
+ class V(Expr):
1349
+ _diff_wrt = True
1350
+ is_scalar = False
1351
+ assert V().diff(V()) == Derivative(V(), V())
1352
+ assert (2*V()).diff(V()) == 2*Derivative(V(), V())
1353
+ class X(Expr):
1354
+ _diff_wrt = True
1355
+ assert X().diff(X()) == 1
1356
+ assert (2*X()).diff(X()) == 2
1357
+
1358
+
1359
+ def test_noncommutative_issue_15131():
1360
+ x = Symbol('x', commutative=False)
1361
+ t = Symbol('t', commutative=False)
1362
+ fx = Function('Fx', commutative=False)(x)
1363
+ ft = Function('Ft', commutative=False)(t)
1364
+ A = Symbol('A', commutative=False)
1365
+ eq = fx * A * ft
1366
+ eqdt = eq.diff(t)
1367
+ assert eqdt.args[-1] == ft.diff(t)
1368
+
1369
+
1370
+ def test_Subs_Derivative():
1371
+ a = Derivative(f(g(x), h(x)), g(x), h(x),x)
1372
+ b = Derivative(Derivative(f(g(x), h(x)), g(x), h(x)),x)
1373
+ c = f(g(x), h(x)).diff(g(x), h(x), x)
1374
+ d = f(g(x), h(x)).diff(g(x), h(x)).diff(x)
1375
+ e = Derivative(f(g(x), h(x)), x)
1376
+ eqs = (a, b, c, d, e)
1377
+ subs = lambda arg: arg.subs(f, Lambda((x, y), exp(x + y))
1378
+ ).subs(g(x), 1/x).subs(h(x), x**3)
1379
+ ans = 3*x**2*exp(1/x)*exp(x**3) - exp(1/x)*exp(x**3)/x**2
1380
+ assert all(subs(i).doit().expand() == ans for i in eqs)
1381
+ assert all(subs(i.doit()).doit().expand() == ans for i in eqs)
1382
+
1383
+ def test_issue_15360():
1384
+ f = Function('f')
1385
+ assert f.name == 'f'
1386
+
1387
+
1388
+ def test_issue_15947():
1389
+ assert f._diff_wrt is False
1390
+ raises(TypeError, lambda: f(f))
1391
+ raises(TypeError, lambda: f(x).diff(f))
1392
+
1393
+
1394
+ def test_Derivative_free_symbols():
1395
+ f = Function('f')
1396
+ n = Symbol('n', integer=True, positive=True)
1397
+ assert diff(f(x), (x, n)).free_symbols == {n, x}
1398
+
1399
+
1400
+ def test_issue_20683():
1401
+ x = Symbol('x')
1402
+ y = Symbol('y')
1403
+ z = Symbol('z')
1404
+ y = Derivative(z, x).subs(x,0)
1405
+ assert y.doit() == 0
1406
+ y = Derivative(8, x).subs(x,0)
1407
+ assert y.doit() == 0
1408
+
1409
+
1410
+ def test_issue_10503():
1411
+ f = exp(x**3)*cos(x**6)
1412
+ assert f.series(x, 0, 14) == 1 + x**3 + x**6/2 + x**9/6 - 11*x**12/24 + O(x**14)
1413
+
1414
+
1415
+ def test_issue_17382():
1416
+ # copied from sympy/core/tests/test_evalf.py
1417
+ def NS(e, n=15, **options):
1418
+ return sstr(sympify(e).evalf(n, **options), full_prec=True)
1419
+
1420
+ x = Symbol('x')
1421
+ expr = solveset(2 * cos(x) * cos(2 * x) - 1, x, S.Reals)
1422
+ expected = "Union(" \
1423
+ "ImageSet(Lambda(_n, 6.28318530717959*_n + 5.79812359592087), Integers), " \
1424
+ "ImageSet(Lambda(_n, 6.28318530717959*_n + 0.485061711258717), Integers))"
1425
+ assert NS(expr) == expected
1426
+
1427
+ def test_eval_sympified():
1428
+ # Check both arguments and return types from eval are sympified
1429
+
1430
+ class F(Function):
1431
+ @classmethod
1432
+ def eval(cls, x):
1433
+ assert x is S.One
1434
+ return 1
1435
+
1436
+ assert F(1) is S.One
1437
+
1438
+ # String arguments are not allowed
1439
+ class F2(Function):
1440
+ @classmethod
1441
+ def eval(cls, x):
1442
+ if x == 0:
1443
+ return '1'
1444
+
1445
+ raises(SympifyError, lambda: F2(0))
1446
+ F2(1) # Doesn't raise
1447
+
1448
+ # TODO: Disable string inputs (https://github.com/sympy/sympy/issues/11003)
1449
+ # raises(SympifyError, lambda: F2('2'))
1450
+
1451
+ def test_eval_classmethod_check():
1452
+ with raises(TypeError):
1453
+ class F(Function):
1454
+ def eval(self, x):
1455
+ pass
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_kind.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.add import Add
2
+ from sympy.core.kind import NumberKind, UndefinedKind
3
+ from sympy.core.mul import Mul
4
+ from sympy.core.numbers import pi, zoo, I, AlgebraicNumber
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import Symbol
7
+ from sympy.integrals.integrals import Integral
8
+ from sympy.core.function import Derivative
9
+ from sympy.matrices import (Matrix, SparseMatrix, ImmutableMatrix,
10
+ ImmutableSparseMatrix, MatrixSymbol, MatrixKind, MatMul)
11
+
12
+ comm_x = Symbol('x')
13
+ noncomm_x = Symbol('x', commutative=False)
14
+
15
+ def test_NumberKind():
16
+ assert S.One.kind is NumberKind
17
+ assert pi.kind is NumberKind
18
+ assert S.NaN.kind is NumberKind
19
+ assert zoo.kind is NumberKind
20
+ assert I.kind is NumberKind
21
+ assert AlgebraicNumber(1).kind is NumberKind
22
+
23
+ def test_Add_kind():
24
+ assert Add(2, 3, evaluate=False).kind is NumberKind
25
+ assert Add(2,comm_x).kind is NumberKind
26
+ assert Add(2,noncomm_x).kind is UndefinedKind
27
+
28
+ def test_mul_kind():
29
+ assert Mul(2,comm_x, evaluate=False).kind is NumberKind
30
+ assert Mul(2,3, evaluate=False).kind is NumberKind
31
+ assert Mul(noncomm_x,2, evaluate=False).kind is UndefinedKind
32
+ assert Mul(2,noncomm_x, evaluate=False).kind is UndefinedKind
33
+
34
+ def test_Symbol_kind():
35
+ assert comm_x.kind is NumberKind
36
+ assert noncomm_x.kind is UndefinedKind
37
+
38
+ def test_Integral_kind():
39
+ A = MatrixSymbol('A', 2,2)
40
+ assert Integral(comm_x, comm_x).kind is NumberKind
41
+ assert Integral(A, comm_x).kind is MatrixKind(NumberKind)
42
+
43
+ def test_Derivative_kind():
44
+ A = MatrixSymbol('A', 2,2)
45
+ assert Derivative(comm_x, comm_x).kind is NumberKind
46
+ assert Derivative(A, comm_x).kind is MatrixKind(NumberKind)
47
+
48
+ def test_Matrix_kind():
49
+ classes = (Matrix, SparseMatrix, ImmutableMatrix, ImmutableSparseMatrix)
50
+ for cls in classes:
51
+ m = cls.zeros(3, 2)
52
+ assert m.kind is MatrixKind(NumberKind)
53
+
54
+ def test_MatMul_kind():
55
+ M = Matrix([[1,2],[3,4]])
56
+ assert MatMul(2, M).kind is MatrixKind(NumberKind)
57
+ assert MatMul(comm_x, M).kind is MatrixKind(NumberKind)
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_logic.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.logic import (fuzzy_not, Logic, And, Or, Not, fuzzy_and,
2
+ fuzzy_or, _fuzzy_group, _torf, fuzzy_nand, fuzzy_xor)
3
+ from sympy.testing.pytest import raises
4
+
5
+ from itertools import product
6
+
7
+ T = True
8
+ F = False
9
+ U = None
10
+
11
+
12
+
13
+ def test_torf():
14
+ v = [T, F, U]
15
+ for i in product(*[v]*3):
16
+ assert _torf(i) is (True if all(j for j in i) else
17
+ (False if all(j is False for j in i) else None))
18
+
19
+
20
+ def test_fuzzy_group():
21
+ v = [T, F, U]
22
+ for i in product(*[v]*3):
23
+ assert _fuzzy_group(i) is (None if None in i else
24
+ (True if all(j for j in i) else False))
25
+ assert _fuzzy_group(i, quick_exit=True) is \
26
+ (None if (i.count(False) > 1) else
27
+ (None if None in i else (True if all(j for j in i) else False)))
28
+ it = (True if (i == 0) else None for i in range(2))
29
+ assert _torf(it) is None
30
+ it = (True if (i == 1) else None for i in range(2))
31
+ assert _torf(it) is None
32
+
33
+
34
+ def test_fuzzy_not():
35
+ assert fuzzy_not(T) == F
36
+ assert fuzzy_not(F) == T
37
+ assert fuzzy_not(U) == U
38
+
39
+
40
+ def test_fuzzy_and():
41
+ assert fuzzy_and([T, T]) == T
42
+ assert fuzzy_and([T, F]) == F
43
+ assert fuzzy_and([T, U]) == U
44
+ assert fuzzy_and([F, F]) == F
45
+ assert fuzzy_and([F, U]) == F
46
+ assert fuzzy_and([U, U]) == U
47
+ assert [fuzzy_and([w]) for w in [U, T, F]] == [U, T, F]
48
+ assert fuzzy_and([T, F, U]) == F
49
+ assert fuzzy_and([]) == T
50
+ raises(TypeError, lambda: fuzzy_and())
51
+
52
+
53
+ def test_fuzzy_or():
54
+ assert fuzzy_or([T, T]) == T
55
+ assert fuzzy_or([T, F]) == T
56
+ assert fuzzy_or([T, U]) == T
57
+ assert fuzzy_or([F, F]) == F
58
+ assert fuzzy_or([F, U]) == U
59
+ assert fuzzy_or([U, U]) == U
60
+ assert [fuzzy_or([w]) for w in [U, T, F]] == [U, T, F]
61
+ assert fuzzy_or([T, F, U]) == T
62
+ assert fuzzy_or([]) == F
63
+ raises(TypeError, lambda: fuzzy_or())
64
+
65
+
66
+ def test_logic_cmp():
67
+ l1 = And('a', Not('b'))
68
+ l2 = And('a', Not('b'))
69
+
70
+ assert hash(l1) == hash(l2)
71
+ assert (l1 == l2) == T
72
+ assert (l1 != l2) == F
73
+
74
+ assert And('a', 'b', 'c') == And('b', 'a', 'c')
75
+ assert And('a', 'b', 'c') == And('c', 'b', 'a')
76
+ assert And('a', 'b', 'c') == And('c', 'a', 'b')
77
+
78
+ assert Not('a') < Not('b')
79
+ assert (Not('b') < Not('a')) is False
80
+ assert (Not('a') < 2) is False
81
+
82
+
83
+ def test_logic_onearg():
84
+ assert And() is True
85
+ assert Or() is False
86
+
87
+ assert And(T) == T
88
+ assert And(F) == F
89
+ assert Or(T) == T
90
+ assert Or(F) == F
91
+
92
+ assert And('a') == 'a'
93
+ assert Or('a') == 'a'
94
+
95
+
96
+ def test_logic_xnotx():
97
+ assert And('a', Not('a')) == F
98
+ assert Or('a', Not('a')) == T
99
+
100
+
101
+ def test_logic_eval_TF():
102
+ assert And(F, F) == F
103
+ assert And(F, T) == F
104
+ assert And(T, F) == F
105
+ assert And(T, T) == T
106
+
107
+ assert Or(F, F) == F
108
+ assert Or(F, T) == T
109
+ assert Or(T, F) == T
110
+ assert Or(T, T) == T
111
+
112
+ assert And('a', T) == 'a'
113
+ assert And('a', F) == F
114
+ assert Or('a', T) == T
115
+ assert Or('a', F) == 'a'
116
+
117
+
118
+ def test_logic_combine_args():
119
+ assert And('a', 'b', 'a') == And('a', 'b')
120
+ assert Or('a', 'b', 'a') == Or('a', 'b')
121
+
122
+ assert And(And('a', 'b'), And('c', 'd')) == And('a', 'b', 'c', 'd')
123
+ assert Or(Or('a', 'b'), Or('c', 'd')) == Or('a', 'b', 'c', 'd')
124
+
125
+ assert Or('t', And('n', 'p', 'r'), And('n', 'r'), And('n', 'p', 'r'), 't',
126
+ And('n', 'r')) == Or('t', And('n', 'p', 'r'), And('n', 'r'))
127
+
128
+
129
+ def test_logic_expand():
130
+ t = And(Or('a', 'b'), 'c')
131
+ assert t.expand() == Or(And('a', 'c'), And('b', 'c'))
132
+
133
+ t = And(Or('a', Not('b')), 'b')
134
+ assert t.expand() == And('a', 'b')
135
+
136
+ t = And(Or('a', 'b'), Or('c', 'd'))
137
+ assert t.expand() == \
138
+ Or(And('a', 'c'), And('a', 'd'), And('b', 'c'), And('b', 'd'))
139
+
140
+
141
+ def test_logic_fromstring():
142
+ S = Logic.fromstring
143
+
144
+ assert S('a') == 'a'
145
+ assert S('!a') == Not('a')
146
+ assert S('a & b') == And('a', 'b')
147
+ assert S('a | b') == Or('a', 'b')
148
+ assert S('a | b & c') == And(Or('a', 'b'), 'c')
149
+ assert S('a & b | c') == Or(And('a', 'b'), 'c')
150
+ assert S('a & b & c') == And('a', 'b', 'c')
151
+ assert S('a | b | c') == Or('a', 'b', 'c')
152
+
153
+ raises(ValueError, lambda: S('| a'))
154
+ raises(ValueError, lambda: S('& a'))
155
+ raises(ValueError, lambda: S('a | | b'))
156
+ raises(ValueError, lambda: S('a | & b'))
157
+ raises(ValueError, lambda: S('a & & b'))
158
+ raises(ValueError, lambda: S('a |'))
159
+ raises(ValueError, lambda: S('a|b'))
160
+ raises(ValueError, lambda: S('!'))
161
+ raises(ValueError, lambda: S('! a'))
162
+ raises(ValueError, lambda: S('!(a + 1)'))
163
+ raises(ValueError, lambda: S(''))
164
+
165
+
166
+ def test_logic_not():
167
+ assert Not('a') != '!a'
168
+ assert Not('!a') != 'a'
169
+ assert Not(True) == False
170
+ assert Not(False) == True
171
+
172
+ # NOTE: we may want to change default Not behaviour and put this
173
+ # functionality into some method.
174
+ assert Not(And('a', 'b')) == Or(Not('a'), Not('b'))
175
+ assert Not(Or('a', 'b')) == And(Not('a'), Not('b'))
176
+
177
+ raises(ValueError, lambda: Not(1))
178
+
179
+
180
+ def test_formatting():
181
+ S = Logic.fromstring
182
+ raises(ValueError, lambda: S('a&b'))
183
+ raises(ValueError, lambda: S('a|b'))
184
+ raises(ValueError, lambda: S('! a'))
185
+
186
+
187
+ def test_fuzzy_xor():
188
+ assert fuzzy_xor((None,)) is None
189
+ assert fuzzy_xor((None, True)) is None
190
+ assert fuzzy_xor((None, False)) is None
191
+ assert fuzzy_xor((True, False)) is True
192
+ assert fuzzy_xor((True, True)) is False
193
+ assert fuzzy_xor((True, True, False)) is False
194
+ assert fuzzy_xor((True, True, False, True)) is True
195
+
196
+ def test_fuzzy_nand():
197
+ for args in [(1, 0), (1, 1), (0, 0)]:
198
+ assert fuzzy_nand(args) == fuzzy_not(fuzzy_and(args))
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_match.py ADDED
@@ -0,0 +1,766 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import abc
2
+ from sympy.concrete.summations import Sum
3
+ from sympy.core.add import Add
4
+ from sympy.core.function import (Derivative, Function, diff)
5
+ from sympy.core.mul import Mul
6
+ from sympy.core.numbers import (Float, I, Integer, Rational, oo, pi)
7
+ from sympy.core.singleton import S
8
+ from sympy.core.symbol import (Symbol, Wild, symbols)
9
+ from sympy.functions.elementary.exponential import (exp, log)
10
+ from sympy.functions.elementary.miscellaneous import sqrt
11
+ from sympy.functions.elementary.trigonometric import (cos, sin)
12
+ from sympy.functions.special.hyper import meijerg
13
+ from sympy.polys.polytools import Poly
14
+ from sympy.simplify.radsimp import collect
15
+ from sympy.simplify.simplify import signsimp
16
+
17
+ from sympy.testing.pytest import XFAIL
18
+
19
+
20
+ def test_symbol():
21
+ x = Symbol('x')
22
+ a, b, c, p, q = map(Wild, 'abcpq')
23
+
24
+ e = x
25
+ assert e.match(x) == {}
26
+ assert e.matches(x) == {}
27
+ assert e.match(a) == {a: x}
28
+
29
+ e = Rational(5)
30
+ assert e.match(c) == {c: 5}
31
+ assert e.match(e) == {}
32
+ assert e.match(e + 1) is None
33
+
34
+
35
+ def test_add():
36
+ x, y, a, b, c = map(Symbol, 'xyabc')
37
+ p, q, r = map(Wild, 'pqr')
38
+
39
+ e = a + b
40
+ assert e.match(p + b) == {p: a}
41
+ assert e.match(p + a) == {p: b}
42
+
43
+ e = 1 + b
44
+ assert e.match(p + b) == {p: 1}
45
+
46
+ e = a + b + c
47
+ assert e.match(a + p + c) == {p: b}
48
+ assert e.match(b + p + c) == {p: a}
49
+
50
+ e = a + b + c + x
51
+ assert e.match(a + p + x + c) == {p: b}
52
+ assert e.match(b + p + c + x) == {p: a}
53
+ assert e.match(b) is None
54
+ assert e.match(b + p) == {p: a + c + x}
55
+ assert e.match(a + p + c) == {p: b + x}
56
+ assert e.match(b + p + c) == {p: a + x}
57
+
58
+ e = 4*x + 5
59
+ assert e.match(4*x + p) == {p: 5}
60
+ assert e.match(3*x + p) == {p: x + 5}
61
+ assert e.match(p*x + 5) == {p: 4}
62
+
63
+
64
+ def test_power():
65
+ x, y, a, b, c = map(Symbol, 'xyabc')
66
+ p, q, r = map(Wild, 'pqr')
67
+
68
+ e = (x + y)**a
69
+ assert e.match(p**q) == {p: x + y, q: a}
70
+ assert e.match(p**p) is None
71
+
72
+ e = (x + y)**(x + y)
73
+ assert e.match(p**p) == {p: x + y}
74
+ assert e.match(p**q) == {p: x + y, q: x + y}
75
+
76
+ e = (2*x)**2
77
+ assert e.match(p*q**r) == {p: 4, q: x, r: 2}
78
+
79
+ e = Integer(1)
80
+ assert e.match(x**p) == {p: 0}
81
+
82
+
83
+ def test_match_exclude():
84
+ x = Symbol('x')
85
+ y = Symbol('y')
86
+ p = Wild("p")
87
+ q = Wild("q")
88
+ r = Wild("r")
89
+
90
+ e = Rational(6)
91
+ assert e.match(2*p) == {p: 3}
92
+
93
+ e = 3/(4*x + 5)
94
+ assert e.match(3/(p*x + q)) == {p: 4, q: 5}
95
+
96
+ e = 3/(4*x + 5)
97
+ assert e.match(p/(q*x + r)) == {p: 3, q: 4, r: 5}
98
+
99
+ e = 2/(x + 1)
100
+ assert e.match(p/(q*x + r)) == {p: 2, q: 1, r: 1}
101
+
102
+ e = 1/(x + 1)
103
+ assert e.match(p/(q*x + r)) == {p: 1, q: 1, r: 1}
104
+
105
+ e = 4*x + 5
106
+ assert e.match(p*x + q) == {p: 4, q: 5}
107
+
108
+ e = 4*x + 5*y + 6
109
+ assert e.match(p*x + q*y + r) == {p: 4, q: 5, r: 6}
110
+
111
+ a = Wild('a', exclude=[x])
112
+
113
+ e = 3*x
114
+ assert e.match(p*x) == {p: 3}
115
+ assert e.match(a*x) == {a: 3}
116
+
117
+ e = 3*x**2
118
+ assert e.match(p*x) == {p: 3*x}
119
+ assert e.match(a*x) is None
120
+
121
+ e = 3*x + 3 + 6/x
122
+ assert e.match(p*x**2 + p*x + 2*p) == {p: 3/x}
123
+ assert e.match(a*x**2 + a*x + 2*a) is None
124
+
125
+
126
+ def test_mul():
127
+ x, y, a, b, c = map(Symbol, 'xyabc')
128
+ p, q = map(Wild, 'pq')
129
+
130
+ e = 4*x
131
+ assert e.match(p*x) == {p: 4}
132
+ assert e.match(p*y) is None
133
+ assert e.match(e + p*y) == {p: 0}
134
+
135
+ e = a*x*b*c
136
+ assert e.match(p*x) == {p: a*b*c}
137
+ assert e.match(c*p*x) == {p: a*b}
138
+
139
+ e = (a + b)*(a + c)
140
+ assert e.match((p + b)*(p + c)) == {p: a}
141
+
142
+ e = x
143
+ assert e.match(p*x) == {p: 1}
144
+
145
+ e = exp(x)
146
+ assert e.match(x**p*exp(x*q)) == {p: 0, q: 1}
147
+
148
+ e = I*Poly(x, x)
149
+ assert e.match(I*p) == {p: x}
150
+
151
+
152
+ def test_mul_noncommutative():
153
+ x, y = symbols('x y')
154
+ A, B, C = symbols('A B C', commutative=False)
155
+ u, v = symbols('u v', cls=Wild)
156
+ w, z = symbols('w z', cls=Wild, commutative=False)
157
+
158
+ assert (u*v).matches(x) in ({v: x, u: 1}, {u: x, v: 1})
159
+ assert (u*v).matches(x*y) in ({v: y, u: x}, {u: y, v: x})
160
+ assert (u*v).matches(A) is None
161
+ assert (u*v).matches(A*B) is None
162
+ assert (u*v).matches(x*A) is None
163
+ assert (u*v).matches(x*y*A) is None
164
+ assert (u*v).matches(x*A*B) is None
165
+ assert (u*v).matches(x*y*A*B) is None
166
+
167
+ assert (v*w).matches(x) is None
168
+ assert (v*w).matches(x*y) is None
169
+ assert (v*w).matches(A) == {w: A, v: 1}
170
+ assert (v*w).matches(A*B) == {w: A*B, v: 1}
171
+ assert (v*w).matches(x*A) == {w: A, v: x}
172
+ assert (v*w).matches(x*y*A) == {w: A, v: x*y}
173
+ assert (v*w).matches(x*A*B) == {w: A*B, v: x}
174
+ assert (v*w).matches(x*y*A*B) == {w: A*B, v: x*y}
175
+
176
+ assert (v*w).matches(-x) is None
177
+ assert (v*w).matches(-x*y) is None
178
+ assert (v*w).matches(-A) == {w: A, v: -1}
179
+ assert (v*w).matches(-A*B) == {w: A*B, v: -1}
180
+ assert (v*w).matches(-x*A) == {w: A, v: -x}
181
+ assert (v*w).matches(-x*y*A) == {w: A, v: -x*y}
182
+ assert (v*w).matches(-x*A*B) == {w: A*B, v: -x}
183
+ assert (v*w).matches(-x*y*A*B) == {w: A*B, v: -x*y}
184
+
185
+ assert (w*z).matches(x) is None
186
+ assert (w*z).matches(x*y) is None
187
+ assert (w*z).matches(A) is None
188
+ assert (w*z).matches(A*B) == {w: A, z: B}
189
+ assert (w*z).matches(B*A) == {w: B, z: A}
190
+ assert (w*z).matches(A*B*C) in [{w: A, z: B*C}, {w: A*B, z: C}]
191
+ assert (w*z).matches(x*A) is None
192
+ assert (w*z).matches(x*y*A) is None
193
+ assert (w*z).matches(x*A*B) is None
194
+ assert (w*z).matches(x*y*A*B) is None
195
+
196
+ assert (w*A).matches(A) is None
197
+ assert (A*w*B).matches(A*B) is None
198
+
199
+ assert (u*w*z).matches(x) is None
200
+ assert (u*w*z).matches(x*y) is None
201
+ assert (u*w*z).matches(A) is None
202
+ assert (u*w*z).matches(A*B) == {u: 1, w: A, z: B}
203
+ assert (u*w*z).matches(B*A) == {u: 1, w: B, z: A}
204
+ assert (u*w*z).matches(x*A) is None
205
+ assert (u*w*z).matches(x*y*A) is None
206
+ assert (u*w*z).matches(x*A*B) == {u: x, w: A, z: B}
207
+ assert (u*w*z).matches(x*B*A) == {u: x, w: B, z: A}
208
+ assert (u*w*z).matches(x*y*A*B) == {u: x*y, w: A, z: B}
209
+ assert (u*w*z).matches(x*y*B*A) == {u: x*y, w: B, z: A}
210
+
211
+ assert (u*A).matches(x*A) == {u: x}
212
+ assert (u*A).matches(x*A*B) is None
213
+ assert (u*B).matches(x*A) is None
214
+ assert (u*A*B).matches(x*A*B) == {u: x}
215
+ assert (u*A*B).matches(x*B*A) is None
216
+ assert (u*A*B).matches(x*A) is None
217
+
218
+ assert (u*w*A).matches(x*A*B) is None
219
+ assert (u*w*B).matches(x*A*B) == {u: x, w: A}
220
+
221
+ assert (u*v*A*B).matches(x*A*B) in [{u: x, v: 1}, {v: x, u: 1}]
222
+ assert (u*v*A*B).matches(x*B*A) is None
223
+ assert (u*v*A*B).matches(u*v*A*C) is None
224
+
225
+
226
+ def test_mul_noncommutative_mismatch():
227
+ A, B, C = symbols('A B C', commutative=False)
228
+ w = symbols('w', cls=Wild, commutative=False)
229
+
230
+ assert (w*B*w).matches(A*B*A) == {w: A}
231
+ assert (w*B*w).matches(A*C*B*A*C) == {w: A*C}
232
+ assert (w*B*w).matches(A*C*B*A*B) is None
233
+ assert (w*B*w).matches(A*B*C) is None
234
+ assert (w*w*C).matches(A*B*C) is None
235
+
236
+
237
+ def test_mul_noncommutative_pow():
238
+ A, B, C = symbols('A B C', commutative=False)
239
+ w = symbols('w', cls=Wild, commutative=False)
240
+
241
+ assert (A*B*w).matches(A*B**2) == {w: B}
242
+ assert (A*(B**2)*w*(B**3)).matches(A*B**8) == {w: B**3}
243
+ assert (A*B*w*C).matches(A*(B**4)*C) == {w: B**3}
244
+
245
+ assert (A*B*(w**(-1))).matches(A*B*(C**(-1))) == {w: C}
246
+ assert (A*(B*w)**(-1)*C).matches(A*(B*C)**(-1)*C) == {w: C}
247
+
248
+ assert ((w**2)*B*C).matches((A**2)*B*C) == {w: A}
249
+ assert ((w**2)*B*(w**3)).matches((A**2)*B*(A**3)) == {w: A}
250
+ assert ((w**2)*B*(w**4)).matches((A**2)*B*(A**2)) is None
251
+
252
+ def test_complex():
253
+ a, b, c = map(Symbol, 'abc')
254
+ x, y = map(Wild, 'xy')
255
+
256
+ assert (1 + I).match(x + I) == {x: 1}
257
+ assert (a + I).match(x + I) == {x: a}
258
+ assert (2*I).match(x*I) == {x: 2}
259
+ assert (a*I).match(x*I) == {x: a}
260
+ assert (a*I).match(x*y) == {x: I, y: a}
261
+ assert (2*I).match(x*y) == {x: 2, y: I}
262
+ assert (a + b*I).match(x + y*I) == {x: a, y: b}
263
+
264
+
265
+ def test_functions():
266
+ from sympy.core.function import WildFunction
267
+ x = Symbol('x')
268
+ g = WildFunction('g')
269
+ p = Wild('p')
270
+ q = Wild('q')
271
+
272
+ f = cos(5*x)
273
+ notf = x
274
+ assert f.match(p*cos(q*x)) == {p: 1, q: 5}
275
+ assert f.match(p*g) == {p: 1, g: cos(5*x)}
276
+ assert notf.match(g) is None
277
+
278
+
279
+ @XFAIL
280
+ def test_functions_X1():
281
+ from sympy.core.function import WildFunction
282
+ x = Symbol('x')
283
+ g = WildFunction('g')
284
+ p = Wild('p')
285
+ q = Wild('q')
286
+
287
+ f = cos(5*x)
288
+ assert f.match(p*g(q*x)) == {p: 1, g: cos, q: 5}
289
+
290
+
291
+ def test_interface():
292
+ x, y = map(Symbol, 'xy')
293
+ p, q = map(Wild, 'pq')
294
+
295
+ assert (x + 1).match(p + 1) == {p: x}
296
+ assert (x*3).match(p*3) == {p: x}
297
+ assert (x**3).match(p**3) == {p: x}
298
+ assert (x*cos(y)).match(p*cos(q)) == {p: x, q: y}
299
+
300
+ assert (x*y).match(p*q) in [{p:x, q:y}, {p:y, q:x}]
301
+ assert (x + y).match(p + q) in [{p:x, q:y}, {p:y, q:x}]
302
+ assert (x*y + 1).match(p*q) in [{p:1, q:1 + x*y}, {p:1 + x*y, q:1}]
303
+
304
+
305
+ def test_derivative1():
306
+ x, y = map(Symbol, 'xy')
307
+ p, q = map(Wild, 'pq')
308
+
309
+ f = Function('f', nargs=1)
310
+ fd = Derivative(f(x), x)
311
+
312
+ assert fd.match(p) == {p: fd}
313
+ assert (fd + 1).match(p + 1) == {p: fd}
314
+ assert (fd).match(fd) == {}
315
+ assert (3*fd).match(p*fd) is not None
316
+ assert (3*fd - 1).match(p*fd + q) == {p: 3, q: -1}
317
+
318
+
319
+ def test_derivative_bug1():
320
+ f = Function("f")
321
+ x = Symbol("x")
322
+ a = Wild("a", exclude=[f, x])
323
+ b = Wild("b", exclude=[f])
324
+ pattern = a * Derivative(f(x), x, x) + b
325
+ expr = Derivative(f(x), x) + x**2
326
+ d1 = {b: x**2}
327
+ d2 = pattern.xreplace(d1).matches(expr, d1)
328
+ assert d2 is None
329
+
330
+
331
+ def test_derivative2():
332
+ f = Function("f")
333
+ x = Symbol("x")
334
+ a = Wild("a", exclude=[f, x])
335
+ b = Wild("b", exclude=[f])
336
+ e = Derivative(f(x), x)
337
+ assert e.match(Derivative(f(x), x)) == {}
338
+ assert e.match(Derivative(f(x), x, x)) is None
339
+ e = Derivative(f(x), x, x)
340
+ assert e.match(Derivative(f(x), x)) is None
341
+ assert e.match(Derivative(f(x), x, x)) == {}
342
+ e = Derivative(f(x), x) + x**2
343
+ assert e.match(a*Derivative(f(x), x) + b) == {a: 1, b: x**2}
344
+ assert e.match(a*Derivative(f(x), x, x) + b) is None
345
+ e = Derivative(f(x), x, x) + x**2
346
+ assert e.match(a*Derivative(f(x), x) + b) is None
347
+ assert e.match(a*Derivative(f(x), x, x) + b) == {a: 1, b: x**2}
348
+
349
+
350
+ def test_match_deriv_bug1():
351
+ n = Function('n')
352
+ l = Function('l')
353
+
354
+ x = Symbol('x')
355
+ p = Wild('p')
356
+
357
+ e = diff(l(x), x)/x - diff(diff(n(x), x), x)/2 - \
358
+ diff(n(x), x)**2/4 + diff(n(x), x)*diff(l(x), x)/4
359
+ e = e.subs(n(x), -l(x)).doit()
360
+ t = x*exp(-l(x))
361
+ t2 = t.diff(x, x)/t
362
+ assert e.match( (p*t2).expand() ) == {p: Rational(-1, 2)}
363
+
364
+
365
+ def test_match_bug2():
366
+ x, y = map(Symbol, 'xy')
367
+ p, q, r = map(Wild, 'pqr')
368
+ res = (x + y).match(p + q + r)
369
+ assert (p + q + r).subs(res) == x + y
370
+
371
+
372
+ def test_match_bug3():
373
+ x, a, b = map(Symbol, 'xab')
374
+ p = Wild('p')
375
+ assert (b*x*exp(a*x)).match(x*exp(p*x)) is None
376
+
377
+
378
+ def test_match_bug4():
379
+ x = Symbol('x')
380
+ p = Wild('p')
381
+ e = x
382
+ assert e.match(-p*x) == {p: -1}
383
+
384
+
385
+ def test_match_bug5():
386
+ x = Symbol('x')
387
+ p = Wild('p')
388
+ e = -x
389
+ assert e.match(-p*x) == {p: 1}
390
+
391
+
392
+ def test_match_bug6():
393
+ x = Symbol('x')
394
+ p = Wild('p')
395
+ e = x
396
+ assert e.match(3*p*x) == {p: Rational(1)/3}
397
+
398
+
399
+ def test_match_polynomial():
400
+ x = Symbol('x')
401
+ a = Wild('a', exclude=[x])
402
+ b = Wild('b', exclude=[x])
403
+ c = Wild('c', exclude=[x])
404
+ d = Wild('d', exclude=[x])
405
+
406
+ eq = 4*x**3 + 3*x**2 + 2*x + 1
407
+ pattern = a*x**3 + b*x**2 + c*x + d
408
+ assert eq.match(pattern) == {a: 4, b: 3, c: 2, d: 1}
409
+ assert (eq - 3*x**2).match(pattern) == {a: 4, b: 0, c: 2, d: 1}
410
+ assert (x + sqrt(2) + 3).match(a + b*x + c*x**2) == \
411
+ {b: 1, a: sqrt(2) + 3, c: 0}
412
+
413
+
414
+ def test_exclude():
415
+ x, y, a = map(Symbol, 'xya')
416
+ p = Wild('p', exclude=[1, x])
417
+ q = Wild('q')
418
+ r = Wild('r', exclude=[sin, y])
419
+
420
+ assert sin(x).match(r) is None
421
+ assert cos(y).match(r) is None
422
+
423
+ e = 3*x**2 + y*x + a
424
+ assert e.match(p*x**2 + q*x + r) == {p: 3, q: y, r: a}
425
+
426
+ e = x + 1
427
+ assert e.match(x + p) is None
428
+ assert e.match(p + 1) is None
429
+ assert e.match(x + 1 + p) == {p: 0}
430
+
431
+ e = cos(x) + 5*sin(y)
432
+ assert e.match(r) is None
433
+ assert e.match(cos(y) + r) is None
434
+ assert e.match(r + p*sin(q)) == {r: cos(x), p: 5, q: y}
435
+
436
+
437
+ def test_floats():
438
+ a, b = map(Wild, 'ab')
439
+
440
+ e = cos(0.12345, evaluate=False)**2
441
+ r = e.match(a*cos(b)**2)
442
+ assert r == {a: 1, b: Float(0.12345)}
443
+
444
+
445
+ def test_Derivative_bug1():
446
+ f = Function("f")
447
+ x = abc.x
448
+ a = Wild("a", exclude=[f(x)])
449
+ b = Wild("b", exclude=[f(x)])
450
+ eq = f(x).diff(x)
451
+ assert eq.match(a*Derivative(f(x), x) + b) == {a: 1, b: 0}
452
+
453
+
454
+ def test_match_wild_wild():
455
+ p = Wild('p')
456
+ q = Wild('q')
457
+ r = Wild('r')
458
+
459
+ assert p.match(q + r) in [ {q: p, r: 0}, {q: 0, r: p} ]
460
+ assert p.match(q*r) in [ {q: p, r: 1}, {q: 1, r: p} ]
461
+
462
+ p = Wild('p')
463
+ q = Wild('q', exclude=[p])
464
+ r = Wild('r')
465
+
466
+ assert p.match(q + r) == {q: 0, r: p}
467
+ assert p.match(q*r) == {q: 1, r: p}
468
+
469
+ p = Wild('p')
470
+ q = Wild('q', exclude=[p])
471
+ r = Wild('r', exclude=[p])
472
+
473
+ assert p.match(q + r) is None
474
+ assert p.match(q*r) is None
475
+
476
+
477
+ def test__combine_inverse():
478
+ x, y = symbols("x y")
479
+ assert Mul._combine_inverse(x*I*y, x*I) == y
480
+ assert Mul._combine_inverse(x*x**(1 + y), x**(1 + y)) == x
481
+ assert Mul._combine_inverse(x*I*y, y*I) == x
482
+ assert Mul._combine_inverse(oo*I*y, y*I) is oo
483
+ assert Mul._combine_inverse(oo*I*y, oo*I) == y
484
+ assert Mul._combine_inverse(oo*I*y, oo*I) == y
485
+ assert Mul._combine_inverse(oo*y, -oo) == -y
486
+ assert Mul._combine_inverse(-oo*y, oo) == -y
487
+ assert Mul._combine_inverse((1-exp(x/y)),(exp(x/y)-1)) == -1
488
+ assert Add._combine_inverse(oo, oo) is S.Zero
489
+ assert Add._combine_inverse(oo*I, oo*I) is S.Zero
490
+ assert Add._combine_inverse(x*oo, x*oo) is S.Zero
491
+ assert Add._combine_inverse(-x*oo, -x*oo) is S.Zero
492
+ assert Add._combine_inverse((x - oo)*(x + oo), -oo)
493
+
494
+
495
+ def test_issue_3773():
496
+ x = symbols('x')
497
+ z, phi, r = symbols('z phi r')
498
+ c, A, B, N = symbols('c A B N', cls=Wild)
499
+ l = Wild('l', exclude=(0,))
500
+
501
+ eq = z * sin(2*phi) * r**7
502
+ matcher = c * sin(phi*N)**l * r**A * log(r)**B
503
+
504
+ assert eq.match(matcher) == {c: z, l: 1, N: 2, A: 7, B: 0}
505
+ assert (-eq).match(matcher) == {c: -z, l: 1, N: 2, A: 7, B: 0}
506
+ assert (x*eq).match(matcher) == {c: x*z, l: 1, N: 2, A: 7, B: 0}
507
+ assert (-7*x*eq).match(matcher) == {c: -7*x*z, l: 1, N: 2, A: 7, B: 0}
508
+
509
+ matcher = c*sin(phi*N)**l * r**A
510
+
511
+ assert eq.match(matcher) == {c: z, l: 1, N: 2, A: 7}
512
+ assert (-eq).match(matcher) == {c: -z, l: 1, N: 2, A: 7}
513
+ assert (x*eq).match(matcher) == {c: x*z, l: 1, N: 2, A: 7}
514
+ assert (-7*x*eq).match(matcher) == {c: -7*x*z, l: 1, N: 2, A: 7}
515
+
516
+
517
+ def test_issue_3883():
518
+ from sympy.abc import gamma, mu, x
519
+ f = (-gamma * (x - mu)**2 - log(gamma) + log(2*pi))/2
520
+ a, b, c = symbols('a b c', cls=Wild, exclude=(gamma,))
521
+
522
+ assert f.match(a * log(gamma) + b * gamma + c) == \
523
+ {a: Rational(-1, 2), b: -(-mu + x)**2/2, c: log(2*pi)/2}
524
+ assert f.expand().collect(gamma).match(a * log(gamma) + b * gamma + c) == \
525
+ {a: Rational(-1, 2), b: (-(x - mu)**2/2).expand(), c: (log(2*pi)/2).expand()}
526
+ g1 = Wild('g1', exclude=[gamma])
527
+ g2 = Wild('g2', exclude=[gamma])
528
+ g3 = Wild('g3', exclude=[gamma])
529
+ assert f.expand().match(g1 * log(gamma) + g2 * gamma + g3) == \
530
+ {g3: log(2)/2 + log(pi)/2, g1: Rational(-1, 2), g2: -mu**2/2 + mu*x - x**2/2}
531
+
532
+
533
+ def test_issue_4418():
534
+ x = Symbol('x')
535
+ a, b, c = symbols('a b c', cls=Wild, exclude=(x,))
536
+ f, g = symbols('f g', cls=Function)
537
+
538
+ eq = diff(g(x)*f(x).diff(x), x)
539
+
540
+ assert eq.match(
541
+ g(x).diff(x)*f(x).diff(x) + g(x)*f(x).diff(x, x) + c) == {c: 0}
542
+ assert eq.match(a*g(x).diff(
543
+ x)*f(x).diff(x) + b*g(x)*f(x).diff(x, x) + c) == {a: 1, b: 1, c: 0}
544
+
545
+
546
+ def test_issue_4700():
547
+ f = Function('f')
548
+ x = Symbol('x')
549
+ a, b = symbols('a b', cls=Wild, exclude=(f(x),))
550
+
551
+ p = a*f(x) + b
552
+ eq1 = sin(x)
553
+ eq2 = f(x) + sin(x)
554
+ eq3 = f(x) + x + sin(x)
555
+ eq4 = x + sin(x)
556
+
557
+ assert eq1.match(p) == {a: 0, b: sin(x)}
558
+ assert eq2.match(p) == {a: 1, b: sin(x)}
559
+ assert eq3.match(p) == {a: 1, b: x + sin(x)}
560
+ assert eq4.match(p) == {a: 0, b: x + sin(x)}
561
+
562
+
563
+ def test_issue_5168():
564
+ a, b, c = symbols('a b c', cls=Wild)
565
+ x = Symbol('x')
566
+ f = Function('f')
567
+
568
+ assert x.match(a) == {a: x}
569
+ assert x.match(a*f(x)**c) == {a: x, c: 0}
570
+ assert x.match(a*b) == {a: 1, b: x}
571
+ assert x.match(a*b*f(x)**c) == {a: 1, b: x, c: 0}
572
+
573
+ assert (-x).match(a) == {a: -x}
574
+ assert (-x).match(a*f(x)**c) == {a: -x, c: 0}
575
+ assert (-x).match(a*b) == {a: -1, b: x}
576
+ assert (-x).match(a*b*f(x)**c) == {a: -1, b: x, c: 0}
577
+
578
+ assert (2*x).match(a) == {a: 2*x}
579
+ assert (2*x).match(a*f(x)**c) == {a: 2*x, c: 0}
580
+ assert (2*x).match(a*b) == {a: 2, b: x}
581
+ assert (2*x).match(a*b*f(x)**c) == {a: 2, b: x, c: 0}
582
+
583
+ assert (-2*x).match(a) == {a: -2*x}
584
+ assert (-2*x).match(a*f(x)**c) == {a: -2*x, c: 0}
585
+ assert (-2*x).match(a*b) == {a: -2, b: x}
586
+ assert (-2*x).match(a*b*f(x)**c) == {a: -2, b: x, c: 0}
587
+
588
+
589
+ def test_issue_4559():
590
+ x = Symbol('x')
591
+ e = Symbol('e')
592
+ w = Wild('w', exclude=[x])
593
+ y = Wild('y')
594
+
595
+ # this is as it should be
596
+
597
+ assert (3/x).match(w/y) == {w: 3, y: x}
598
+ assert (3*x).match(w*y) == {w: 3, y: x}
599
+ assert (x/3).match(y/w) == {w: 3, y: x}
600
+ assert (3*x).match(y/w) == {w: S.One/3, y: x}
601
+ assert (3*x).match(y/w) == {w: Rational(1, 3), y: x}
602
+
603
+ # these could be allowed to fail
604
+
605
+ assert (x/3).match(w/y) == {w: S.One/3, y: 1/x}
606
+ assert (3*x).match(w/y) == {w: 3, y: 1/x}
607
+ assert (3/x).match(w*y) == {w: 3, y: 1/x}
608
+
609
+ # Note that solve will give
610
+ # multiple roots but match only gives one:
611
+ #
612
+ # >>> solve(x**r-y**2,y)
613
+ # [-x**(r/2), x**(r/2)]
614
+
615
+ r = Symbol('r', rational=True)
616
+ assert (x**r).match(y**2) == {y: x**(r/2)}
617
+ assert (x**e).match(y**2) == {y: sqrt(x**e)}
618
+
619
+ # since (x**i = y) -> x = y**(1/i) where i is an integer
620
+ # the following should also be valid as long as y is not
621
+ # zero when i is negative.
622
+
623
+ a = Wild('a')
624
+
625
+ e = S.Zero
626
+ assert e.match(a) == {a: e}
627
+ assert e.match(1/a) is None
628
+ assert e.match(a**.3) is None
629
+
630
+ e = S(3)
631
+ assert e.match(1/a) == {a: 1/e}
632
+ assert e.match(1/a**2) == {a: 1/sqrt(e)}
633
+ e = pi
634
+ assert e.match(1/a) == {a: 1/e}
635
+ assert e.match(1/a**2) == {a: 1/sqrt(e)}
636
+ assert (-e).match(sqrt(a)) is None
637
+ assert (-e).match(a**2) == {a: I*sqrt(pi)}
638
+
639
+ # The pattern matcher doesn't know how to handle (x - a)**2 == (a - x)**2. To
640
+ # avoid ambiguity in actual applications, don't put a coefficient (including a
641
+ # minus sign) in front of a wild.
642
+ @XFAIL
643
+ def test_issue_4883():
644
+ a = Wild('a')
645
+ x = Symbol('x')
646
+
647
+ e = [i**2 for i in (x - 2, 2 - x)]
648
+ p = [i**2 for i in (x - a, a- x)]
649
+ for eq in e:
650
+ for pat in p:
651
+ assert eq.match(pat) == {a: 2}
652
+
653
+
654
+ def test_issue_4319():
655
+ x, y = symbols('x y')
656
+
657
+ p = -x*(S.One/8 - y)
658
+ ans = {S.Zero, y - S.One/8}
659
+
660
+ def ok(pat):
661
+ assert set(p.match(pat).values()) == ans
662
+
663
+ ok(Wild("coeff", exclude=[x])*x + Wild("rest"))
664
+ ok(Wild("w", exclude=[x])*x + Wild("rest"))
665
+ ok(Wild("coeff", exclude=[x])*x + Wild("rest"))
666
+ ok(Wild("w", exclude=[x])*x + Wild("rest"))
667
+ ok(Wild("e", exclude=[x])*x + Wild("rest"))
668
+ ok(Wild("ress", exclude=[x])*x + Wild("rest"))
669
+ ok(Wild("resu", exclude=[x])*x + Wild("rest"))
670
+
671
+
672
+ def test_issue_3778():
673
+ p, c, q = symbols('p c q', cls=Wild)
674
+ x = Symbol('x')
675
+
676
+ assert (sin(x)**2).match(sin(p)*sin(q)*c) == {q: x, c: 1, p: x}
677
+ assert (2*sin(x)).match(sin(p) + sin(q) + c) == {q: x, c: 0, p: x}
678
+
679
+
680
+ def test_issue_6103():
681
+ x = Symbol('x')
682
+ a = Wild('a')
683
+ assert (-I*x*oo).match(I*a*oo) == {a: -x}
684
+
685
+
686
+ def test_issue_3539():
687
+ a = Wild('a')
688
+ x = Symbol('x')
689
+ assert (x - 2).match(a - x) is None
690
+ assert (6/x).match(a*x) is None
691
+ assert (6/x**2).match(a/x) == {a: 6/x}
692
+
693
+ def test_gh_issue_2711():
694
+ x = Symbol('x')
695
+ f = meijerg(((), ()), ((0,), ()), x)
696
+ a = Wild('a')
697
+ b = Wild('b')
698
+
699
+ assert f.find(a) == {(S.Zero,), ((), ()), ((S.Zero,), ()), x, S.Zero,
700
+ (), meijerg(((), ()), ((S.Zero,), ()), x)}
701
+ assert f.find(a + b) == \
702
+ {meijerg(((), ()), ((S.Zero,), ()), x), x, S.Zero}
703
+ assert f.find(a**2) == {meijerg(((), ()), ((S.Zero,), ()), x), x}
704
+
705
+
706
+ def test_issue_17354():
707
+ from sympy.core.symbol import (Wild, symbols)
708
+ x, y = symbols("x y", real=True)
709
+ a, b = symbols("a b", cls=Wild)
710
+ assert ((0 <= x).reversed | (y <= x)).match((1/a <= b) | (a <= b)) is None
711
+
712
+
713
+ def test_match_issue_17397():
714
+ f = Function("f")
715
+ x = Symbol("x")
716
+ a3 = Wild('a3', exclude=[f(x), f(x).diff(x), f(x).diff(x, 2)])
717
+ b3 = Wild('b3', exclude=[f(x), f(x).diff(x), f(x).diff(x, 2)])
718
+ c3 = Wild('c3', exclude=[f(x), f(x).diff(x), f(x).diff(x, 2)])
719
+ deq = a3*(f(x).diff(x, 2)) + b3*f(x).diff(x) + c3*f(x)
720
+
721
+ eq = (x-2)**2*(f(x).diff(x, 2)) + (x-2)*(f(x).diff(x)) + ((x-2)**2 - 4)*f(x)
722
+ r = collect(eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
723
+ assert r == {a3: (x - 2)**2, c3: (x - 2)**2 - 4, b3: x - 2}
724
+
725
+ eq =x*f(x) + x*Derivative(f(x), (x, 2)) - 4*f(x) + Derivative(f(x), x) \
726
+ - 4*Derivative(f(x), (x, 2)) - 2*Derivative(f(x), x)/x + 4*Derivative(f(x), (x, 2))/x
727
+ r = collect(eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
728
+ assert r == {a3: x - 4 + 4/x, b3: 1 - 2/x, c3: x - 4}
729
+
730
+
731
+ def test_match_issue_21942():
732
+ a, r, w = symbols('a, r, w', nonnegative=True)
733
+ p = symbols('p', positive=True)
734
+ g_ = Wild('g')
735
+ pattern = g_ ** (1 / (1 - p))
736
+ eq = (a * r ** (1 - p) + w ** (1 - p) * (1 - a)) ** (1 / (1 - p))
737
+ m = {g_: a * r ** (1 - p) + w ** (1 - p) * (1 - a)}
738
+ assert pattern.matches(eq) == m
739
+ assert (-pattern).matches(-eq) == m
740
+ assert pattern.matches(signsimp(eq)) is None
741
+
742
+
743
+ def test_match_terms():
744
+ X, Y = map(Wild, "XY")
745
+ x, y, z = symbols('x y z')
746
+ assert (5*y - x).match(5*X - Y) == {X: y, Y: x}
747
+ # 15907
748
+ assert (x + (y - 1)*z).match(x + X*z) == {X: y - 1}
749
+ # 20747
750
+ assert (x - log(x/y)*(1-exp(x/y))).match(x - log(X/y)*(1-exp(x/y))) == {X: x}
751
+
752
+
753
+ def test_match_bound():
754
+ V, W = map(Wild, "VW")
755
+ x, y = symbols('x y')
756
+ assert Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, W))) == {W: 2}
757
+ assert Sum(x, (x, 1, 2)).match(Sum(V, (V, 1, W))) == {W: 2, V:x}
758
+ assert Sum(x, (x, 1, 2)).match(Sum(V, (V, 1, 2))) == {V:x}
759
+
760
+
761
+ def test_issue_22462():
762
+ x, f = symbols('x'), Function('f')
763
+ n, Q = symbols('n Q', cls=Wild)
764
+ pattern = -Q*f(x)**n
765
+ eq = 5*f(x)**2
766
+ assert pattern.matches(eq) == {n: 2, Q: -5}
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_multidimensional.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import (Derivative, Function, diff)
2
+ from sympy.core.symbol import symbols
3
+ from sympy.functions.elementary.trigonometric import sin
4
+ from sympy.core.multidimensional import vectorize
5
+ x, y, z = symbols('x y z')
6
+ f, g, h = list(map(Function, 'fgh'))
7
+
8
+
9
+ def test_vectorize():
10
+ @vectorize(0)
11
+ def vsin(x):
12
+ return sin(x)
13
+
14
+ assert vsin([1, x, y]) == [sin(1), sin(x), sin(y)]
15
+
16
+ @vectorize(0, 1)
17
+ def vdiff(f, y):
18
+ return diff(f, y)
19
+
20
+ assert vdiff([f(x, y, z), g(x, y, z), h(x, y, z)], [x, y, z]) == \
21
+ [[Derivative(f(x, y, z), x), Derivative(f(x, y, z), y),
22
+ Derivative(f(x, y, z), z)], [Derivative(g(x, y, z), x),
23
+ Derivative(g(x, y, z), y), Derivative(g(x, y, z), z)],
24
+ [Derivative(h(x, y, z), x), Derivative(h(x, y, z), y), Derivative(h(x, y, z), z)]]
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_noncommutative.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for noncommutative symbols and expressions."""
2
+
3
+ from sympy.core.function import expand
4
+ from sympy.core.numbers import I
5
+ from sympy.core.symbol import symbols
6
+ from sympy.functions.elementary.complexes import (adjoint, conjugate, transpose)
7
+ from sympy.functions.elementary.trigonometric import (cos, sin)
8
+ from sympy.polys.polytools import (cancel, factor)
9
+ from sympy.simplify.combsimp import combsimp
10
+ from sympy.simplify.gammasimp import gammasimp
11
+ from sympy.simplify.radsimp import (collect, radsimp, rcollect)
12
+ from sympy.simplify.ratsimp import ratsimp
13
+ from sympy.simplify.simplify import (posify, simplify)
14
+ from sympy.simplify.trigsimp import trigsimp
15
+ from sympy.abc import x, y, z
16
+ from sympy.testing.pytest import XFAIL
17
+
18
+ A, B, C = symbols("A B C", commutative=False)
19
+ X = symbols("X", commutative=False, hermitian=True)
20
+ Y = symbols("Y", commutative=False, antihermitian=True)
21
+
22
+
23
+ def test_adjoint():
24
+ assert adjoint(A).is_commutative is False
25
+ assert adjoint(A*A) == adjoint(A)**2
26
+ assert adjoint(A*B) == adjoint(B)*adjoint(A)
27
+ assert adjoint(A*B**2) == adjoint(B)**2*adjoint(A)
28
+ assert adjoint(A*B - B*A) == adjoint(B)*adjoint(A) - adjoint(A)*adjoint(B)
29
+ assert adjoint(A + I*B) == adjoint(A) - I*adjoint(B)
30
+
31
+ assert adjoint(X) == X
32
+ assert adjoint(-I*X) == I*X
33
+ assert adjoint(Y) == -Y
34
+ assert adjoint(-I*Y) == -I*Y
35
+
36
+ assert adjoint(X) == conjugate(transpose(X))
37
+ assert adjoint(Y) == conjugate(transpose(Y))
38
+ assert adjoint(X) == transpose(conjugate(X))
39
+ assert adjoint(Y) == transpose(conjugate(Y))
40
+
41
+
42
+ def test_cancel():
43
+ assert cancel(A*B - B*A) == A*B - B*A
44
+ assert cancel(A*B*(x - 1)) == A*B*(x - 1)
45
+ assert cancel(A*B*(x**2 - 1)/(x + 1)) == A*B*(x - 1)
46
+ assert cancel(A*B*(x**2 - 1)/(x + 1) - B*A*(x - 1)) == A*B*(x - 1) + (1 - x)*B*A
47
+
48
+
49
+ @XFAIL
50
+ def test_collect():
51
+ assert collect(A*B - B*A, A) == A*B - B*A
52
+ assert collect(A*B - B*A, B) == A*B - B*A
53
+ assert collect(A*B - B*A, x) == A*B - B*A
54
+
55
+
56
+ def test_combsimp():
57
+ assert combsimp(A*B - B*A) == A*B - B*A
58
+
59
+
60
+ def test_gammasimp():
61
+ assert gammasimp(A*B - B*A) == A*B - B*A
62
+
63
+
64
+ def test_conjugate():
65
+ assert conjugate(A).is_commutative is False
66
+ assert (A*A).conjugate() == conjugate(A)**2
67
+ assert (A*B).conjugate() == conjugate(A)*conjugate(B)
68
+ assert (A*B**2).conjugate() == conjugate(A)*conjugate(B)**2
69
+ assert (A*B - B*A).conjugate() == \
70
+ conjugate(A)*conjugate(B) - conjugate(B)*conjugate(A)
71
+ assert (A*B).conjugate() - (B*A).conjugate() == \
72
+ conjugate(A)*conjugate(B) - conjugate(B)*conjugate(A)
73
+ assert (A + I*B).conjugate() == conjugate(A) - I*conjugate(B)
74
+
75
+
76
+ def test_expand():
77
+ assert expand((A*B)**2) == A*B*A*B
78
+ assert expand(A*B - B*A) == A*B - B*A
79
+ assert expand((A*B/A)**2) == A*B*B/A
80
+ assert expand(B*A*(A + B)*B) == B*A**2*B + B*A*B**2
81
+ assert expand(B*A*(A + C)*B) == B*A**2*B + B*A*C*B
82
+
83
+
84
+ def test_factor():
85
+ assert factor(A*B - B*A) == A*B - B*A
86
+
87
+
88
+ def test_posify():
89
+ assert posify(A)[0].is_commutative is False
90
+ for q in (A*B/A, (A*B/A)**2, (A*B)**2, A*B - B*A):
91
+ p = posify(q)
92
+ assert p[0].subs(p[1]) == q
93
+
94
+
95
+ def test_radsimp():
96
+ assert radsimp(A*B - B*A) == A*B - B*A
97
+
98
+
99
+ @XFAIL
100
+ def test_ratsimp():
101
+ assert ratsimp(A*B - B*A) == A*B - B*A
102
+
103
+
104
+ @XFAIL
105
+ def test_rcollect():
106
+ assert rcollect(A*B - B*A, A) == A*B - B*A
107
+ assert rcollect(A*B - B*A, B) == A*B - B*A
108
+ assert rcollect(A*B - B*A, x) == A*B - B*A
109
+
110
+
111
+ def test_simplify():
112
+ assert simplify(A*B - B*A) == A*B - B*A
113
+
114
+
115
+ def test_subs():
116
+ assert (x*y*A).subs(x*y, z) == A*z
117
+ assert (x*A*B).subs(x*A, C) == C*B
118
+ assert (x*A*x*x).subs(x**2*A, C) == x*C
119
+ assert (x*A*x*B).subs(x**2*A, C) == C*B
120
+ assert (A**2*B**2).subs(A*B**2, C) == A*C
121
+ assert (A*A*A + A*B*A).subs(A*A*A, C) == C + A*B*A
122
+
123
+
124
+ def test_transpose():
125
+ assert transpose(A).is_commutative is False
126
+ assert transpose(A*A) == transpose(A)**2
127
+ assert transpose(A*B) == transpose(B)*transpose(A)
128
+ assert transpose(A*B**2) == transpose(B)**2*transpose(A)
129
+ assert transpose(A*B - B*A) == \
130
+ transpose(B)*transpose(A) - transpose(A)*transpose(B)
131
+ assert transpose(A + I*B) == transpose(A) + I*transpose(B)
132
+
133
+ assert transpose(X) == conjugate(X)
134
+ assert transpose(-I*X) == -I*conjugate(X)
135
+ assert transpose(Y) == -conjugate(Y)
136
+ assert transpose(-I*Y) == I*conjugate(Y)
137
+
138
+
139
+ def test_trigsimp():
140
+ assert trigsimp(A*sin(x)**2 + A*cos(x)**2) == A
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_numbers.py ADDED
@@ -0,0 +1,2266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numbers as nums
2
+ import decimal
3
+ from sympy.concrete.summations import Sum
4
+ from sympy.core import (EulerGamma, Catalan, TribonacciConstant,
5
+ GoldenRatio)
6
+ from sympy.core.containers import Tuple
7
+ from sympy.core.expr import unchanged
8
+ from sympy.core.logic import fuzzy_not
9
+ from sympy.core.mul import Mul
10
+ from sympy.core.numbers import (mpf_norm, mod_inverse, igcd, seterr,
11
+ igcd_lehmer, Integer, I, pi, comp, ilcm, Rational, E, nan, igcd2,
12
+ oo, AlgebraicNumber, igcdex, Number, Float, zoo, equal_valued)
13
+ from sympy.core.power import Pow
14
+ from sympy.core.relational import Ge, Gt, Le, Lt
15
+ from sympy.core.singleton import S
16
+ from sympy.core.symbol import Dummy, Symbol
17
+ from sympy.core.sympify import sympify
18
+ from sympy.functions.combinatorial.factorials import factorial
19
+ from sympy.functions.elementary.integers import floor
20
+ from sympy.functions.combinatorial.numbers import fibonacci
21
+ from sympy.functions.elementary.exponential import exp, log
22
+ from sympy.functions.elementary.miscellaneous import sqrt, cbrt
23
+ from sympy.functions.elementary.trigonometric import cos, sin
24
+ from sympy.polys.domains.realfield import RealField
25
+ from sympy.printing.latex import latex
26
+ from sympy.printing.repr import srepr
27
+ from sympy.simplify import simplify
28
+ from sympy.core.power import integer_nthroot, isqrt, integer_log
29
+ from sympy.polys.domains.groundtypes import PythonRational
30
+ from sympy.utilities.decorator import conserve_mpmath_dps
31
+ from sympy.utilities.iterables import permutations
32
+ from sympy.testing.pytest import XFAIL, raises, _both_exp_pow
33
+
34
+ from mpmath import mpf
35
+ from mpmath.rational import mpq
36
+ import mpmath
37
+ from sympy.core import numbers
38
+ t = Symbol('t', real=False)
39
+
40
+ _ninf = float(-oo)
41
+ _inf = float(oo)
42
+
43
+
44
+ def same_and_same_prec(a, b):
45
+ # stricter matching for Floats
46
+ return a == b and a._prec == b._prec
47
+
48
+
49
+ def test_seterr():
50
+ seterr(divide=True)
51
+ raises(ValueError, lambda: S.Zero/S.Zero)
52
+ seterr(divide=False)
53
+ assert S.Zero / S.Zero is S.NaN
54
+
55
+
56
+ def test_mod():
57
+ x = S.Half
58
+ y = Rational(3, 4)
59
+ z = Rational(5, 18043)
60
+
61
+ assert x % x == 0
62
+ assert x % y == S.Half
63
+ assert x % z == Rational(3, 36086)
64
+ assert y % x == Rational(1, 4)
65
+ assert y % y == 0
66
+ assert y % z == Rational(9, 72172)
67
+ assert z % x == Rational(5, 18043)
68
+ assert z % y == Rational(5, 18043)
69
+ assert z % z == 0
70
+
71
+ a = Float(2.6)
72
+
73
+ assert (a % .2) == 0.0
74
+ assert (a % 2).round(15) == 0.6
75
+ assert (a % 0.5).round(15) == 0.1
76
+
77
+ p = Symbol('p', infinite=True)
78
+
79
+ assert oo % oo is nan
80
+ assert zoo % oo is nan
81
+ assert 5 % oo is nan
82
+ assert p % 5 is nan
83
+
84
+ # In these two tests, if the precision of m does
85
+ # not match the precision of the ans, then it is
86
+ # likely that the change made now gives an answer
87
+ # with degraded accuracy.
88
+ r = Rational(500, 41)
89
+ f = Float('.36', 3)
90
+ m = r % f
91
+ ans = Float(r % Rational(f), 3)
92
+ assert m == ans and m._prec == ans._prec
93
+ f = Float('8.36', 3)
94
+ m = f % r
95
+ ans = Float(Rational(f) % r, 3)
96
+ assert m == ans and m._prec == ans._prec
97
+
98
+ s = S.Zero
99
+
100
+ assert s % float(1) == 0.0
101
+
102
+ # No rounding required since these numbers can be represented
103
+ # exactly.
104
+ assert Rational(3, 4) % Float(1.1) == 0.75
105
+ assert Float(1.5) % Rational(5, 4) == 0.25
106
+ assert Rational(5, 4).__rmod__(Float('1.5')) == 0.25
107
+ assert Float('1.5').__rmod__(Float('2.75')) == Float('1.25')
108
+ assert 2.75 % Float('1.5') == Float('1.25')
109
+
110
+ a = Integer(7)
111
+ b = Integer(4)
112
+
113
+ assert type(a % b) == Integer
114
+ assert a % b == Integer(3)
115
+ assert Integer(1) % Rational(2, 3) == Rational(1, 3)
116
+ assert Rational(7, 5) % Integer(1) == Rational(2, 5)
117
+ assert Integer(2) % 1.5 == 0.5
118
+
119
+ assert Integer(3).__rmod__(Integer(10)) == Integer(1)
120
+ assert Integer(10) % 4 == Integer(2)
121
+ assert 15 % Integer(4) == Integer(3)
122
+
123
+
124
+ def test_divmod():
125
+ x = Symbol("x")
126
+ assert divmod(S(12), S(8)) == Tuple(1, 4)
127
+ assert divmod(-S(12), S(8)) == Tuple(-2, 4)
128
+ assert divmod(S.Zero, S.One) == Tuple(0, 0)
129
+ raises(ZeroDivisionError, lambda: divmod(S.Zero, S.Zero))
130
+ raises(ZeroDivisionError, lambda: divmod(S.One, S.Zero))
131
+ assert divmod(S(12), 8) == Tuple(1, 4)
132
+ assert divmod(12, S(8)) == Tuple(1, 4)
133
+ assert S(1024)//x == 1024//x == floor(1024/x)
134
+
135
+ assert divmod(S("2"), S("3/2")) == Tuple(S("1"), S("1/2"))
136
+ assert divmod(S("3/2"), S("2")) == Tuple(S("0"), S("3/2"))
137
+ assert divmod(S("2"), S("3.5")) == Tuple(S("0"), S("2"))
138
+ assert divmod(S("3.5"), S("2")) == Tuple(S("1"), S("1.5"))
139
+ assert divmod(S("2"), S("1/3")) == Tuple(S("6"), S("0"))
140
+ assert divmod(S("1/3"), S("2")) == Tuple(S("0"), S("1/3"))
141
+ assert divmod(S("2"), S("1/10")) == Tuple(S("20"), S("0"))
142
+ assert divmod(S("2"), S(".1"))[0] == 19
143
+ assert divmod(S("0.1"), S("2")) == Tuple(S("0"), S("0.1"))
144
+ assert divmod(S("2"), 2) == Tuple(S("1"), S("0"))
145
+ assert divmod(2, S("2")) == Tuple(S("1"), S("0"))
146
+ assert divmod(S("2"), 1.5) == Tuple(S("1"), S("0.5"))
147
+ assert divmod(1.5, S("2")) == Tuple(S("0"), S("1.5"))
148
+ assert divmod(0.3, S("2")) == Tuple(S("0"), S("0.3"))
149
+ assert divmod(S("3/2"), S("3.5")) == Tuple(S("0"), S("3/2"))
150
+ assert divmod(S("3.5"), S("3/2")) == Tuple(S("2"), S("0.5"))
151
+ assert divmod(S("3/2"), S("1/3")) == Tuple(S("4"), S("1/6"))
152
+ assert divmod(S("1/3"), S("3/2")) == Tuple(S("0"), S("1/3"))
153
+ assert divmod(S("3/2"), S("0.1"))[0] == 14
154
+ assert divmod(S("0.1"), S("3/2")) == Tuple(S("0"), S("0.1"))
155
+ assert divmod(S("3/2"), 2) == Tuple(S("0"), S("3/2"))
156
+ assert divmod(2, S("3/2")) == Tuple(S("1"), S("1/2"))
157
+ assert divmod(S("3/2"), 1.5) == Tuple(S("1"), S("0"))
158
+ assert divmod(1.5, S("3/2")) == Tuple(S("1"), S("0"))
159
+ assert divmod(S("3/2"), 0.3) == Tuple(S("5"), S("0"))
160
+ assert divmod(0.3, S("3/2")) == Tuple(S("0"), S("0.3"))
161
+ assert divmod(S("1/3"), S("3.5")) == Tuple(S("0"), S("1/3"))
162
+ assert divmod(S("3.5"), S("0.1")) == Tuple(S("35"), S("0"))
163
+ assert divmod(S("0.1"), S("3.5")) == Tuple(S("0"), S("0.1"))
164
+ assert divmod(S("3.5"), 2) == Tuple(S("1"), S("1.5"))
165
+ assert divmod(2, S("3.5")) == Tuple(S("0"), S("2"))
166
+ assert divmod(S("3.5"), 1.5) == Tuple(S("2"), S("0.5"))
167
+ assert divmod(1.5, S("3.5")) == Tuple(S("0"), S("1.5"))
168
+ assert divmod(0.3, S("3.5")) == Tuple(S("0"), S("0.3"))
169
+ assert divmod(S("0.1"), S("1/3")) == Tuple(S("0"), S("0.1"))
170
+ assert divmod(S("1/3"), 2) == Tuple(S("0"), S("1/3"))
171
+ assert divmod(2, S("1/3")) == Tuple(S("6"), S("0"))
172
+ assert divmod(S("1/3"), 1.5) == Tuple(S("0"), S("1/3"))
173
+ assert divmod(0.3, S("1/3")) == Tuple(S("0"), S("0.3"))
174
+ assert divmod(S("0.1"), 2) == Tuple(S("0"), S("0.1"))
175
+ assert divmod(2, S("0.1"))[0] == 19
176
+ assert divmod(S("0.1"), 1.5) == Tuple(S("0"), S("0.1"))
177
+ assert divmod(1.5, S("0.1")) == Tuple(S("15"), S("0"))
178
+ assert divmod(S("0.1"), 0.3) == Tuple(S("0"), S("0.1"))
179
+
180
+ assert str(divmod(S("2"), 0.3)) == '(6, 0.2)'
181
+ assert str(divmod(S("3.5"), S("1/3"))) == '(10, 0.166666666666667)'
182
+ assert str(divmod(S("3.5"), 0.3)) == '(11, 0.2)'
183
+ assert str(divmod(S("1/3"), S("0.1"))) == '(3, 0.0333333333333333)'
184
+ assert str(divmod(1.5, S("1/3"))) == '(4, 0.166666666666667)'
185
+ assert str(divmod(S("1/3"), 0.3)) == '(1, 0.0333333333333333)'
186
+ assert str(divmod(0.3, S("0.1"))) == '(2, 0.1)'
187
+
188
+ assert divmod(-3, S(2)) == (-2, 1)
189
+ assert divmod(S(-3), S(2)) == (-2, 1)
190
+ assert divmod(S(-3), 2) == (-2, 1)
191
+
192
+ assert divmod(S(4), S(-3.1)) == Tuple(-2, -2.2)
193
+ assert divmod(S(4), S(-2.1)) == divmod(4, -2.1)
194
+ assert divmod(S(-8), S(-2.5) ) == Tuple(3, -0.5)
195
+
196
+ assert divmod(oo, 1) == (S.NaN, S.NaN)
197
+ assert divmod(S.NaN, 1) == (S.NaN, S.NaN)
198
+ assert divmod(1, S.NaN) == (S.NaN, S.NaN)
199
+ ans = [(-1, oo), (-1, oo), (0, 0), (0, 1), (0, 2)]
200
+ OO = float('inf')
201
+ ANS = [tuple(map(float, i)) for i in ans]
202
+ assert [divmod(i, oo) for i in range(-2, 3)] == ans
203
+ ans = [(0, -2), (0, -1), (0, 0), (-1, -oo), (-1, -oo)]
204
+ ANS = [tuple(map(float, i)) for i in ans]
205
+ assert [divmod(i, -oo) for i in range(-2, 3)] == ans
206
+ assert [divmod(i, -OO) for i in range(-2, 3)] == ANS
207
+ assert divmod(S(3.5), S(-2)) == divmod(3.5, -2)
208
+ assert divmod(-S(3.5), S(-2)) == divmod(-3.5, -2)
209
+ assert divmod(S(0.0), S(9)) == divmod(0.0, 9)
210
+ assert divmod(S(0), S(9.0)) == divmod(0, 9.0)
211
+
212
+
213
+ def test_igcd():
214
+ assert igcd(0, 0) == 0
215
+ assert igcd(0, 1) == 1
216
+ assert igcd(1, 0) == 1
217
+ assert igcd(0, 7) == 7
218
+ assert igcd(7, 0) == 7
219
+ assert igcd(7, 1) == 1
220
+ assert igcd(1, 7) == 1
221
+ assert igcd(-1, 0) == 1
222
+ assert igcd(0, -1) == 1
223
+ assert igcd(-1, -1) == 1
224
+ assert igcd(-1, 7) == 1
225
+ assert igcd(7, -1) == 1
226
+ assert igcd(8, 2) == 2
227
+ assert igcd(4, 8) == 4
228
+ assert igcd(8, 16) == 8
229
+ assert igcd(7, -3) == 1
230
+ assert igcd(-7, 3) == 1
231
+ assert igcd(-7, -3) == 1
232
+ assert igcd(*[10, 20, 30]) == 10
233
+ raises(TypeError, lambda: igcd())
234
+ raises(TypeError, lambda: igcd(2))
235
+ raises(ValueError, lambda: igcd(0, None))
236
+ raises(ValueError, lambda: igcd(1, 2.2))
237
+ for args in permutations((45.1, 1, 30)):
238
+ raises(ValueError, lambda: igcd(*args))
239
+ for args in permutations((1, 2, None)):
240
+ raises(ValueError, lambda: igcd(*args))
241
+
242
+
243
+ def test_igcd_lehmer():
244
+ a, b = fibonacci(10001), fibonacci(10000)
245
+ # len(str(a)) == 2090
246
+ # small divisors, long Euclidean sequence
247
+ assert igcd_lehmer(a, b) == 1
248
+ c = fibonacci(100)
249
+ assert igcd_lehmer(a*c, b*c) == c
250
+ # big divisor
251
+ assert igcd_lehmer(a, 10**1000) == 1
252
+ # swapping argument
253
+ assert igcd_lehmer(1, 2) == igcd_lehmer(2, 1)
254
+
255
+
256
+ def test_igcd2():
257
+ # short loop
258
+ assert igcd2(2**100 - 1, 2**99 - 1) == 1
259
+ # Lehmer's algorithm
260
+ a, b = int(fibonacci(10001)), int(fibonacci(10000))
261
+ assert igcd2(a, b) == 1
262
+
263
+
264
+ def test_ilcm():
265
+ assert ilcm(0, 0) == 0
266
+ assert ilcm(1, 0) == 0
267
+ assert ilcm(0, 1) == 0
268
+ assert ilcm(1, 1) == 1
269
+ assert ilcm(2, 1) == 2
270
+ assert ilcm(8, 2) == 8
271
+ assert ilcm(8, 6) == 24
272
+ assert ilcm(8, 7) == 56
273
+ assert ilcm(*[10, 20, 30]) == 60
274
+ raises(ValueError, lambda: ilcm(8.1, 7))
275
+ raises(ValueError, lambda: ilcm(8, 7.1))
276
+ raises(TypeError, lambda: ilcm(8))
277
+
278
+
279
+ def test_igcdex():
280
+ assert igcdex(2, 3) == (-1, 1, 1)
281
+ assert igcdex(10, 12) == (-1, 1, 2)
282
+ assert igcdex(100, 2004) == (-20, 1, 4)
283
+ assert igcdex(0, 0) == (0, 1, 0)
284
+ assert igcdex(1, 0) == (1, 0, 1)
285
+
286
+
287
+ def _strictly_equal(a, b):
288
+ return (a.p, a.q, type(a.p), type(a.q)) == \
289
+ (b.p, b.q, type(b.p), type(b.q))
290
+
291
+
292
+ def _test_rational_new(cls):
293
+ """
294
+ Tests that are common between Integer and Rational.
295
+ """
296
+ assert cls(0) is S.Zero
297
+ assert cls(1) is S.One
298
+ assert cls(-1) is S.NegativeOne
299
+ # These look odd, but are similar to int():
300
+ assert cls('1') is S.One
301
+ assert cls('-1') is S.NegativeOne
302
+
303
+ i = Integer(10)
304
+ assert _strictly_equal(i, cls('10'))
305
+ assert _strictly_equal(i, cls('10'))
306
+ assert _strictly_equal(i, cls(int(10)))
307
+ assert _strictly_equal(i, cls(i))
308
+
309
+ raises(TypeError, lambda: cls(Symbol('x')))
310
+
311
+
312
+ def test_Integer_new():
313
+ """
314
+ Test for Integer constructor
315
+ """
316
+ _test_rational_new(Integer)
317
+
318
+ assert _strictly_equal(Integer(0.9), S.Zero)
319
+ assert _strictly_equal(Integer(10.5), Integer(10))
320
+ raises(ValueError, lambda: Integer("10.5"))
321
+ assert Integer(Rational('1.' + '9'*20)) == 1
322
+
323
+
324
+ def test_Rational_new():
325
+ """"
326
+ Test for Rational constructor
327
+ """
328
+ _test_rational_new(Rational)
329
+
330
+ n1 = S.Half
331
+ assert n1 == Rational(Integer(1), 2)
332
+ assert n1 == Rational(Integer(1), Integer(2))
333
+ assert n1 == Rational(1, Integer(2))
334
+ assert n1 == Rational(S.Half)
335
+ assert 1 == Rational(n1, n1)
336
+ assert Rational(3, 2) == Rational(S.Half, Rational(1, 3))
337
+ assert Rational(3, 1) == Rational(1, Rational(1, 3))
338
+ n3_4 = Rational(3, 4)
339
+ assert Rational('3/4') == n3_4
340
+ assert -Rational('-3/4') == n3_4
341
+ assert Rational('.76').limit_denominator(4) == n3_4
342
+ assert Rational(19, 25).limit_denominator(4) == n3_4
343
+ assert Rational('19/25').limit_denominator(4) == n3_4
344
+ assert Rational(1.0, 3) == Rational(1, 3)
345
+ assert Rational(1, 3.0) == Rational(1, 3)
346
+ assert Rational(Float(0.5)) == S.Half
347
+ assert Rational('1e2/1e-2') == Rational(10000)
348
+ assert Rational('1 234') == Rational(1234)
349
+ assert Rational('1/1 234') == Rational(1, 1234)
350
+ assert Rational(-1, 0) is S.ComplexInfinity
351
+ assert Rational(1, 0) is S.ComplexInfinity
352
+ # Make sure Rational doesn't lose precision on Floats
353
+ assert Rational(pi.evalf(100)).evalf(100) == pi.evalf(100)
354
+ raises(TypeError, lambda: Rational('3**3'))
355
+ raises(TypeError, lambda: Rational('1/2 + 2/3'))
356
+
357
+ # handle fractions.Fraction instances
358
+ try:
359
+ import fractions
360
+ assert Rational(fractions.Fraction(1, 2)) == S.Half
361
+ except ImportError:
362
+ pass
363
+
364
+ assert Rational(mpq(2, 6)) == Rational(1, 3)
365
+ assert Rational(PythonRational(2, 6)) == Rational(1, 3)
366
+
367
+ assert Rational(2, 4, gcd=1).q == 4
368
+ n = Rational(2, -4, gcd=1)
369
+ assert n.q == 4
370
+ assert n.p == -2
371
+
372
+ def test_issue_24543():
373
+ for p in ('1.5', 1.5, 2):
374
+ for q in ('1.5', 1.5, 2):
375
+ assert Rational(p, q).as_numer_denom() == Rational('%s/%s'%(p,q)).as_numer_denom()
376
+
377
+ assert Rational('0.5', '100') == Rational(1, 200)
378
+
379
+
380
+ def test_Number_new():
381
+ """"
382
+ Test for Number constructor
383
+ """
384
+ # Expected behavior on numbers and strings
385
+ assert Number(1) is S.One
386
+ assert Number(2).__class__ is Integer
387
+ assert Number(-622).__class__ is Integer
388
+ assert Number(5, 3).__class__ is Rational
389
+ assert Number(5.3).__class__ is Float
390
+ assert Number('1') is S.One
391
+ assert Number('2').__class__ is Integer
392
+ assert Number('-622').__class__ is Integer
393
+ assert Number('5/3').__class__ is Rational
394
+ assert Number('5.3').__class__ is Float
395
+ raises(ValueError, lambda: Number('cos'))
396
+ raises(TypeError, lambda: Number(cos))
397
+ a = Rational(3, 5)
398
+ assert Number(a) is a # Check idempotence on Numbers
399
+ u = ['inf', '-inf', 'nan', 'iNF', '+inf']
400
+ v = [oo, -oo, nan, oo, oo]
401
+ for i, a in zip(u, v):
402
+ assert Number(i) is a, (i, Number(i), a)
403
+
404
+
405
+ def test_Number_cmp():
406
+ n1 = Number(1)
407
+ n2 = Number(2)
408
+ n3 = Number(-3)
409
+
410
+ assert n1 < n2
411
+ assert n1 <= n2
412
+ assert n3 < n1
413
+ assert n2 > n3
414
+ assert n2 >= n3
415
+
416
+ raises(TypeError, lambda: n1 < S.NaN)
417
+ raises(TypeError, lambda: n1 <= S.NaN)
418
+ raises(TypeError, lambda: n1 > S.NaN)
419
+ raises(TypeError, lambda: n1 >= S.NaN)
420
+
421
+
422
+ def test_Rational_cmp():
423
+ n1 = Rational(1, 4)
424
+ n2 = Rational(1, 3)
425
+ n3 = Rational(2, 4)
426
+ n4 = Rational(2, -4)
427
+ n5 = Rational(0)
428
+ n6 = Rational(1)
429
+ n7 = Rational(3)
430
+ n8 = Rational(-3)
431
+
432
+ assert n8 < n5
433
+ assert n5 < n6
434
+ assert n6 < n7
435
+ assert n8 < n7
436
+ assert n7 > n8
437
+ assert (n1 + 1)**n2 < 2
438
+ assert ((n1 + n6)/n7) < 1
439
+
440
+ assert n4 < n3
441
+ assert n2 < n3
442
+ assert n1 < n2
443
+ assert n3 > n1
444
+ assert not n3 < n1
445
+ assert not (Rational(-1) > 0)
446
+ assert Rational(-1) < 0
447
+
448
+ raises(TypeError, lambda: n1 < S.NaN)
449
+ raises(TypeError, lambda: n1 <= S.NaN)
450
+ raises(TypeError, lambda: n1 > S.NaN)
451
+ raises(TypeError, lambda: n1 >= S.NaN)
452
+
453
+
454
+ def test_Float():
455
+ def eq(a, b):
456
+ t = Float("1.0E-15")
457
+ return (-t < a - b < t)
458
+
459
+ zeros = (0, S.Zero, 0., Float(0))
460
+ for i, j in permutations(zeros, 2):
461
+ assert i == j
462
+ for z in zeros:
463
+ assert z in zeros
464
+ assert S.Zero.is_zero
465
+
466
+ a = Float(2) ** Float(3)
467
+ assert eq(a.evalf(), Float(8))
468
+ assert eq((pi ** -1).evalf(), Float("0.31830988618379067"))
469
+ a = Float(2) ** Float(4)
470
+ assert eq(a.evalf(), Float(16))
471
+ assert (S(.3) == S(.5)) is False
472
+
473
+ mpf = (0, 5404319552844595, -52, 53)
474
+ x_str = Float((0, '13333333333333', -52, 53))
475
+ x_0xstr = Float((0, '0x13333333333333', -52, 53))
476
+ x2_str = Float((0, '26666666666666', -53, 54))
477
+ x_hex = Float((0, int(0x13333333333333), -52, 53))
478
+ x_dec = Float(mpf)
479
+ assert x_str == x_0xstr == x_hex == x_dec == Float(1.2)
480
+ # x2_str was entered slightly malformed in that the mantissa
481
+ # was even -- it should be odd and the even part should be
482
+ # included with the exponent, but this is resolved by normalization
483
+ # ONLY IF REQUIREMENTS of mpf_norm are met: the bitcount must
484
+ # be exact: double the mantissa ==> increase bc by 1
485
+ assert Float(1.2)._mpf_ == mpf
486
+ assert x2_str._mpf_ == mpf
487
+
488
+ assert Float((0, int(0), -123, -1)) is S.NaN
489
+ assert Float((0, int(0), -456, -2)) is S.Infinity
490
+ assert Float((1, int(0), -789, -3)) is S.NegativeInfinity
491
+ # if you don't give the full signature, it's not special
492
+ assert Float((0, int(0), -123)) == Float(0)
493
+ assert Float((0, int(0), -456)) == Float(0)
494
+ assert Float((1, int(0), -789)) == Float(0)
495
+
496
+ raises(ValueError, lambda: Float((0, 7, 1, 3), ''))
497
+
498
+ assert Float('0.0').is_finite is True
499
+ assert Float('0.0').is_negative is False
500
+ assert Float('0.0').is_positive is False
501
+ assert Float('0.0').is_infinite is False
502
+ assert Float('0.0').is_zero is True
503
+
504
+ # rationality properties
505
+ # if the integer test fails then the use of intlike
506
+ # should be removed from gamma_functions.py
507
+ assert Float(1).is_integer is False
508
+ assert Float(1).is_rational is None
509
+ assert Float(1).is_irrational is None
510
+ assert sqrt(2).n(15).is_rational is None
511
+ assert sqrt(2).n(15).is_irrational is None
512
+
513
+ # do not automatically evalf
514
+ def teq(a):
515
+ assert (a.evalf() == a) is False
516
+ assert (a.evalf() != a) is True
517
+ assert (a == a.evalf()) is False
518
+ assert (a != a.evalf()) is True
519
+
520
+ teq(pi)
521
+ teq(2*pi)
522
+ teq(cos(0.1, evaluate=False))
523
+
524
+ # long integer
525
+ i = 12345678901234567890
526
+ assert same_and_same_prec(Float(12, ''), Float('12', ''))
527
+ assert same_and_same_prec(Float(Integer(i), ''), Float(i, ''))
528
+ assert same_and_same_prec(Float(i, ''), Float(str(i), 20))
529
+ assert same_and_same_prec(Float(str(i)), Float(i, ''))
530
+ assert same_and_same_prec(Float(i), Float(i, ''))
531
+
532
+ # inexact floats (repeating binary = denom not multiple of 2)
533
+ # cannot have precision greater than 15
534
+ assert Float(.125, 22) == .125
535
+ assert Float(2.0, 22) == 2
536
+ assert float(Float('.12500000000000001', '')) == .125
537
+ raises(ValueError, lambda: Float(.12500000000000001, ''))
538
+
539
+ # allow spaces
540
+ assert Float('123 456.123 456') == Float('123456.123456')
541
+ assert Integer('123 456') == Integer('123456')
542
+ assert Rational('123 456.123 456') == Rational('123456.123456')
543
+ assert Float(' .3e2') == Float('0.3e2')
544
+
545
+ # allow underscore
546
+ assert Float('1_23.4_56') == Float('123.456')
547
+ assert Float('1_') == Float('1.0')
548
+ assert Float('1_.') == Float('1.0')
549
+ assert Float('1._') == Float('1.0')
550
+ assert Float('1__2') == Float('12.0')
551
+ # assert Float('1_23.4_5_6', 12) == Float('123.456', 12)
552
+ # ...but not in all cases (per Py 3.6)
553
+ raises(ValueError, lambda: Float('_1'))
554
+ raises(ValueError, lambda: Float('_inf'))
555
+
556
+ # allow auto precision detection
557
+ assert Float('.1', '') == Float(.1, 1)
558
+ assert Float('.125', '') == Float(.125, 3)
559
+ assert Float('.100', '') == Float(.1, 3)
560
+ assert Float('2.0', '') == Float('2', 2)
561
+
562
+ raises(ValueError, lambda: Float("12.3d-4", ""))
563
+ raises(ValueError, lambda: Float(12.3, ""))
564
+ raises(ValueError, lambda: Float('.'))
565
+ raises(ValueError, lambda: Float('-.'))
566
+
567
+ zero = Float('0.0')
568
+ assert Float('-0') == zero
569
+ assert Float('.0') == zero
570
+ assert Float('-.0') == zero
571
+ assert Float('-0.0') == zero
572
+ assert Float(0.0) == zero
573
+ assert Float(0) == zero
574
+ assert Float(0, '') == Float('0', '')
575
+ assert Float(1) == Float(1.0)
576
+ assert Float(S.Zero) == zero
577
+ assert Float(S.One) == Float(1.0)
578
+
579
+ assert Float(decimal.Decimal('0.1'), 3) == Float('.1', 3)
580
+ assert Float(decimal.Decimal('nan')) is S.NaN
581
+ assert Float(decimal.Decimal('Infinity')) is S.Infinity
582
+ assert Float(decimal.Decimal('-Infinity')) is S.NegativeInfinity
583
+
584
+ assert '{:.3f}'.format(Float(4.236622)) == '4.237'
585
+ assert '{:.35f}'.format(Float(pi.n(40), 40)) == \
586
+ '3.14159265358979323846264338327950288'
587
+
588
+ # unicode
589
+ assert Float('0.73908513321516064100000000') == \
590
+ Float('0.73908513321516064100000000')
591
+ assert Float('0.73908513321516064100000000', 28) == \
592
+ Float('0.73908513321516064100000000', 28)
593
+
594
+ # binary precision
595
+ # Decimal value 0.1 cannot be expressed precisely as a base 2 fraction
596
+ a = Float(S.One/10, dps=15)
597
+ b = Float(S.One/10, dps=16)
598
+ p = Float(S.One/10, precision=53)
599
+ q = Float(S.One/10, precision=54)
600
+ assert a._mpf_ == p._mpf_
601
+ assert not a._mpf_ == q._mpf_
602
+ assert not b._mpf_ == q._mpf_
603
+
604
+ # Precision specifying errors
605
+ raises(ValueError, lambda: Float("1.23", dps=3, precision=10))
606
+ raises(ValueError, lambda: Float("1.23", dps="", precision=10))
607
+ raises(ValueError, lambda: Float("1.23", dps=3, precision=""))
608
+ raises(ValueError, lambda: Float("1.23", dps="", precision=""))
609
+
610
+ # from NumberSymbol
611
+ assert same_and_same_prec(Float(pi, 32), pi.evalf(32))
612
+ assert same_and_same_prec(Float(Catalan), Catalan.evalf())
613
+
614
+ # oo and nan
615
+ u = ['inf', '-inf', 'nan', 'iNF', '+inf']
616
+ v = [oo, -oo, nan, oo, oo]
617
+ for i, a in zip(u, v):
618
+ assert Float(i) is a
619
+
620
+
621
+ def test_zero_not_false():
622
+ # https://github.com/sympy/sympy/issues/20796
623
+ assert (S(0.0) == S.false) is False
624
+ assert (S.false == S(0.0)) is False
625
+ assert (S(0) == S.false) is False
626
+ assert (S.false == S(0)) is False
627
+
628
+
629
+ @conserve_mpmath_dps
630
+ def test_float_mpf():
631
+ import mpmath
632
+ mpmath.mp.dps = 100
633
+ mp_pi = mpmath.pi()
634
+
635
+ assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100)
636
+
637
+ mpmath.mp.dps = 15
638
+
639
+ assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100)
640
+
641
+
642
+ def test_Float_RealElement():
643
+ repi = RealField(dps=100)(pi.evalf(100))
644
+ # We still have to pass the precision because Float doesn't know what
645
+ # RealElement is, but make sure it keeps full precision from the result.
646
+ assert Float(repi, 100) == pi.evalf(100)
647
+
648
+
649
+ def test_Float_default_to_highprec_from_str():
650
+ s = str(pi.evalf(128))
651
+ assert same_and_same_prec(Float(s), Float(s, ''))
652
+
653
+
654
+ def test_Float_eval():
655
+ a = Float(3.2)
656
+ assert (a**2).is_Float
657
+
658
+
659
+ def test_Float_issue_2107():
660
+ a = Float(0.1, 10)
661
+ b = Float("0.1", 10)
662
+
663
+ assert a - a == 0
664
+ assert a + (-a) == 0
665
+ assert S.Zero + a - a == 0
666
+ assert S.Zero + a + (-a) == 0
667
+
668
+ assert b - b == 0
669
+ assert b + (-b) == 0
670
+ assert S.Zero + b - b == 0
671
+ assert S.Zero + b + (-b) == 0
672
+
673
+
674
+ def test_issue_14289():
675
+ from sympy.polys.numberfields import to_number_field
676
+
677
+ a = 1 - sqrt(2)
678
+ b = to_number_field(a)
679
+ assert b.as_expr() == a
680
+ assert b.minpoly(a).expand() == 0
681
+
682
+
683
+ def test_Float_from_tuple():
684
+ a = Float((0, '1L', 0, 1))
685
+ b = Float((0, '1', 0, 1))
686
+ assert a == b
687
+
688
+
689
+ def test_Infinity():
690
+ assert oo != 1
691
+ assert 1*oo is oo
692
+ assert 1 != oo
693
+ assert oo != -oo
694
+ assert oo != Symbol("x")**3
695
+ assert oo + 1 is oo
696
+ assert 2 + oo is oo
697
+ assert 3*oo + 2 is oo
698
+ assert S.Half**oo == 0
699
+ assert S.Half**(-oo) is oo
700
+ assert -oo*3 is -oo
701
+ assert oo + oo is oo
702
+ assert -oo + oo*(-5) is -oo
703
+ assert 1/oo == 0
704
+ assert 1/(-oo) == 0
705
+ assert 8/oo == 0
706
+ assert oo % 2 is nan
707
+ assert 2 % oo is nan
708
+ assert oo/oo is nan
709
+ assert oo/-oo is nan
710
+ assert -oo/oo is nan
711
+ assert -oo/-oo is nan
712
+ assert oo - oo is nan
713
+ assert oo - -oo is oo
714
+ assert -oo - oo is -oo
715
+ assert -oo - -oo is nan
716
+ assert oo + -oo is nan
717
+ assert -oo + oo is nan
718
+ assert oo + oo is oo
719
+ assert -oo + oo is nan
720
+ assert oo + -oo is nan
721
+ assert -oo + -oo is -oo
722
+ assert oo*oo is oo
723
+ assert -oo*oo is -oo
724
+ assert oo*-oo is -oo
725
+ assert -oo*-oo is oo
726
+ assert oo/0 is oo
727
+ assert -oo/0 is -oo
728
+ assert 0/oo == 0
729
+ assert 0/-oo == 0
730
+ assert oo*0 is nan
731
+ assert -oo*0 is nan
732
+ assert 0*oo is nan
733
+ assert 0*-oo is nan
734
+ assert oo + 0 is oo
735
+ assert -oo + 0 is -oo
736
+ assert 0 + oo is oo
737
+ assert 0 + -oo is -oo
738
+ assert oo - 0 is oo
739
+ assert -oo - 0 is -oo
740
+ assert 0 - oo is -oo
741
+ assert 0 - -oo is oo
742
+ assert oo/2 is oo
743
+ assert -oo/2 is -oo
744
+ assert oo/-2 is -oo
745
+ assert -oo/-2 is oo
746
+ assert oo*2 is oo
747
+ assert -oo*2 is -oo
748
+ assert oo*-2 is -oo
749
+ assert 2/oo == 0
750
+ assert 2/-oo == 0
751
+ assert -2/oo == 0
752
+ assert -2/-oo == 0
753
+ assert 2*oo is oo
754
+ assert 2*-oo is -oo
755
+ assert -2*oo is -oo
756
+ assert -2*-oo is oo
757
+ assert 2 + oo is oo
758
+ assert 2 - oo is -oo
759
+ assert -2 + oo is oo
760
+ assert -2 - oo is -oo
761
+ assert 2 + -oo is -oo
762
+ assert 2 - -oo is oo
763
+ assert -2 + -oo is -oo
764
+ assert -2 - -oo is oo
765
+ assert S(2) + oo is oo
766
+ assert S(2) - oo is -oo
767
+ assert oo/I == -oo*I
768
+ assert -oo/I == oo*I
769
+ assert oo*float(1) == _inf and (oo*float(1)) is oo
770
+ assert -oo*float(1) == _ninf and (-oo*float(1)) is -oo
771
+ assert oo/float(1) == _inf and (oo/float(1)) is oo
772
+ assert -oo/float(1) == _ninf and (-oo/float(1)) is -oo
773
+ assert oo*float(-1) == _ninf and (oo*float(-1)) is -oo
774
+ assert -oo*float(-1) == _inf and (-oo*float(-1)) is oo
775
+ assert oo/float(-1) == _ninf and (oo/float(-1)) is -oo
776
+ assert -oo/float(-1) == _inf and (-oo/float(-1)) is oo
777
+ assert oo + float(1) == _inf and (oo + float(1)) is oo
778
+ assert -oo + float(1) == _ninf and (-oo + float(1)) is -oo
779
+ assert oo - float(1) == _inf and (oo - float(1)) is oo
780
+ assert -oo - float(1) == _ninf and (-oo - float(1)) is -oo
781
+ assert float(1)*oo == _inf and (float(1)*oo) is oo
782
+ assert float(1)*-oo == _ninf and (float(1)*-oo) is -oo
783
+ assert float(1)/oo == 0
784
+ assert float(1)/-oo == 0
785
+ assert float(-1)*oo == _ninf and (float(-1)*oo) is -oo
786
+ assert float(-1)*-oo == _inf and (float(-1)*-oo) is oo
787
+ assert float(-1)/oo == 0
788
+ assert float(-1)/-oo == 0
789
+ assert float(1) + oo is oo
790
+ assert float(1) + -oo is -oo
791
+ assert float(1) - oo is -oo
792
+ assert float(1) - -oo is oo
793
+ assert oo == float(oo)
794
+ assert (oo != float(oo)) is False
795
+ assert type(float(oo)) is float
796
+ assert -oo == float(-oo)
797
+ assert (-oo != float(-oo)) is False
798
+ assert type(float(-oo)) is float
799
+
800
+ assert Float('nan') is nan
801
+ assert nan*1.0 is nan
802
+ assert -1.0*nan is nan
803
+ assert nan*oo is nan
804
+ assert nan*-oo is nan
805
+ assert nan/oo is nan
806
+ assert nan/-oo is nan
807
+ assert nan + oo is nan
808
+ assert nan + -oo is nan
809
+ assert nan - oo is nan
810
+ assert nan - -oo is nan
811
+ assert -oo * S.Zero is nan
812
+
813
+ assert oo*nan is nan
814
+ assert -oo*nan is nan
815
+ assert oo/nan is nan
816
+ assert -oo/nan is nan
817
+ assert oo + nan is nan
818
+ assert -oo + nan is nan
819
+ assert oo - nan is nan
820
+ assert -oo - nan is nan
821
+ assert S.Zero * oo is nan
822
+ assert oo.is_Rational is False
823
+ assert isinstance(oo, Rational) is False
824
+
825
+ assert S.One/oo == 0
826
+ assert -S.One/oo == 0
827
+ assert S.One/-oo == 0
828
+ assert -S.One/-oo == 0
829
+ assert S.One*oo is oo
830
+ assert -S.One*oo is -oo
831
+ assert S.One*-oo is -oo
832
+ assert -S.One*-oo is oo
833
+ assert S.One/nan is nan
834
+ assert S.One - -oo is oo
835
+ assert S.One + nan is nan
836
+ assert S.One - nan is nan
837
+ assert nan - S.One is nan
838
+ assert nan/S.One is nan
839
+ assert -oo - S.One is -oo
840
+
841
+
842
+ def test_Infinity_2():
843
+ x = Symbol('x')
844
+ assert oo*x != oo
845
+ assert oo*(pi - 1) is oo
846
+ assert oo*(1 - pi) is -oo
847
+
848
+ assert (-oo)*x != -oo
849
+ assert (-oo)*(pi - 1) is -oo
850
+ assert (-oo)*(1 - pi) is oo
851
+
852
+ assert (-1)**S.NaN is S.NaN
853
+ assert oo - _inf is S.NaN
854
+ assert oo + _ninf is S.NaN
855
+ assert oo*0 is S.NaN
856
+ assert oo/_inf is S.NaN
857
+ assert oo/_ninf is S.NaN
858
+ assert oo**S.NaN is S.NaN
859
+ assert -oo + _inf is S.NaN
860
+ assert -oo - _ninf is S.NaN
861
+ assert -oo*S.NaN is S.NaN
862
+ assert -oo*0 is S.NaN
863
+ assert -oo/_inf is S.NaN
864
+ assert -oo/_ninf is S.NaN
865
+ assert -oo/S.NaN is S.NaN
866
+ assert abs(-oo) is oo
867
+ assert all((-oo)**i is S.NaN for i in (oo, -oo, S.NaN))
868
+ assert (-oo)**3 is -oo
869
+ assert (-oo)**2 is oo
870
+ assert abs(S.ComplexInfinity) is oo
871
+
872
+
873
+ def test_Mul_Infinity_Zero():
874
+ assert Float(0)*_inf is nan
875
+ assert Float(0)*_ninf is nan
876
+ assert Float(0)*_inf is nan
877
+ assert Float(0)*_ninf is nan
878
+ assert _inf*Float(0) is nan
879
+ assert _ninf*Float(0) is nan
880
+ assert _inf*Float(0) is nan
881
+ assert _ninf*Float(0) is nan
882
+
883
+
884
+ def test_Div_By_Zero():
885
+ assert 1/S.Zero is zoo
886
+ assert 1/Float(0) is zoo
887
+ assert 0/S.Zero is nan
888
+ assert 0/Float(0) is nan
889
+ assert S.Zero/0 is nan
890
+ assert Float(0)/0 is nan
891
+ assert -1/S.Zero is zoo
892
+ assert -1/Float(0) is zoo
893
+
894
+
895
+ @_both_exp_pow
896
+ def test_Infinity_inequations():
897
+ assert oo > pi
898
+ assert not (oo < pi)
899
+ assert exp(-3) < oo
900
+
901
+ assert _inf > pi
902
+ assert not (_inf < pi)
903
+ assert exp(-3) < _inf
904
+
905
+ raises(TypeError, lambda: oo < I)
906
+ raises(TypeError, lambda: oo <= I)
907
+ raises(TypeError, lambda: oo > I)
908
+ raises(TypeError, lambda: oo >= I)
909
+ raises(TypeError, lambda: -oo < I)
910
+ raises(TypeError, lambda: -oo <= I)
911
+ raises(TypeError, lambda: -oo > I)
912
+ raises(TypeError, lambda: -oo >= I)
913
+
914
+ raises(TypeError, lambda: I < oo)
915
+ raises(TypeError, lambda: I <= oo)
916
+ raises(TypeError, lambda: I > oo)
917
+ raises(TypeError, lambda: I >= oo)
918
+ raises(TypeError, lambda: I < -oo)
919
+ raises(TypeError, lambda: I <= -oo)
920
+ raises(TypeError, lambda: I > -oo)
921
+ raises(TypeError, lambda: I >= -oo)
922
+
923
+ assert oo > -oo and oo >= -oo
924
+ assert (oo < -oo) == False and (oo <= -oo) == False
925
+ assert -oo < oo and -oo <= oo
926
+ assert (-oo > oo) == False and (-oo >= oo) == False
927
+
928
+ assert (oo < oo) == False # issue 7775
929
+ assert (oo > oo) == False
930
+ assert (-oo > -oo) == False and (-oo < -oo) == False
931
+ assert oo >= oo and oo <= oo and -oo >= -oo and -oo <= -oo
932
+ assert (-oo < -_inf) == False
933
+ assert (oo > _inf) == False
934
+ assert -oo >= -_inf
935
+ assert oo <= _inf
936
+
937
+ x = Symbol('x')
938
+ b = Symbol('b', finite=True, real=True)
939
+ assert (x < oo) == Lt(x, oo) # issue 7775
940
+ assert b < oo and b > -oo and b <= oo and b >= -oo
941
+ assert oo > b and oo >= b and (oo < b) == False and (oo <= b) == False
942
+ assert (-oo > b) == False and (-oo >= b) == False and -oo < b and -oo <= b
943
+ assert (oo < x) == Lt(oo, x) and (oo > x) == Gt(oo, x)
944
+ assert (oo <= x) == Le(oo, x) and (oo >= x) == Ge(oo, x)
945
+ assert (-oo < x) == Lt(-oo, x) and (-oo > x) == Gt(-oo, x)
946
+ assert (-oo <= x) == Le(-oo, x) and (-oo >= x) == Ge(-oo, x)
947
+
948
+
949
+ def test_NaN():
950
+ assert nan is nan
951
+ assert nan != 1
952
+ assert 1*nan is nan
953
+ assert 1 != nan
954
+ assert -nan is nan
955
+ assert oo != Symbol("x")**3
956
+ assert 2 + nan is nan
957
+ assert 3*nan + 2 is nan
958
+ assert -nan*3 is nan
959
+ assert nan + nan is nan
960
+ assert -nan + nan*(-5) is nan
961
+ assert 8/nan is nan
962
+ raises(TypeError, lambda: nan > 0)
963
+ raises(TypeError, lambda: nan < 0)
964
+ raises(TypeError, lambda: nan >= 0)
965
+ raises(TypeError, lambda: nan <= 0)
966
+ raises(TypeError, lambda: 0 < nan)
967
+ raises(TypeError, lambda: 0 > nan)
968
+ raises(TypeError, lambda: 0 <= nan)
969
+ raises(TypeError, lambda: 0 >= nan)
970
+ assert nan**0 == 1 # as per IEEE 754
971
+ assert 1**nan is nan # IEEE 754 is not the best choice for symbolic work
972
+ # test Pow._eval_power's handling of NaN
973
+ assert Pow(nan, 0, evaluate=False)**2 == 1
974
+ for n in (1, 1., S.One, S.NegativeOne, Float(1)):
975
+ assert n + nan is nan
976
+ assert n - nan is nan
977
+ assert nan + n is nan
978
+ assert nan - n is nan
979
+ assert n/nan is nan
980
+ assert nan/n is nan
981
+
982
+
983
+ def test_special_numbers():
984
+ assert isinstance(S.NaN, Number) is True
985
+ assert isinstance(S.Infinity, Number) is True
986
+ assert isinstance(S.NegativeInfinity, Number) is True
987
+
988
+ assert S.NaN.is_number is True
989
+ assert S.Infinity.is_number is True
990
+ assert S.NegativeInfinity.is_number is True
991
+ assert S.ComplexInfinity.is_number is True
992
+
993
+ assert isinstance(S.NaN, Rational) is False
994
+ assert isinstance(S.Infinity, Rational) is False
995
+ assert isinstance(S.NegativeInfinity, Rational) is False
996
+
997
+ assert S.NaN.is_rational is not True
998
+ assert S.Infinity.is_rational is not True
999
+ assert S.NegativeInfinity.is_rational is not True
1000
+
1001
+
1002
+ def test_powers():
1003
+ assert integer_nthroot(1, 2) == (1, True)
1004
+ assert integer_nthroot(1, 5) == (1, True)
1005
+ assert integer_nthroot(2, 1) == (2, True)
1006
+ assert integer_nthroot(2, 2) == (1, False)
1007
+ assert integer_nthroot(2, 5) == (1, False)
1008
+ assert integer_nthroot(4, 2) == (2, True)
1009
+ assert integer_nthroot(123**25, 25) == (123, True)
1010
+ assert integer_nthroot(123**25 + 1, 25) == (123, False)
1011
+ assert integer_nthroot(123**25 - 1, 25) == (122, False)
1012
+ assert integer_nthroot(1, 1) == (1, True)
1013
+ assert integer_nthroot(0, 1) == (0, True)
1014
+ assert integer_nthroot(0, 3) == (0, True)
1015
+ assert integer_nthroot(10000, 1) == (10000, True)
1016
+ assert integer_nthroot(4, 2) == (2, True)
1017
+ assert integer_nthroot(16, 2) == (4, True)
1018
+ assert integer_nthroot(26, 2) == (5, False)
1019
+ assert integer_nthroot(1234567**7, 7) == (1234567, True)
1020
+ assert integer_nthroot(1234567**7 + 1, 7) == (1234567, False)
1021
+ assert integer_nthroot(1234567**7 - 1, 7) == (1234566, False)
1022
+ b = 25**1000
1023
+ assert integer_nthroot(b, 1000) == (25, True)
1024
+ assert integer_nthroot(b + 1, 1000) == (25, False)
1025
+ assert integer_nthroot(b - 1, 1000) == (24, False)
1026
+ c = 10**400
1027
+ c2 = c**2
1028
+ assert integer_nthroot(c2, 2) == (c, True)
1029
+ assert integer_nthroot(c2 + 1, 2) == (c, False)
1030
+ assert integer_nthroot(c2 - 1, 2) == (c - 1, False)
1031
+ assert integer_nthroot(2, 10**10) == (1, False)
1032
+
1033
+ p, r = integer_nthroot(int(factorial(10000)), 100)
1034
+ assert p % (10**10) == 5322420655
1035
+ assert not r
1036
+
1037
+ # Test that this is fast
1038
+ assert integer_nthroot(2, 10**10) == (1, False)
1039
+
1040
+ # output should be int if possible
1041
+ assert type(integer_nthroot(2**61, 2)[0]) is int
1042
+
1043
+
1044
+ def test_integer_nthroot_overflow():
1045
+ assert integer_nthroot(10**(50*50), 50) == (10**50, True)
1046
+ assert integer_nthroot(10**100000, 10000) == (10**10, True)
1047
+
1048
+
1049
+ def test_integer_log():
1050
+ raises(ValueError, lambda: integer_log(2, 1))
1051
+ raises(ValueError, lambda: integer_log(0, 2))
1052
+ raises(ValueError, lambda: integer_log(1.1, 2))
1053
+ raises(ValueError, lambda: integer_log(1, 2.2))
1054
+
1055
+ assert integer_log(1, 2) == (0, True)
1056
+ assert integer_log(1, 3) == (0, True)
1057
+ assert integer_log(2, 3) == (0, False)
1058
+ assert integer_log(3, 3) == (1, True)
1059
+ assert integer_log(3*2, 3) == (1, False)
1060
+ assert integer_log(3**2, 3) == (2, True)
1061
+ assert integer_log(3*4, 3) == (2, False)
1062
+ assert integer_log(3**3, 3) == (3, True)
1063
+ assert integer_log(27, 5) == (2, False)
1064
+ assert integer_log(2, 3) == (0, False)
1065
+ assert integer_log(-4, -2) == (2, False)
1066
+ assert integer_log(27, -3) == (3, False)
1067
+ assert integer_log(-49, 7) == (0, False)
1068
+ assert integer_log(-49, -7) == (2, False)
1069
+
1070
+
1071
+ def test_isqrt():
1072
+ from math import sqrt as _sqrt
1073
+ limit = 4503599761588223
1074
+ assert int(_sqrt(limit)) == integer_nthroot(limit, 2)[0]
1075
+ assert int(_sqrt(limit + 1)) != integer_nthroot(limit + 1, 2)[0]
1076
+ assert isqrt(limit + 1) == integer_nthroot(limit + 1, 2)[0]
1077
+ assert isqrt(limit + S.Half) == integer_nthroot(limit, 2)[0]
1078
+ assert isqrt(limit + 1 + S.Half) == integer_nthroot(limit + 1, 2)[0]
1079
+ assert isqrt(limit + 2 + S.Half) == integer_nthroot(limit + 2, 2)[0]
1080
+
1081
+ # Regression tests for https://github.com/sympy/sympy/issues/17034
1082
+ assert isqrt(4503599761588224) == 67108864
1083
+ assert isqrt(9999999999999999) == 99999999
1084
+
1085
+ # Other corner cases, especially involving non-integers.
1086
+ raises(ValueError, lambda: isqrt(-1))
1087
+ raises(ValueError, lambda: isqrt(-10**1000))
1088
+ raises(ValueError, lambda: isqrt(Rational(-1, 2)))
1089
+
1090
+ tiny = Rational(1, 10**1000)
1091
+ raises(ValueError, lambda: isqrt(-tiny))
1092
+ assert isqrt(1-tiny) == 0
1093
+ assert isqrt(4503599761588224-tiny) == 67108864
1094
+ assert isqrt(10**100 - tiny) == 10**50 - 1
1095
+
1096
+ # Check that using an inaccurate math.sqrt doesn't affect the results.
1097
+ from sympy.core import power
1098
+ old_sqrt = power._sqrt
1099
+ power._sqrt = lambda x: 2.999999999
1100
+ try:
1101
+ assert isqrt(9) == 3
1102
+ assert isqrt(10000) == 100
1103
+ finally:
1104
+ power._sqrt = old_sqrt
1105
+
1106
+
1107
+ def test_powers_Integer():
1108
+ """Test Integer._eval_power"""
1109
+ # check infinity
1110
+ assert S.One ** S.Infinity is S.NaN
1111
+ assert S.NegativeOne** S.Infinity is S.NaN
1112
+ assert S(2) ** S.Infinity is S.Infinity
1113
+ assert S(-2)** S.Infinity == zoo
1114
+ assert S(0) ** S.Infinity is S.Zero
1115
+
1116
+ # check Nan
1117
+ assert S.One ** S.NaN is S.NaN
1118
+ assert S.NegativeOne ** S.NaN is S.NaN
1119
+
1120
+ # check for exact roots
1121
+ assert S.NegativeOne ** Rational(6, 5) == - (-1)**(S.One/5)
1122
+ assert sqrt(S(4)) == 2
1123
+ assert sqrt(S(-4)) == I * 2
1124
+ assert S(16) ** Rational(1, 4) == 2
1125
+ assert S(-16) ** Rational(1, 4) == 2 * (-1)**Rational(1, 4)
1126
+ assert S(9) ** Rational(3, 2) == 27
1127
+ assert S(-9) ** Rational(3, 2) == -27*I
1128
+ assert S(27) ** Rational(2, 3) == 9
1129
+ assert S(-27) ** Rational(2, 3) == 9 * (S.NegativeOne ** Rational(2, 3))
1130
+ assert (-2) ** Rational(-2, 1) == Rational(1, 4)
1131
+
1132
+ # not exact roots
1133
+ assert sqrt(-3) == I*sqrt(3)
1134
+ assert (3) ** (Rational(3, 2)) == 3 * sqrt(3)
1135
+ assert (-3) ** (Rational(3, 2)) == - 3 * sqrt(-3)
1136
+ assert (-3) ** (Rational(5, 2)) == 9 * I * sqrt(3)
1137
+ assert (-3) ** (Rational(7, 2)) == - I * 27 * sqrt(3)
1138
+ assert (2) ** (Rational(3, 2)) == 2 * sqrt(2)
1139
+ assert (2) ** (Rational(-3, 2)) == sqrt(2) / 4
1140
+ assert (81) ** (Rational(2, 3)) == 9 * (S(3) ** (Rational(2, 3)))
1141
+ assert (-81) ** (Rational(2, 3)) == 9 * (S(-3) ** (Rational(2, 3)))
1142
+ assert (-3) ** Rational(-7, 3) == \
1143
+ -(-1)**Rational(2, 3)*3**Rational(2, 3)/27
1144
+ assert (-3) ** Rational(-2, 3) == \
1145
+ -(-1)**Rational(1, 3)*3**Rational(1, 3)/3
1146
+
1147
+ # join roots
1148
+ assert sqrt(6) + sqrt(24) == 3*sqrt(6)
1149
+ assert sqrt(2) * sqrt(3) == sqrt(6)
1150
+
1151
+ # separate symbols & constansts
1152
+ x = Symbol("x")
1153
+ assert sqrt(49 * x) == 7 * sqrt(x)
1154
+ assert sqrt((3 - sqrt(pi)) ** 2) == 3 - sqrt(pi)
1155
+
1156
+ # check that it is fast for big numbers
1157
+ assert (2**64 + 1) ** Rational(4, 3)
1158
+ assert (2**64 + 1) ** Rational(17, 25)
1159
+
1160
+ # negative rational power and negative base
1161
+ assert (-3) ** Rational(-7, 3) == \
1162
+ -(-1)**Rational(2, 3)*3**Rational(2, 3)/27
1163
+ assert (-3) ** Rational(-2, 3) == \
1164
+ -(-1)**Rational(1, 3)*3**Rational(1, 3)/3
1165
+ assert (-2) ** Rational(-10, 3) == \
1166
+ (-1)**Rational(2, 3)*2**Rational(2, 3)/16
1167
+ assert abs(Pow(-2, Rational(-10, 3)).n() -
1168
+ Pow(-2, Rational(-10, 3), evaluate=False).n()) < 1e-16
1169
+
1170
+ # negative base and rational power with some simplification
1171
+ assert (-8) ** Rational(2, 5) == \
1172
+ 2*(-1)**Rational(2, 5)*2**Rational(1, 5)
1173
+ assert (-4) ** Rational(9, 5) == \
1174
+ -8*(-1)**Rational(4, 5)*2**Rational(3, 5)
1175
+
1176
+ assert S(1234).factors() == {617: 1, 2: 1}
1177
+ assert Rational(2*3, 3*5*7).factors() == {2: 1, 5: -1, 7: -1}
1178
+
1179
+ # test that eval_power factors numbers bigger than
1180
+ # the current limit in factor_trial_division (2**15)
1181
+ from sympy.ntheory.generate import nextprime
1182
+ n = nextprime(2**15)
1183
+ assert sqrt(n**2) == n
1184
+ assert sqrt(n**3) == n*sqrt(n)
1185
+ assert sqrt(4*n) == 2*sqrt(n)
1186
+
1187
+ # check that factors of base with powers sharing gcd with power are removed
1188
+ assert (2**4*3)**Rational(1, 6) == 2**Rational(2, 3)*3**Rational(1, 6)
1189
+ assert (2**4*3)**Rational(5, 6) == 8*2**Rational(1, 3)*3**Rational(5, 6)
1190
+
1191
+ # check that bases sharing a gcd are exptracted
1192
+ assert 2**Rational(1, 3)*3**Rational(1, 4)*6**Rational(1, 5) == \
1193
+ 2**Rational(8, 15)*3**Rational(9, 20)
1194
+ assert sqrt(8)*24**Rational(1, 3)*6**Rational(1, 5) == \
1195
+ 4*2**Rational(7, 10)*3**Rational(8, 15)
1196
+ assert sqrt(8)*(-24)**Rational(1, 3)*(-6)**Rational(1, 5) == \
1197
+ 4*(-3)**Rational(8, 15)*2**Rational(7, 10)
1198
+ assert 2**Rational(1, 3)*2**Rational(8, 9) == 2*2**Rational(2, 9)
1199
+ assert 2**Rational(2, 3)*6**Rational(1, 3) == 2*3**Rational(1, 3)
1200
+ assert 2**Rational(2, 3)*6**Rational(8, 9) == \
1201
+ 2*2**Rational(5, 9)*3**Rational(8, 9)
1202
+ assert (-2)**Rational(2, S(3))*(-4)**Rational(1, S(3)) == -2*2**Rational(1, 3)
1203
+ assert 3*Pow(3, 2, evaluate=False) == 3**3
1204
+ assert 3*Pow(3, Rational(-1, 3), evaluate=False) == 3**Rational(2, 3)
1205
+ assert (-2)**Rational(1, 3)*(-3)**Rational(1, 4)*(-5)**Rational(5, 6) == \
1206
+ -(-1)**Rational(5, 12)*2**Rational(1, 3)*3**Rational(1, 4) * \
1207
+ 5**Rational(5, 6)
1208
+
1209
+ assert Integer(-2)**Symbol('', even=True) == \
1210
+ Integer(2)**Symbol('', even=True)
1211
+ assert (-1)**Float(.5) == 1.0*I
1212
+
1213
+
1214
+ def test_powers_Rational():
1215
+ """Test Rational._eval_power"""
1216
+ # check infinity
1217
+ assert S.Half ** S.Infinity == 0
1218
+ assert Rational(3, 2) ** S.Infinity is S.Infinity
1219
+ assert Rational(-1, 2) ** S.Infinity == 0
1220
+ assert Rational(-3, 2) ** S.Infinity == zoo
1221
+
1222
+ # check Nan
1223
+ assert Rational(3, 4) ** S.NaN is S.NaN
1224
+ assert Rational(-2, 3) ** S.NaN is S.NaN
1225
+
1226
+ # exact roots on numerator
1227
+ assert sqrt(Rational(4, 3)) == 2 * sqrt(3) / 3
1228
+ assert Rational(4, 3) ** Rational(3, 2) == 8 * sqrt(3) / 9
1229
+ assert sqrt(Rational(-4, 3)) == I * 2 * sqrt(3) / 3
1230
+ assert Rational(-4, 3) ** Rational(3, 2) == - I * 8 * sqrt(3) / 9
1231
+ assert Rational(27, 2) ** Rational(1, 3) == 3 * (2 ** Rational(2, 3)) / 2
1232
+ assert Rational(5**3, 8**3) ** Rational(4, 3) == Rational(5**4, 8**4)
1233
+
1234
+ # exact root on denominator
1235
+ assert sqrt(Rational(1, 4)) == S.Half
1236
+ assert sqrt(Rational(1, -4)) == I * S.Half
1237
+ assert sqrt(Rational(3, 4)) == sqrt(3) / 2
1238
+ assert sqrt(Rational(3, -4)) == I * sqrt(3) / 2
1239
+ assert Rational(5, 27) ** Rational(1, 3) == (5 ** Rational(1, 3)) / 3
1240
+
1241
+ # not exact roots
1242
+ assert sqrt(S.Half) == sqrt(2) / 2
1243
+ assert sqrt(Rational(-4, 7)) == I * sqrt(Rational(4, 7))
1244
+ assert Rational(-3, 2)**Rational(-7, 3) == \
1245
+ -4*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/27
1246
+ assert Rational(-3, 2)**Rational(-2, 3) == \
1247
+ -(-1)**Rational(1, 3)*2**Rational(2, 3)*3**Rational(1, 3)/3
1248
+ assert Rational(-3, 2)**Rational(-10, 3) == \
1249
+ 8*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/81
1250
+ assert abs(Pow(Rational(-2, 3), Rational(-7, 4)).n() -
1251
+ Pow(Rational(-2, 3), Rational(-7, 4), evaluate=False).n()) < 1e-16
1252
+
1253
+ # negative integer power and negative rational base
1254
+ assert Rational(-2, 3) ** Rational(-2, 1) == Rational(9, 4)
1255
+
1256
+ a = Rational(1, 10)
1257
+ assert a**Float(a, 2) == Float(a, 2)**Float(a, 2)
1258
+ assert Rational(-2, 3)**Symbol('', even=True) == \
1259
+ Rational(2, 3)**Symbol('', even=True)
1260
+
1261
+
1262
+ def test_powers_Float():
1263
+ assert str((S('-1/10')**S('3/10')).n()) == str(Float(-.1)**(.3))
1264
+
1265
+
1266
+ def test_lshift_Integer():
1267
+ assert Integer(0) << Integer(2) == Integer(0)
1268
+ assert Integer(0) << 2 == Integer(0)
1269
+ assert 0 << Integer(2) == Integer(0)
1270
+
1271
+ assert Integer(0b11) << Integer(0) == Integer(0b11)
1272
+ assert Integer(0b11) << 0 == Integer(0b11)
1273
+ assert 0b11 << Integer(0) == Integer(0b11)
1274
+
1275
+ assert Integer(0b11) << Integer(2) == Integer(0b11 << 2)
1276
+ assert Integer(0b11) << 2 == Integer(0b11 << 2)
1277
+ assert 0b11 << Integer(2) == Integer(0b11 << 2)
1278
+
1279
+ assert Integer(-0b11) << Integer(2) == Integer(-0b11 << 2)
1280
+ assert Integer(-0b11) << 2 == Integer(-0b11 << 2)
1281
+ assert -0b11 << Integer(2) == Integer(-0b11 << 2)
1282
+
1283
+ raises(TypeError, lambda: Integer(2) << 0.0)
1284
+ raises(TypeError, lambda: 0.0 << Integer(2))
1285
+ raises(ValueError, lambda: Integer(1) << Integer(-1))
1286
+
1287
+
1288
+ def test_rshift_Integer():
1289
+ assert Integer(0) >> Integer(2) == Integer(0)
1290
+ assert Integer(0) >> 2 == Integer(0)
1291
+ assert 0 >> Integer(2) == Integer(0)
1292
+
1293
+ assert Integer(0b11) >> Integer(0) == Integer(0b11)
1294
+ assert Integer(0b11) >> 0 == Integer(0b11)
1295
+ assert 0b11 >> Integer(0) == Integer(0b11)
1296
+
1297
+ assert Integer(0b11) >> Integer(2) == Integer(0)
1298
+ assert Integer(0b11) >> 2 == Integer(0)
1299
+ assert 0b11 >> Integer(2) == Integer(0)
1300
+
1301
+ assert Integer(-0b11) >> Integer(2) == Integer(-1)
1302
+ assert Integer(-0b11) >> 2 == Integer(-1)
1303
+ assert -0b11 >> Integer(2) == Integer(-1)
1304
+
1305
+ assert Integer(0b1100) >> Integer(2) == Integer(0b1100 >> 2)
1306
+ assert Integer(0b1100) >> 2 == Integer(0b1100 >> 2)
1307
+ assert 0b1100 >> Integer(2) == Integer(0b1100 >> 2)
1308
+
1309
+ assert Integer(-0b1100) >> Integer(2) == Integer(-0b1100 >> 2)
1310
+ assert Integer(-0b1100) >> 2 == Integer(-0b1100 >> 2)
1311
+ assert -0b1100 >> Integer(2) == Integer(-0b1100 >> 2)
1312
+
1313
+ raises(TypeError, lambda: Integer(0b10) >> 0.0)
1314
+ raises(TypeError, lambda: 0.0 >> Integer(2))
1315
+ raises(ValueError, lambda: Integer(1) >> Integer(-1))
1316
+
1317
+
1318
+ def test_and_Integer():
1319
+ assert Integer(0b01010101) & Integer(0b10101010) == Integer(0)
1320
+ assert Integer(0b01010101) & 0b10101010 == Integer(0)
1321
+ assert 0b01010101 & Integer(0b10101010) == Integer(0)
1322
+
1323
+ assert Integer(0b01010101) & Integer(0b11011011) == Integer(0b01010001)
1324
+ assert Integer(0b01010101) & 0b11011011 == Integer(0b01010001)
1325
+ assert 0b01010101 & Integer(0b11011011) == Integer(0b01010001)
1326
+
1327
+ assert -Integer(0b01010101) & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011)
1328
+ assert Integer(-0b01010101) & 0b11011011 == Integer(-0b01010101 & 0b11011011)
1329
+ assert -0b01010101 & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011)
1330
+
1331
+ assert Integer(0b01010101) & -Integer(0b11011011) == Integer(0b01010101 & -0b11011011)
1332
+ assert Integer(0b01010101) & -0b11011011 == Integer(0b01010101 & -0b11011011)
1333
+ assert 0b01010101 & Integer(-0b11011011) == Integer(0b01010101 & -0b11011011)
1334
+
1335
+ raises(TypeError, lambda: Integer(2) & 0.0)
1336
+ raises(TypeError, lambda: 0.0 & Integer(2))
1337
+
1338
+
1339
+ def test_xor_Integer():
1340
+ assert Integer(0b01010101) ^ Integer(0b11111111) == Integer(0b10101010)
1341
+ assert Integer(0b01010101) ^ 0b11111111 == Integer(0b10101010)
1342
+ assert 0b01010101 ^ Integer(0b11111111) == Integer(0b10101010)
1343
+
1344
+ assert Integer(0b01010101) ^ Integer(0b11011011) == Integer(0b10001110)
1345
+ assert Integer(0b01010101) ^ 0b11011011 == Integer(0b10001110)
1346
+ assert 0b01010101 ^ Integer(0b11011011) == Integer(0b10001110)
1347
+
1348
+ assert -Integer(0b01010101) ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011)
1349
+ assert Integer(-0b01010101) ^ 0b11011011 == Integer(-0b01010101 ^ 0b11011011)
1350
+ assert -0b01010101 ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011)
1351
+
1352
+ assert Integer(0b01010101) ^ -Integer(0b11011011) == Integer(0b01010101 ^ -0b11011011)
1353
+ assert Integer(0b01010101) ^ -0b11011011 == Integer(0b01010101 ^ -0b11011011)
1354
+ assert 0b01010101 ^ Integer(-0b11011011) == Integer(0b01010101 ^ -0b11011011)
1355
+
1356
+ raises(TypeError, lambda: Integer(2) ^ 0.0)
1357
+ raises(TypeError, lambda: 0.0 ^ Integer(2))
1358
+
1359
+
1360
+ def test_or_Integer():
1361
+ assert Integer(0b01010101) | Integer(0b10101010) == Integer(0b11111111)
1362
+ assert Integer(0b01010101) | 0b10101010 == Integer(0b11111111)
1363
+ assert 0b01010101 | Integer(0b10101010) == Integer(0b11111111)
1364
+
1365
+ assert Integer(0b01010101) | Integer(0b11011011) == Integer(0b11011111)
1366
+ assert Integer(0b01010101) | 0b11011011 == Integer(0b11011111)
1367
+ assert 0b01010101 | Integer(0b11011011) == Integer(0b11011111)
1368
+
1369
+ assert -Integer(0b01010101) | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011)
1370
+ assert Integer(-0b01010101) | 0b11011011 == Integer(-0b01010101 | 0b11011011)
1371
+ assert -0b01010101 | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011)
1372
+
1373
+ assert Integer(0b01010101) | -Integer(0b11011011) == Integer(0b01010101 | -0b11011011)
1374
+ assert Integer(0b01010101) | -0b11011011 == Integer(0b01010101 | -0b11011011)
1375
+ assert 0b01010101 | Integer(-0b11011011) == Integer(0b01010101 | -0b11011011)
1376
+
1377
+ raises(TypeError, lambda: Integer(2) | 0.0)
1378
+ raises(TypeError, lambda: 0.0 | Integer(2))
1379
+
1380
+
1381
+ def test_invert_Integer():
1382
+ assert ~Integer(0b01010101) == Integer(-0b01010110)
1383
+ assert ~Integer(0b01010101) == Integer(~0b01010101)
1384
+ assert ~(~Integer(0b01010101)) == Integer(0b01010101)
1385
+
1386
+
1387
+ def test_abs1():
1388
+ assert Rational(1, 6) != Rational(-1, 6)
1389
+ assert abs(Rational(1, 6)) == abs(Rational(-1, 6))
1390
+
1391
+
1392
+ def test_accept_int():
1393
+ assert Float(4) == 4
1394
+
1395
+
1396
+ def test_dont_accept_str():
1397
+ assert Float("0.2") != "0.2"
1398
+ assert not (Float("0.2") == "0.2")
1399
+
1400
+
1401
+ def test_int():
1402
+ a = Rational(5)
1403
+ assert int(a) == 5
1404
+ a = Rational(9, 10)
1405
+ assert int(a) == int(-a) == 0
1406
+ assert 1/(-1)**Rational(2, 3) == -(-1)**Rational(1, 3)
1407
+ # issue 10368
1408
+ a = Rational(32442016954, 78058255275)
1409
+ assert type(int(a)) is type(int(-a)) is int
1410
+
1411
+
1412
+ def test_int_NumberSymbols():
1413
+ assert int(Catalan) == 0
1414
+ assert int(EulerGamma) == 0
1415
+ assert int(pi) == 3
1416
+ assert int(E) == 2
1417
+ assert int(GoldenRatio) == 1
1418
+ assert int(TribonacciConstant) == 1
1419
+ for i in [Catalan, E, EulerGamma, GoldenRatio, TribonacciConstant, pi]:
1420
+ a, b = i.approximation_interval(Integer)
1421
+ ia = int(i)
1422
+ assert ia == a
1423
+ assert isinstance(ia, int)
1424
+ assert b == a + 1
1425
+ assert a.is_Integer and b.is_Integer
1426
+
1427
+
1428
+ def test_real_bug():
1429
+ x = Symbol("x")
1430
+ assert str(2.0*x*x) in ["(2.0*x)*x", "2.0*x**2", "2.00000000000000*x**2"]
1431
+ assert str(2.1*x*x) != "(2.0*x)*x"
1432
+
1433
+
1434
+ def test_bug_sqrt():
1435
+ assert ((sqrt(Rational(2)) + 1)*(sqrt(Rational(2)) - 1)).expand() == 1
1436
+
1437
+
1438
+ def test_pi_Pi():
1439
+ "Test that pi (instance) is imported, but Pi (class) is not"
1440
+ from sympy import pi # noqa
1441
+ with raises(ImportError):
1442
+ from sympy import Pi # noqa
1443
+
1444
+
1445
+ def test_no_len():
1446
+ # there should be no len for numbers
1447
+ raises(TypeError, lambda: len(Rational(2)))
1448
+ raises(TypeError, lambda: len(Rational(2, 3)))
1449
+ raises(TypeError, lambda: len(Integer(2)))
1450
+
1451
+
1452
+ def test_issue_3321():
1453
+ assert sqrt(Rational(1, 5)) == Rational(1, 5)**S.Half
1454
+ assert 5 * sqrt(Rational(1, 5)) == sqrt(5)
1455
+
1456
+
1457
+ def test_issue_3692():
1458
+ assert ((-1)**Rational(1, 6)).expand(complex=True) == I/2 + sqrt(3)/2
1459
+ assert ((-5)**Rational(1, 6)).expand(complex=True) == \
1460
+ 5**Rational(1, 6)*I/2 + 5**Rational(1, 6)*sqrt(3)/2
1461
+ assert ((-64)**Rational(1, 6)).expand(complex=True) == I + sqrt(3)
1462
+
1463
+
1464
+ def test_issue_3423():
1465
+ x = Symbol("x")
1466
+ assert sqrt(x - 1).as_base_exp() == (x - 1, S.Half)
1467
+ assert sqrt(x - 1) != I*sqrt(1 - x)
1468
+
1469
+
1470
+ def test_issue_3449():
1471
+ x = Symbol("x")
1472
+ assert sqrt(x - 1).subs(x, 5) == 2
1473
+
1474
+
1475
+ def test_issue_13890():
1476
+ x = Symbol("x")
1477
+ e = (-x/4 - S.One/12)**x - 1
1478
+ f = simplify(e)
1479
+ a = Rational(9, 5)
1480
+ assert abs(e.subs(x,a).evalf() - f.subs(x,a).evalf()) < 1e-15
1481
+
1482
+
1483
+ def test_Integer_factors():
1484
+ def F(i):
1485
+ return Integer(i).factors()
1486
+
1487
+ assert F(1) == {}
1488
+ assert F(2) == {2: 1}
1489
+ assert F(3) == {3: 1}
1490
+ assert F(4) == {2: 2}
1491
+ assert F(5) == {5: 1}
1492
+ assert F(6) == {2: 1, 3: 1}
1493
+ assert F(7) == {7: 1}
1494
+ assert F(8) == {2: 3}
1495
+ assert F(9) == {3: 2}
1496
+ assert F(10) == {2: 1, 5: 1}
1497
+ assert F(11) == {11: 1}
1498
+ assert F(12) == {2: 2, 3: 1}
1499
+ assert F(13) == {13: 1}
1500
+ assert F(14) == {2: 1, 7: 1}
1501
+ assert F(15) == {3: 1, 5: 1}
1502
+ assert F(16) == {2: 4}
1503
+ assert F(17) == {17: 1}
1504
+ assert F(18) == {2: 1, 3: 2}
1505
+ assert F(19) == {19: 1}
1506
+ assert F(20) == {2: 2, 5: 1}
1507
+ assert F(21) == {3: 1, 7: 1}
1508
+ assert F(22) == {2: 1, 11: 1}
1509
+ assert F(23) == {23: 1}
1510
+ assert F(24) == {2: 3, 3: 1}
1511
+ assert F(25) == {5: 2}
1512
+ assert F(26) == {2: 1, 13: 1}
1513
+ assert F(27) == {3: 3}
1514
+ assert F(28) == {2: 2, 7: 1}
1515
+ assert F(29) == {29: 1}
1516
+ assert F(30) == {2: 1, 3: 1, 5: 1}
1517
+ assert F(31) == {31: 1}
1518
+ assert F(32) == {2: 5}
1519
+ assert F(33) == {3: 1, 11: 1}
1520
+ assert F(34) == {2: 1, 17: 1}
1521
+ assert F(35) == {5: 1, 7: 1}
1522
+ assert F(36) == {2: 2, 3: 2}
1523
+ assert F(37) == {37: 1}
1524
+ assert F(38) == {2: 1, 19: 1}
1525
+ assert F(39) == {3: 1, 13: 1}
1526
+ assert F(40) == {2: 3, 5: 1}
1527
+ assert F(41) == {41: 1}
1528
+ assert F(42) == {2: 1, 3: 1, 7: 1}
1529
+ assert F(43) == {43: 1}
1530
+ assert F(44) == {2: 2, 11: 1}
1531
+ assert F(45) == {3: 2, 5: 1}
1532
+ assert F(46) == {2: 1, 23: 1}
1533
+ assert F(47) == {47: 1}
1534
+ assert F(48) == {2: 4, 3: 1}
1535
+ assert F(49) == {7: 2}
1536
+ assert F(50) == {2: 1, 5: 2}
1537
+ assert F(51) == {3: 1, 17: 1}
1538
+
1539
+
1540
+ def test_Rational_factors():
1541
+ def F(p, q, visual=None):
1542
+ return Rational(p, q).factors(visual=visual)
1543
+
1544
+ assert F(2, 3) == {2: 1, 3: -1}
1545
+ assert F(2, 9) == {2: 1, 3: -2}
1546
+ assert F(2, 15) == {2: 1, 3: -1, 5: -1}
1547
+ assert F(6, 10) == {3: 1, 5: -1}
1548
+
1549
+
1550
+ def test_issue_4107():
1551
+ assert pi*(E + 10) + pi*(-E - 10) != 0
1552
+ assert pi*(E + 10**10) + pi*(-E - 10**10) != 0
1553
+ assert pi*(E + 10**20) + pi*(-E - 10**20) != 0
1554
+ assert pi*(E + 10**80) + pi*(-E - 10**80) != 0
1555
+
1556
+ assert (pi*(E + 10) + pi*(-E - 10)).expand() == 0
1557
+ assert (pi*(E + 10**10) + pi*(-E - 10**10)).expand() == 0
1558
+ assert (pi*(E + 10**20) + pi*(-E - 10**20)).expand() == 0
1559
+ assert (pi*(E + 10**80) + pi*(-E - 10**80)).expand() == 0
1560
+
1561
+
1562
+ def test_IntegerInteger():
1563
+ a = Integer(4)
1564
+ b = Integer(a)
1565
+
1566
+ assert a == b
1567
+
1568
+
1569
+ def test_Rational_gcd_lcm_cofactors():
1570
+ assert Integer(4).gcd(2) == Integer(2)
1571
+ assert Integer(4).lcm(2) == Integer(4)
1572
+ assert Integer(4).gcd(Integer(2)) == Integer(2)
1573
+ assert Integer(4).lcm(Integer(2)) == Integer(4)
1574
+ a, b = 720**99911, 480**12342
1575
+ assert Integer(a).lcm(b) == a*b/Integer(a).gcd(b)
1576
+
1577
+ assert Integer(4).gcd(3) == Integer(1)
1578
+ assert Integer(4).lcm(3) == Integer(12)
1579
+ assert Integer(4).gcd(Integer(3)) == Integer(1)
1580
+ assert Integer(4).lcm(Integer(3)) == Integer(12)
1581
+
1582
+ assert Rational(4, 3).gcd(2) == Rational(2, 3)
1583
+ assert Rational(4, 3).lcm(2) == Integer(4)
1584
+ assert Rational(4, 3).gcd(Integer(2)) == Rational(2, 3)
1585
+ assert Rational(4, 3).lcm(Integer(2)) == Integer(4)
1586
+
1587
+ assert Integer(4).gcd(Rational(2, 9)) == Rational(2, 9)
1588
+ assert Integer(4).lcm(Rational(2, 9)) == Integer(4)
1589
+
1590
+ assert Rational(4, 3).gcd(Rational(2, 9)) == Rational(2, 9)
1591
+ assert Rational(4, 3).lcm(Rational(2, 9)) == Rational(4, 3)
1592
+ assert Rational(4, 5).gcd(Rational(2, 9)) == Rational(2, 45)
1593
+ assert Rational(4, 5).lcm(Rational(2, 9)) == Integer(4)
1594
+ assert Rational(5, 9).lcm(Rational(3, 7)) == Rational(Integer(5).lcm(3),Integer(9).gcd(7))
1595
+
1596
+ assert Integer(4).cofactors(2) == (Integer(2), Integer(2), Integer(1))
1597
+ assert Integer(4).cofactors(Integer(2)) == \
1598
+ (Integer(2), Integer(2), Integer(1))
1599
+
1600
+ assert Integer(4).gcd(Float(2.0)) == Float(1.0)
1601
+ assert Integer(4).lcm(Float(2.0)) == Float(8.0)
1602
+ assert Integer(4).cofactors(Float(2.0)) == (Float(1.0), Float(4.0), Float(2.0))
1603
+
1604
+ assert S.Half.gcd(Float(2.0)) == Float(1.0)
1605
+ assert S.Half.lcm(Float(2.0)) == Float(1.0)
1606
+ assert S.Half.cofactors(Float(2.0)) == \
1607
+ (Float(1.0), Float(0.5), Float(2.0))
1608
+
1609
+
1610
+ def test_Float_gcd_lcm_cofactors():
1611
+ assert Float(2.0).gcd(Integer(4)) == Float(1.0)
1612
+ assert Float(2.0).lcm(Integer(4)) == Float(8.0)
1613
+ assert Float(2.0).cofactors(Integer(4)) == (Float(1.0), Float(2.0), Float(4.0))
1614
+
1615
+ assert Float(2.0).gcd(S.Half) == Float(1.0)
1616
+ assert Float(2.0).lcm(S.Half) == Float(1.0)
1617
+ assert Float(2.0).cofactors(S.Half) == \
1618
+ (Float(1.0), Float(2.0), Float(0.5))
1619
+
1620
+
1621
+ def test_issue_4611():
1622
+ assert abs(pi._evalf(50) - 3.14159265358979) < 1e-10
1623
+ assert abs(E._evalf(50) - 2.71828182845905) < 1e-10
1624
+ assert abs(Catalan._evalf(50) - 0.915965594177219) < 1e-10
1625
+ assert abs(EulerGamma._evalf(50) - 0.577215664901533) < 1e-10
1626
+ assert abs(GoldenRatio._evalf(50) - 1.61803398874989) < 1e-10
1627
+ assert abs(TribonacciConstant._evalf(50) - 1.83928675521416) < 1e-10
1628
+
1629
+ x = Symbol("x")
1630
+ assert (pi + x).evalf() == pi.evalf() + x
1631
+ assert (E + x).evalf() == E.evalf() + x
1632
+ assert (Catalan + x).evalf() == Catalan.evalf() + x
1633
+ assert (EulerGamma + x).evalf() == EulerGamma.evalf() + x
1634
+ assert (GoldenRatio + x).evalf() == GoldenRatio.evalf() + x
1635
+ assert (TribonacciConstant + x).evalf() == TribonacciConstant.evalf() + x
1636
+
1637
+
1638
+ @conserve_mpmath_dps
1639
+ def test_conversion_to_mpmath():
1640
+ assert mpmath.mpmathify(Integer(1)) == mpmath.mpf(1)
1641
+ assert mpmath.mpmathify(S.Half) == mpmath.mpf(0.5)
1642
+ assert mpmath.mpmathify(Float('1.23', 15)) == mpmath.mpf('1.23')
1643
+
1644
+ assert mpmath.mpmathify(I) == mpmath.mpc(1j)
1645
+
1646
+ assert mpmath.mpmathify(1 + 2*I) == mpmath.mpc(1 + 2j)
1647
+ assert mpmath.mpmathify(1.0 + 2*I) == mpmath.mpc(1 + 2j)
1648
+ assert mpmath.mpmathify(1 + 2.0*I) == mpmath.mpc(1 + 2j)
1649
+ assert mpmath.mpmathify(1.0 + 2.0*I) == mpmath.mpc(1 + 2j)
1650
+ assert mpmath.mpmathify(S.Half + S.Half*I) == mpmath.mpc(0.5 + 0.5j)
1651
+
1652
+ assert mpmath.mpmathify(2*I) == mpmath.mpc(2j)
1653
+ assert mpmath.mpmathify(2.0*I) == mpmath.mpc(2j)
1654
+ assert mpmath.mpmathify(S.Half*I) == mpmath.mpc(0.5j)
1655
+
1656
+ mpmath.mp.dps = 100
1657
+ assert mpmath.mpmathify(pi.evalf(100) + pi.evalf(100)*I) == mpmath.pi + mpmath.pi*mpmath.j
1658
+ assert mpmath.mpmathify(pi.evalf(100)*I) == mpmath.pi*mpmath.j
1659
+
1660
+
1661
+ def test_relational():
1662
+ # real
1663
+ x = S(.1)
1664
+ assert (x != cos) is True
1665
+ assert (x == cos) is False
1666
+
1667
+ # rational
1668
+ x = Rational(1, 3)
1669
+ assert (x != cos) is True
1670
+ assert (x == cos) is False
1671
+
1672
+ # integer defers to rational so these tests are omitted
1673
+
1674
+ # number symbol
1675
+ x = pi
1676
+ assert (x != cos) is True
1677
+ assert (x == cos) is False
1678
+
1679
+
1680
+ def test_Integer_as_index():
1681
+ assert 'hello'[Integer(2):] == 'llo'
1682
+
1683
+
1684
+ def test_Rational_int():
1685
+ assert int( Rational(7, 5)) == 1
1686
+ assert int( S.Half) == 0
1687
+ assert int(Rational(-1, 2)) == 0
1688
+ assert int(-Rational(7, 5)) == -1
1689
+
1690
+
1691
+ def test_zoo():
1692
+ b = Symbol('b', finite=True)
1693
+ nz = Symbol('nz', nonzero=True)
1694
+ p = Symbol('p', positive=True)
1695
+ n = Symbol('n', negative=True)
1696
+ im = Symbol('i', imaginary=True)
1697
+ c = Symbol('c', complex=True)
1698
+ pb = Symbol('pb', positive=True)
1699
+ nb = Symbol('nb', negative=True)
1700
+ imb = Symbol('ib', imaginary=True, finite=True)
1701
+ for i in [I, S.Infinity, S.NegativeInfinity, S.Zero, S.One, S.Pi, S.Half, S(3), log(3),
1702
+ b, nz, p, n, im, pb, nb, imb, c]:
1703
+ if i.is_finite and (i.is_real or i.is_imaginary):
1704
+ assert i + zoo is zoo
1705
+ assert i - zoo is zoo
1706
+ assert zoo + i is zoo
1707
+ assert zoo - i is zoo
1708
+ elif i.is_finite is not False:
1709
+ assert (i + zoo).is_Add
1710
+ assert (i - zoo).is_Add
1711
+ assert (zoo + i).is_Add
1712
+ assert (zoo - i).is_Add
1713
+ else:
1714
+ assert (i + zoo) is S.NaN
1715
+ assert (i - zoo) is S.NaN
1716
+ assert (zoo + i) is S.NaN
1717
+ assert (zoo - i) is S.NaN
1718
+
1719
+ if fuzzy_not(i.is_zero) and (i.is_extended_real or i.is_imaginary):
1720
+ assert i*zoo is zoo
1721
+ assert zoo*i is zoo
1722
+ elif i.is_zero:
1723
+ assert i*zoo is S.NaN
1724
+ assert zoo*i is S.NaN
1725
+ else:
1726
+ assert (i*zoo).is_Mul
1727
+ assert (zoo*i).is_Mul
1728
+
1729
+ if fuzzy_not((1/i).is_zero) and (i.is_real or i.is_imaginary):
1730
+ assert zoo/i is zoo
1731
+ elif (1/i).is_zero:
1732
+ assert zoo/i is S.NaN
1733
+ elif i.is_zero:
1734
+ assert zoo/i is zoo
1735
+ else:
1736
+ assert (zoo/i).is_Mul
1737
+
1738
+ assert (I*oo).is_Mul # allow directed infinity
1739
+ assert zoo + zoo is S.NaN
1740
+ assert zoo * zoo is zoo
1741
+ assert zoo - zoo is S.NaN
1742
+ assert zoo/zoo is S.NaN
1743
+ assert zoo**zoo is S.NaN
1744
+ assert zoo**0 is S.One
1745
+ assert zoo**2 is zoo
1746
+ assert 1/zoo is S.Zero
1747
+
1748
+ assert Mul.flatten([S.NegativeOne, oo, S(0)]) == ([S.NaN], [], None)
1749
+
1750
+
1751
+ def test_issue_4122():
1752
+ x = Symbol('x', nonpositive=True)
1753
+ assert oo + x is oo
1754
+ x = Symbol('x', extended_nonpositive=True)
1755
+ assert (oo + x).is_Add
1756
+ x = Symbol('x', finite=True)
1757
+ assert (oo + x).is_Add # x could be imaginary
1758
+ x = Symbol('x', nonnegative=True)
1759
+ assert oo + x is oo
1760
+ x = Symbol('x', extended_nonnegative=True)
1761
+ assert oo + x is oo
1762
+ x = Symbol('x', finite=True, real=True)
1763
+ assert oo + x is oo
1764
+
1765
+ # similarly for negative infinity
1766
+ x = Symbol('x', nonnegative=True)
1767
+ assert -oo + x is -oo
1768
+ x = Symbol('x', extended_nonnegative=True)
1769
+ assert (-oo + x).is_Add
1770
+ x = Symbol('x', finite=True)
1771
+ assert (-oo + x).is_Add
1772
+ x = Symbol('x', nonpositive=True)
1773
+ assert -oo + x is -oo
1774
+ x = Symbol('x', extended_nonpositive=True)
1775
+ assert -oo + x is -oo
1776
+ x = Symbol('x', finite=True, real=True)
1777
+ assert -oo + x is -oo
1778
+
1779
+
1780
+ def test_GoldenRatio_expand():
1781
+ assert GoldenRatio.expand(func=True) == S.Half + sqrt(5)/2
1782
+
1783
+
1784
+ def test_TribonacciConstant_expand():
1785
+ assert TribonacciConstant.expand(func=True) == \
1786
+ (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
1787
+
1788
+
1789
+ def test_as_content_primitive():
1790
+ assert S.Zero.as_content_primitive() == (1, 0)
1791
+ assert S.Half.as_content_primitive() == (S.Half, 1)
1792
+ assert (Rational(-1, 2)).as_content_primitive() == (S.Half, -1)
1793
+ assert S(3).as_content_primitive() == (3, 1)
1794
+ assert S(3.1).as_content_primitive() == (1, 3.1)
1795
+
1796
+
1797
+ def test_hashing_sympy_integers():
1798
+ # Test for issue 5072
1799
+ assert {Integer(3)} == {int(3)}
1800
+ assert hash(Integer(4)) == hash(int(4))
1801
+
1802
+
1803
+ def test_rounding_issue_4172():
1804
+ assert int((E**100).round()) == \
1805
+ 26881171418161354484126255515800135873611119
1806
+ assert int((pi**100).round()) == \
1807
+ 51878483143196131920862615246303013562686760680406
1808
+ assert int((Rational(1)/EulerGamma**100).round()) == \
1809
+ 734833795660954410469466
1810
+
1811
+
1812
+ @XFAIL
1813
+ def test_mpmath_issues():
1814
+ from mpmath.libmp.libmpf import _normalize
1815
+ import mpmath.libmp as mlib
1816
+ rnd = mlib.round_nearest
1817
+ mpf = (0, int(0), -123, -1, 53, rnd) # nan
1818
+ assert _normalize(mpf, 53) != (0, int(0), 0, 0)
1819
+ mpf = (0, int(0), -456, -2, 53, rnd) # +inf
1820
+ assert _normalize(mpf, 53) != (0, int(0), 0, 0)
1821
+ mpf = (1, int(0), -789, -3, 53, rnd) # -inf
1822
+ assert _normalize(mpf, 53) != (0, int(0), 0, 0)
1823
+
1824
+ from mpmath.libmp.libmpf import fnan
1825
+ assert mlib.mpf_eq(fnan, fnan)
1826
+
1827
+
1828
+ def test_Catalan_EulerGamma_prec():
1829
+ n = GoldenRatio
1830
+ f = Float(n.n(), 5)
1831
+ assert f._mpf_ == (0, int(212079), -17, 18)
1832
+ assert f._prec == 20
1833
+ assert n._as_mpf_val(20) == f._mpf_
1834
+
1835
+ n = EulerGamma
1836
+ f = Float(n.n(), 5)
1837
+ assert f._mpf_ == (0, int(302627), -19, 19)
1838
+ assert f._prec == 20
1839
+ assert n._as_mpf_val(20) == f._mpf_
1840
+
1841
+
1842
+ def test_Catalan_rewrite():
1843
+ k = Dummy('k', integer=True, nonnegative=True)
1844
+ assert Catalan.rewrite(Sum).dummy_eq(
1845
+ Sum((-1)**k/(2*k + 1)**2, (k, 0, oo)))
1846
+ assert Catalan.rewrite() == Catalan
1847
+
1848
+
1849
+ def test_bool_eq():
1850
+ assert 0 == False
1851
+ assert S(0) == False
1852
+ assert S(0) != S.false
1853
+ assert 1 == True
1854
+ assert S.One == True
1855
+ assert S.One != S.true
1856
+
1857
+
1858
+ def test_Float_eq():
1859
+ # all .5 values are the same
1860
+ assert Float(.5, 10) == Float(.5, 11) == Float(.5, 1)
1861
+ # but floats that aren't exact in base-2 still
1862
+ # don't compare the same because they have different
1863
+ # underlying mpf values
1864
+ assert Float(.12, 3) != Float(.12, 4)
1865
+ assert Float(.12, 3) != .12
1866
+ assert 0.12 != Float(.12, 3)
1867
+ assert Float('.12', 22) != .12
1868
+ # issue 11707
1869
+ # but Float/Rational -- except for 0 --
1870
+ # are exact so Rational(x) = Float(y) only if
1871
+ # Rational(x) == Rational(Float(y))
1872
+ assert Float('1.1') != Rational(11, 10)
1873
+ assert Rational(11, 10) != Float('1.1')
1874
+ # coverage
1875
+ assert not Float(3) == 2
1876
+ assert not Float(2**2) == S.Half
1877
+ assert Float(2**2) == 4
1878
+ assert not Float(2**-2) == 1
1879
+ assert Float(2**-1) == S.Half
1880
+ assert not Float(2*3) == 3
1881
+ assert not Float(2*3) == S.Half
1882
+ assert Float(2*3) == 6
1883
+ assert not Float(2*3) == 8
1884
+ assert Float(.75) == Rational(3, 4)
1885
+ assert Float(5/18) == 5/18
1886
+ # 4473
1887
+ assert Float(2.) != 3
1888
+ assert Float((0,1,-3)) == S.One/8
1889
+ assert Float((0,1,-3)) != S.One/9
1890
+ # 16196
1891
+ assert 2 == Float(2) # as per Python
1892
+ # but in a computation...
1893
+ assert t**2 != t**2.0
1894
+
1895
+
1896
+ def test_issue_6640():
1897
+ from mpmath.libmp.libmpf import finf, fninf
1898
+ # fnan is not included because Float no longer returns fnan,
1899
+ # but otherwise, the same sort of test could apply
1900
+ assert Float(finf).is_zero is False
1901
+ assert Float(fninf).is_zero is False
1902
+ assert bool(Float(0)) is False
1903
+
1904
+
1905
+ def test_issue_6349():
1906
+ assert Float('23.e3', '')._prec == 10
1907
+ assert Float('23e3', '')._prec == 20
1908
+ assert Float('23000', '')._prec == 20
1909
+ assert Float('-23000', '')._prec == 20
1910
+
1911
+
1912
+ def test_mpf_norm():
1913
+ assert mpf_norm((1, 0, 1, 0), 10) == mpf('0')._mpf_
1914
+ assert Float._new((1, 0, 1, 0), 10)._mpf_ == mpf('0')._mpf_
1915
+
1916
+
1917
+ def test_latex():
1918
+ assert latex(pi) == r"\pi"
1919
+ assert latex(E) == r"e"
1920
+ assert latex(GoldenRatio) == r"\phi"
1921
+ assert latex(TribonacciConstant) == r"\text{TribonacciConstant}"
1922
+ assert latex(EulerGamma) == r"\gamma"
1923
+ assert latex(oo) == r"\infty"
1924
+ assert latex(-oo) == r"-\infty"
1925
+ assert latex(zoo) == r"\tilde{\infty}"
1926
+ assert latex(nan) == r"\text{NaN}"
1927
+ assert latex(I) == r"i"
1928
+
1929
+
1930
+ def test_issue_7742():
1931
+ assert -oo % 1 is nan
1932
+
1933
+
1934
+ def test_simplify_AlgebraicNumber():
1935
+ A = AlgebraicNumber
1936
+ e = 3**(S.One/6)*(3 + (135 + 78*sqrt(3))**Rational(2, 3))/(45 + 26*sqrt(3))**(S.One/3)
1937
+ assert simplify(A(e)) == A(12) # wester test_C20
1938
+
1939
+ e = (41 + 29*sqrt(2))**(S.One/5)
1940
+ assert simplify(A(e)) == A(1 + sqrt(2)) # wester test_C21
1941
+
1942
+ e = (3 + 4*I)**Rational(3, 2)
1943
+ assert simplify(A(e)) == A(2 + 11*I) # issue 4401
1944
+
1945
+
1946
+ def test_Float_idempotence():
1947
+ x = Float('1.23', '')
1948
+ y = Float(x)
1949
+ z = Float(x, 15)
1950
+ assert same_and_same_prec(y, x)
1951
+ assert not same_and_same_prec(z, x)
1952
+ x = Float(10**20)
1953
+ y = Float(x)
1954
+ z = Float(x, 15)
1955
+ assert same_and_same_prec(y, x)
1956
+ assert not same_and_same_prec(z, x)
1957
+
1958
+
1959
+ def test_comp1():
1960
+ # sqrt(2) = 1.414213 5623730950...
1961
+ a = sqrt(2).n(7)
1962
+ assert comp(a, 1.4142129) is False
1963
+ assert comp(a, 1.4142130)
1964
+ # ...
1965
+ assert comp(a, 1.4142141)
1966
+ assert comp(a, 1.4142142) is False
1967
+ assert comp(sqrt(2).n(2), '1.4')
1968
+ assert comp(sqrt(2).n(2), Float(1.4, 2), '')
1969
+ assert comp(sqrt(2).n(2), 1.4, '')
1970
+ assert comp(sqrt(2).n(2), Float(1.4, 3), '') is False
1971
+ assert comp(sqrt(2) + sqrt(3)*I, 1.4 + 1.7*I, .1)
1972
+ assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.89, .1)
1973
+ assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.90, .1)
1974
+ assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.07, .1)
1975
+ assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.08, .1)
1976
+ assert [(i, j)
1977
+ for i in range(130, 150)
1978
+ for j in range(170, 180)
1979
+ if comp((sqrt(2)+ I*sqrt(3)).n(3), i/100. + I*j/100.)] == [
1980
+ (141, 173), (142, 173)]
1981
+ raises(ValueError, lambda: comp(t, '1'))
1982
+ raises(ValueError, lambda: comp(t, 1))
1983
+ assert comp(0, 0.0)
1984
+ assert comp(.5, S.Half)
1985
+ assert comp(2 + sqrt(2), 2.0 + sqrt(2))
1986
+ assert not comp(0, 1)
1987
+ assert not comp(2, sqrt(2))
1988
+ assert not comp(2 + I, 2.0 + sqrt(2))
1989
+ assert not comp(2.0 + sqrt(2), 2 + I)
1990
+ assert not comp(2.0 + sqrt(2), sqrt(3))
1991
+ assert comp(1/pi.n(4), 0.3183, 1e-5)
1992
+ assert not comp(1/pi.n(4), 0.3183, 8e-6)
1993
+
1994
+
1995
+ def test_issue_9491():
1996
+ assert oo**zoo is nan
1997
+
1998
+
1999
+ def test_issue_10063():
2000
+ assert 2**Float(3) == Float(8)
2001
+
2002
+
2003
+ def test_issue_10020():
2004
+ assert oo**I is S.NaN
2005
+ assert oo**(1 + I) is S.ComplexInfinity
2006
+ assert oo**(-1 + I) is S.Zero
2007
+ assert (-oo)**I is S.NaN
2008
+ assert (-oo)**(-1 + I) is S.Zero
2009
+ assert oo**t == Pow(oo, t, evaluate=False)
2010
+ assert (-oo)**t == Pow(-oo, t, evaluate=False)
2011
+
2012
+
2013
+ def test_invert_numbers():
2014
+ assert S(2).invert(5) == 3
2015
+ assert S(2).invert(Rational(5, 2)) == S.Half
2016
+ assert S(2).invert(5.) == S.Half
2017
+ assert S(2).invert(S(5)) == 3
2018
+ assert S(2.).invert(5) == 0.5
2019
+ assert S(sqrt(2)).invert(5) == 1/sqrt(2)
2020
+ assert S(sqrt(2)).invert(sqrt(3)) == 1/sqrt(2)
2021
+
2022
+
2023
+ def test_mod_inverse():
2024
+ assert mod_inverse(3, 11) == 4
2025
+ assert mod_inverse(5, 11) == 9
2026
+ assert mod_inverse(21124921, 521512) == 7713
2027
+ assert mod_inverse(124215421, 5125) == 2981
2028
+ assert mod_inverse(214, 12515) == 1579
2029
+ assert mod_inverse(5823991, 3299) == 1442
2030
+ assert mod_inverse(123, 44) == 39
2031
+ assert mod_inverse(2, 5) == 3
2032
+ assert mod_inverse(-2, 5) == 2
2033
+ assert mod_inverse(2, -5) == -2
2034
+ assert mod_inverse(-2, -5) == -3
2035
+ assert mod_inverse(-3, -7) == -5
2036
+ x = Symbol('x')
2037
+ assert S(2).invert(x) == S.Half
2038
+ raises(TypeError, lambda: mod_inverse(2, x))
2039
+ raises(ValueError, lambda: mod_inverse(2, S.Half))
2040
+ raises(ValueError, lambda: mod_inverse(2, cos(1)**2 + sin(1)**2))
2041
+
2042
+
2043
+ def test_golden_ratio_rewrite_as_sqrt():
2044
+ assert GoldenRatio.rewrite(sqrt) == S.Half + sqrt(5)*S.Half
2045
+
2046
+
2047
+ def test_tribonacci_constant_rewrite_as_sqrt():
2048
+ assert TribonacciConstant.rewrite(sqrt) == \
2049
+ (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
2050
+
2051
+
2052
+ def test_comparisons_with_unknown_type():
2053
+ class Foo:
2054
+ """
2055
+ Class that is unaware of Basic, and relies on both classes returning
2056
+ the NotImplemented singleton for equivalence to evaluate to False.
2057
+
2058
+ """
2059
+
2060
+ ni, nf, nr = Integer(3), Float(1.0), Rational(1, 3)
2061
+ foo = Foo()
2062
+
2063
+ for n in ni, nf, nr, oo, -oo, zoo, nan:
2064
+ assert n != foo
2065
+ assert foo != n
2066
+ assert not n == foo
2067
+ assert not foo == n
2068
+ raises(TypeError, lambda: n < foo)
2069
+ raises(TypeError, lambda: foo > n)
2070
+ raises(TypeError, lambda: n > foo)
2071
+ raises(TypeError, lambda: foo < n)
2072
+ raises(TypeError, lambda: n <= foo)
2073
+ raises(TypeError, lambda: foo >= n)
2074
+ raises(TypeError, lambda: n >= foo)
2075
+ raises(TypeError, lambda: foo <= n)
2076
+
2077
+ class Bar:
2078
+ """
2079
+ Class that considers itself equal to any instance of Number except
2080
+ infinities and nans, and relies on SymPy types returning the
2081
+ NotImplemented singleton for symmetric equality relations.
2082
+
2083
+ """
2084
+ def __eq__(self, other):
2085
+ if other in (oo, -oo, zoo, nan):
2086
+ return False
2087
+ if isinstance(other, Number):
2088
+ return True
2089
+ return NotImplemented
2090
+
2091
+ def __ne__(self, other):
2092
+ return not self == other
2093
+
2094
+ bar = Bar()
2095
+
2096
+ for n in ni, nf, nr:
2097
+ assert n == bar
2098
+ assert bar == n
2099
+ assert not n != bar
2100
+ assert not bar != n
2101
+
2102
+ for n in oo, -oo, zoo, nan:
2103
+ assert n != bar
2104
+ assert bar != n
2105
+ assert not n == bar
2106
+ assert not bar == n
2107
+
2108
+ for n in ni, nf, nr, oo, -oo, zoo, nan:
2109
+ raises(TypeError, lambda: n < bar)
2110
+ raises(TypeError, lambda: bar > n)
2111
+ raises(TypeError, lambda: n > bar)
2112
+ raises(TypeError, lambda: bar < n)
2113
+ raises(TypeError, lambda: n <= bar)
2114
+ raises(TypeError, lambda: bar >= n)
2115
+ raises(TypeError, lambda: n >= bar)
2116
+ raises(TypeError, lambda: bar <= n)
2117
+
2118
+
2119
+ def test_NumberSymbol_comparison():
2120
+ from sympy.core.tests.test_relational import rel_check
2121
+ rpi = Rational('905502432259640373/288230376151711744')
2122
+ fpi = Float(float(pi))
2123
+ assert rel_check(rpi, fpi)
2124
+
2125
+
2126
+ def test_Integer_precision():
2127
+ # Make sure Integer inputs for keyword args work
2128
+ assert Float('1.0', dps=Integer(15))._prec == 53
2129
+ assert Float('1.0', precision=Integer(15))._prec == 15
2130
+ assert type(Float('1.0', precision=Integer(15))._prec) == int
2131
+ assert sympify(srepr(Float('1.0', precision=15))) == Float('1.0', precision=15)
2132
+
2133
+
2134
+ def test_numpy_to_float():
2135
+ from sympy.testing.pytest import skip
2136
+ from sympy.external import import_module
2137
+ np = import_module('numpy')
2138
+ if not np:
2139
+ skip('numpy not installed. Abort numpy tests.')
2140
+
2141
+ def check_prec_and_relerr(npval, ratval):
2142
+ prec = np.finfo(npval).nmant + 1
2143
+ x = Float(npval)
2144
+ assert x._prec == prec
2145
+ y = Float(ratval, precision=prec)
2146
+ assert abs((x - y)/y) < 2**(-(prec + 1))
2147
+
2148
+ check_prec_and_relerr(np.float16(2.0/3), Rational(2, 3))
2149
+ check_prec_and_relerr(np.float32(2.0/3), Rational(2, 3))
2150
+ check_prec_and_relerr(np.float64(2.0/3), Rational(2, 3))
2151
+ # extended precision, on some arch/compilers:
2152
+ x = np.longdouble(2)/3
2153
+ check_prec_and_relerr(x, Rational(2, 3))
2154
+ y = Float(x, precision=10)
2155
+ assert same_and_same_prec(y, Float(Rational(2, 3), precision=10))
2156
+
2157
+ raises(TypeError, lambda: Float(np.complex64(1+2j)))
2158
+ raises(TypeError, lambda: Float(np.complex128(1+2j)))
2159
+
2160
+
2161
+ def test_Integer_ceiling_floor():
2162
+ a = Integer(4)
2163
+
2164
+ assert a.floor() == a
2165
+ assert a.ceiling() == a
2166
+
2167
+
2168
+ def test_ComplexInfinity():
2169
+ assert zoo.floor() is zoo
2170
+ assert zoo.ceiling() is zoo
2171
+ assert zoo**zoo is S.NaN
2172
+
2173
+
2174
+ def test_Infinity_floor_ceiling_power():
2175
+ assert oo.floor() is oo
2176
+ assert oo.ceiling() is oo
2177
+ assert oo**S.NaN is S.NaN
2178
+ assert oo**zoo is S.NaN
2179
+
2180
+
2181
+ def test_One_power():
2182
+ assert S.One**12 is S.One
2183
+ assert S.NegativeOne**S.NaN is S.NaN
2184
+
2185
+
2186
+ def test_NegativeInfinity():
2187
+ assert (-oo).floor() is -oo
2188
+ assert (-oo).ceiling() is -oo
2189
+ assert (-oo)**11 is -oo
2190
+ assert (-oo)**12 is oo
2191
+
2192
+
2193
+ def test_issue_6133():
2194
+ raises(TypeError, lambda: (-oo < None))
2195
+ raises(TypeError, lambda: (S(-2) < None))
2196
+ raises(TypeError, lambda: (oo < None))
2197
+ raises(TypeError, lambda: (oo > None))
2198
+ raises(TypeError, lambda: (S(2) < None))
2199
+
2200
+
2201
+ def test_abc():
2202
+ x = numbers.Float(5)
2203
+ assert(isinstance(x, nums.Number))
2204
+ assert(isinstance(x, numbers.Number))
2205
+ assert(isinstance(x, nums.Real))
2206
+ y = numbers.Rational(1, 3)
2207
+ assert(isinstance(y, nums.Number))
2208
+ assert(y.numerator == 1)
2209
+ assert(y.denominator == 3)
2210
+ assert(isinstance(y, nums.Rational))
2211
+ z = numbers.Integer(3)
2212
+ assert(isinstance(z, nums.Number))
2213
+ assert(isinstance(z, numbers.Number))
2214
+ assert(isinstance(z, nums.Rational))
2215
+ assert(isinstance(z, numbers.Rational))
2216
+ assert(isinstance(z, nums.Integral))
2217
+
2218
+
2219
+ def test_floordiv():
2220
+ assert S(2)//S.Half == 4
2221
+
2222
+
2223
+ def test_negation():
2224
+ assert -S.Zero is S.Zero
2225
+ assert -Float(0) is not S.Zero and -Float(0) == 0.0
2226
+
2227
+
2228
+ def test_exponentiation_of_0():
2229
+ x = Symbol('x')
2230
+ assert 0**-x == zoo**x
2231
+ assert unchanged(Pow, 0, x)
2232
+ x = Symbol('x', zero=True)
2233
+ assert 0**-x == S.One
2234
+ assert 0**x == S.One
2235
+
2236
+
2237
+ def test_equal_valued():
2238
+ x = Symbol('x')
2239
+
2240
+ equal_values = [
2241
+ [1, 1.0, S(1), S(1.0), S(1).n(5)],
2242
+ [2, 2.0, S(2), S(2.0), S(2).n(5)],
2243
+ [-1, -1.0, -S(1), -S(1.0), -S(1).n(5)],
2244
+ [0.5, S(0.5), S(1)/2],
2245
+ [-0.5, -S(0.5), -S(1)/2],
2246
+ [0, 0.0, S(0), S(0.0), S(0).n()],
2247
+ [pi], [pi.n()], # <-- not equal
2248
+ [S(1)/10], [0.1, S(0.1)], # <-- not equal
2249
+ [S(0.1).n(5)],
2250
+ [oo],
2251
+ [cos(x/2)], [cos(0.5*x)], # <-- no recursion
2252
+ ]
2253
+
2254
+ for m, values_m in enumerate(equal_values):
2255
+ for value_i in values_m:
2256
+
2257
+ # All values in same list equal
2258
+ for value_j in values_m:
2259
+ assert equal_valued(value_i, value_j) is True
2260
+
2261
+ # Not equal to anything in any other list:
2262
+ for n, values_n in enumerate(equal_values):
2263
+ if n == m:
2264
+ continue
2265
+ for value_j in values_n:
2266
+ assert equal_valued(value_i, value_j) is False
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_operations.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.expr import Expr
2
+ from sympy.core.numbers import Integer
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import (Symbol, symbols)
5
+ from sympy.core.operations import AssocOp, LatticeOp
6
+ from sympy.testing.pytest import raises
7
+ from sympy.core.sympify import SympifyError
8
+ from sympy.core.add import Add, add
9
+ from sympy.core.mul import Mul, mul
10
+
11
+ # create the simplest possible Lattice class
12
+
13
+
14
+ class join(LatticeOp):
15
+ zero = Integer(0)
16
+ identity = Integer(1)
17
+
18
+
19
+ def test_lattice_simple():
20
+ assert join(join(2, 3), 4) == join(2, join(3, 4))
21
+ assert join(2, 3) == join(3, 2)
22
+ assert join(0, 2) == 0
23
+ assert join(1, 2) == 2
24
+ assert join(2, 2) == 2
25
+
26
+ assert join(join(2, 3), 4) == join(2, 3, 4)
27
+ assert join() == 1
28
+ assert join(4) == 4
29
+ assert join(1, 4, 2, 3, 1, 3, 2) == join(2, 3, 4)
30
+
31
+
32
+ def test_lattice_shortcircuit():
33
+ raises(SympifyError, lambda: join(object))
34
+ assert join(0, object) == 0
35
+
36
+
37
+ def test_lattice_print():
38
+ assert str(join(5, 4, 3, 2)) == 'join(2, 3, 4, 5)'
39
+
40
+
41
+ def test_lattice_make_args():
42
+ assert join.make_args(join(2, 3, 4)) == {S(2), S(3), S(4)}
43
+ assert join.make_args(0) == {0}
44
+ assert list(join.make_args(0))[0] is S.Zero
45
+ assert Add.make_args(0)[0] is S.Zero
46
+
47
+
48
+ def test_issue_14025():
49
+ a, b, c, d = symbols('a,b,c,d', commutative=False)
50
+ assert Mul(a, b, c).has(c*b) == False
51
+ assert Mul(a, b, c).has(b*c) == True
52
+ assert Mul(a, b, c, d).has(b*c*d) == True
53
+
54
+
55
+ def test_AssocOp_flatten():
56
+ a, b, c, d = symbols('a,b,c,d')
57
+
58
+ class MyAssoc(AssocOp):
59
+ identity = S.One
60
+
61
+ assert MyAssoc(a, MyAssoc(b, c)).args == \
62
+ MyAssoc(MyAssoc(a, b), c).args == \
63
+ MyAssoc(MyAssoc(a, b, c)).args == \
64
+ MyAssoc(a, b, c).args == \
65
+ (a, b, c)
66
+ u = MyAssoc(b, c)
67
+ v = MyAssoc(u, d, evaluate=False)
68
+ assert v.args == (u, d)
69
+ # like Add, any unevaluated outer call will flatten inner args
70
+ assert MyAssoc(a, v).args == (a, b, c, d)
71
+
72
+
73
+ def test_add_dispatcher():
74
+
75
+ class NewBase(Expr):
76
+ @property
77
+ def _add_handler(self):
78
+ return NewAdd
79
+ class NewAdd(NewBase, Add):
80
+ pass
81
+ add.register_handlerclass((Add, NewAdd), NewAdd)
82
+
83
+ a, b = Symbol('a'), NewBase()
84
+
85
+ # Add called as fallback
86
+ assert add(1, 2) == Add(1, 2)
87
+ assert add(a, a) == Add(a, a)
88
+
89
+ # selection by registered priority
90
+ assert add(a,b,a) == NewAdd(2*a, b)
91
+
92
+
93
+ def test_mul_dispatcher():
94
+
95
+ class NewBase(Expr):
96
+ @property
97
+ def _mul_handler(self):
98
+ return NewMul
99
+ class NewMul(NewBase, Mul):
100
+ pass
101
+ mul.register_handlerclass((Mul, NewMul), NewMul)
102
+
103
+ a, b = Symbol('a'), NewBase()
104
+
105
+ # Mul called as fallback
106
+ assert mul(1, 2) == Mul(1, 2)
107
+ assert mul(a, a) == Mul(a, a)
108
+
109
+ # selection by registered priority
110
+ assert mul(a,b,a) == NewMul(a**2, b)
env-llmeval/lib/python3.10/site-packages/sympy/core/tests/test_parameters.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.abc import x, y
2
+ from sympy.core.parameters import evaluate
3
+ from sympy.core import Mul, Add, Pow, S
4
+ from sympy.core.numbers import oo
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+
7
+ def test_add():
8
+ with evaluate(False):
9
+ p = oo - oo
10
+ assert isinstance(p, Add) and p.args == (oo, -oo)
11
+ p = 5 - oo
12
+ assert isinstance(p, Add) and p.args == (-oo, 5)
13
+ p = oo - 5
14
+ assert isinstance(p, Add) and p.args == (oo, -5)
15
+ p = oo + 5
16
+ assert isinstance(p, Add) and p.args == (oo, 5)
17
+ p = 5 + oo
18
+ assert isinstance(p, Add) and p.args == (oo, 5)
19
+ p = -oo + 5
20
+ assert isinstance(p, Add) and p.args == (-oo, 5)
21
+ p = -5 - oo
22
+ assert isinstance(p, Add) and p.args == (-oo, -5)
23
+
24
+ with evaluate(False):
25
+ expr = x + x
26
+ assert isinstance(expr, Add)
27
+ assert expr.args == (x, x)
28
+
29
+ with evaluate(True):
30
+ assert (x + x).args == (2, x)
31
+
32
+ assert (x + x).args == (x, x)
33
+
34
+ assert isinstance(x + x, Mul)
35
+
36
+ with evaluate(False):
37
+ assert S.One + 1 == Add(1, 1)
38
+ assert 1 + S.One == Add(1, 1)
39
+
40
+ assert S(4) - 3 == Add(4, -3)
41
+ assert -3 + S(4) == Add(4, -3)
42
+
43
+ assert S(2) * 4 == Mul(2, 4)
44
+ assert 4 * S(2) == Mul(2, 4)
45
+
46
+ assert S(6) / 3 == Mul(6, Pow(3, -1))
47
+ assert S.One / 3 * 6 == Mul(S.One / 3, 6)
48
+
49
+ assert 9 ** S(2) == Pow(9, 2)
50
+ assert S(2) ** 9 == Pow(2, 9)
51
+
52
+ assert S(2) / 2 == Mul(2, Pow(2, -1))
53
+ assert S.One / 2 * 2 == Mul(S.One / 2, 2)
54
+
55
+ assert S(2) / 3 + 1 == Add(S(2) / 3, 1)
56
+ assert 1 + S(2) / 3 == Add(1, S(2) / 3)
57
+
58
+ assert S(4) / 7 - 3 == Add(S(4) / 7, -3)
59
+ assert -3 + S(4) / 7 == Add(-3, S(4) / 7)
60
+
61
+ assert S(2) / 4 * 4 == Mul(S(2) / 4, 4)
62
+ assert 4 * (S(2) / 4) == Mul(4, S(2) / 4)
63
+
64
+ assert S(6) / 3 == Mul(6, Pow(3, -1))
65
+ assert S.One / 3 * 6 == Mul(S.One / 3, 6)
66
+
67
+ assert S.One / 3 + sqrt(3) == Add(S.One / 3, sqrt(3))
68
+ assert sqrt(3) + S.One / 3 == Add(sqrt(3), S.One / 3)
69
+
70
+ assert S.One / 2 * 10.333 == Mul(S.One / 2, 10.333)
71
+ assert 10.333 * (S.One / 2) == Mul(10.333, S.One / 2)
72
+
73
+ assert sqrt(2) * sqrt(2) == Mul(sqrt(2), sqrt(2))
74
+
75
+ assert S.One / 2 + x == Add(S.One / 2, x)
76
+ assert x + S.One / 2 == Add(x, S.One / 2)
77
+
78
+ assert S.One / x * x == Mul(S.One / x, x)
79
+ assert x * (S.One / x) == Mul(x, Pow(x, -1))
80
+
81
+ assert S.One / 3 == Pow(3, -1)
82
+ assert S.One / x == Pow(x, -1)
83
+ assert 1 / S(3) == Pow(3, -1)
84
+ assert 1 / x == Pow(x, -1)
85
+
86
+ def test_nested():
87
+ with evaluate(False):
88
+ expr = (x + x) + (y + y)
89
+ assert expr.args == ((x + x), (y + y))
90
+ assert expr.args[0].args == (x, x)