Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/sympy/core/__init__.py +100 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/_print_helpers.py +65 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/add.py +1287 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/alphabets.py +4 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/backend.py +84 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/cache.py +210 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/compatibility.py +35 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/containers.py +410 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/core.py +63 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/coreerrors.py +9 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/decorators.py +238 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/expr.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/function.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/logic.py +427 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/mod.py +238 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/multidimensional.py +131 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/numbers.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/operations.py +722 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/power.py +2004 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/random.py +227 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/relational.py +1587 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/rules.py +66 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/singleton.py +174 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/sorting.py +309 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/symbol.py +945 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/sympify.py +634 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_args.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_basic.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_compatibility.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_operations.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_symbol.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_sympify.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_args.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_arit.py +2463 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_assumptions.py +1335 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_basic.py +319 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_cache.py +91 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_compatibility.py +6 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_complex.py +226 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_constructor_postprocessor.py +87 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_containers.py +217 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_count_ops.py +155 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_diff.py +160 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_equal.py +89 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_eval.py +95 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_evalf.py +732 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_expand.py +351 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_expr.py +2261 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_exprtools.py +493 -0
llmeval-env/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 |
+
]
|
llmeval-env/lib/python3.10/site-packages/sympy/core/_print_helpers.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Base class to provide str and repr hooks that `init_printing` can overwrite.
|
3 |
+
|
4 |
+
This is exposed publicly in the `printing.defaults` module,
|
5 |
+
but cannot be defined there without causing circular imports.
|
6 |
+
"""
|
7 |
+
|
8 |
+
class Printable:
|
9 |
+
"""
|
10 |
+
The default implementation of printing for SymPy classes.
|
11 |
+
|
12 |
+
This implements a hack that allows us to print elements of built-in
|
13 |
+
Python containers in a readable way. Natively Python uses ``repr()``
|
14 |
+
even if ``str()`` was explicitly requested. Mix in this trait into
|
15 |
+
a class to get proper default printing.
|
16 |
+
|
17 |
+
This also adds support for LaTeX printing in jupyter notebooks.
|
18 |
+
"""
|
19 |
+
|
20 |
+
# Since this class is used as a mixin we set empty slots. That means that
|
21 |
+
# instances of any subclasses that use slots will not need to have a
|
22 |
+
# __dict__.
|
23 |
+
__slots__ = ()
|
24 |
+
|
25 |
+
# Note, we always use the default ordering (lex) in __str__ and __repr__,
|
26 |
+
# regardless of the global setting. See issue 5487.
|
27 |
+
def __str__(self):
|
28 |
+
from sympy.printing.str import sstr
|
29 |
+
return sstr(self, order=None)
|
30 |
+
|
31 |
+
__repr__ = __str__
|
32 |
+
|
33 |
+
def _repr_disabled(self):
|
34 |
+
"""
|
35 |
+
No-op repr function used to disable jupyter display hooks.
|
36 |
+
|
37 |
+
When :func:`sympy.init_printing` is used to disable certain display
|
38 |
+
formats, this function is copied into the appropriate ``_repr_*_``
|
39 |
+
attributes.
|
40 |
+
|
41 |
+
While we could just set the attributes to `None``, doing it this way
|
42 |
+
allows derived classes to call `super()`.
|
43 |
+
"""
|
44 |
+
return None
|
45 |
+
|
46 |
+
# We don't implement _repr_png_ here because it would add a large amount of
|
47 |
+
# data to any notebook containing SymPy expressions, without adding
|
48 |
+
# anything useful to the notebook. It can still enabled manually, e.g.,
|
49 |
+
# for the qtconsole, with init_printing().
|
50 |
+
_repr_png_ = _repr_disabled
|
51 |
+
|
52 |
+
_repr_svg_ = _repr_disabled
|
53 |
+
|
54 |
+
def _repr_latex_(self):
|
55 |
+
"""
|
56 |
+
IPython/Jupyter LaTeX printing
|
57 |
+
|
58 |
+
To change the behavior of this (e.g., pass in some settings to LaTeX),
|
59 |
+
use init_printing(). init_printing() will also enable LaTeX printing
|
60 |
+
for built in numeric types like ints and container types that contain
|
61 |
+
SymPy objects, like lists and dictionaries of expressions.
|
62 |
+
"""
|
63 |
+
from sympy.printing.latex import latex
|
64 |
+
s = latex(self, mode='plain')
|
65 |
+
return "$\\displaystyle %s$" % s
|
llmeval-env/lib/python3.10/site-packages/sympy/core/add.py
ADDED
@@ -0,0 +1,1287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Tuple as tTuple
|
2 |
+
from collections import defaultdict
|
3 |
+
from functools import cmp_to_key, reduce
|
4 |
+
from operator import attrgetter
|
5 |
+
from .basic import Basic
|
6 |
+
from .parameters import global_parameters
|
7 |
+
from .logic import _fuzzy_group, fuzzy_or, fuzzy_not
|
8 |
+
from .singleton import S
|
9 |
+
from .operations import AssocOp, AssocOpDispatcher
|
10 |
+
from .cache import cacheit
|
11 |
+
from .numbers import ilcm, igcd, equal_valued
|
12 |
+
from .expr import Expr
|
13 |
+
from .kind import UndefinedKind
|
14 |
+
from sympy.utilities.iterables import is_sequence, sift
|
15 |
+
|
16 |
+
# Key for sorting commutative args in canonical order
|
17 |
+
_args_sortkey = cmp_to_key(Basic.compare)
|
18 |
+
|
19 |
+
|
20 |
+
def _could_extract_minus_sign(expr):
|
21 |
+
# assume expr is Add-like
|
22 |
+
# We choose the one with less arguments with minus signs
|
23 |
+
negative_args = sum(1 for i in expr.args
|
24 |
+
if i.could_extract_minus_sign())
|
25 |
+
positive_args = len(expr.args) - negative_args
|
26 |
+
if positive_args > negative_args:
|
27 |
+
return False
|
28 |
+
elif positive_args < negative_args:
|
29 |
+
return True
|
30 |
+
# choose based on .sort_key() to prefer
|
31 |
+
# x - 1 instead of 1 - x and
|
32 |
+
# 3 - sqrt(2) instead of -3 + sqrt(2)
|
33 |
+
return bool(expr.sort_key() < (-expr).sort_key())
|
34 |
+
|
35 |
+
|
36 |
+
def _addsort(args):
|
37 |
+
# in-place sorting of args
|
38 |
+
args.sort(key=_args_sortkey)
|
39 |
+
|
40 |
+
|
41 |
+
def _unevaluated_Add(*args):
|
42 |
+
"""Return a well-formed unevaluated Add: Numbers are collected and
|
43 |
+
put in slot 0 and args are sorted. Use this when args have changed
|
44 |
+
but you still want to return an unevaluated Add.
|
45 |
+
|
46 |
+
Examples
|
47 |
+
========
|
48 |
+
|
49 |
+
>>> from sympy.core.add import _unevaluated_Add as uAdd
|
50 |
+
>>> from sympy import S, Add
|
51 |
+
>>> from sympy.abc import x, y
|
52 |
+
>>> a = uAdd(*[S(1.0), x, S(2)])
|
53 |
+
>>> a.args[0]
|
54 |
+
3.00000000000000
|
55 |
+
>>> a.args[1]
|
56 |
+
x
|
57 |
+
|
58 |
+
Beyond the Number being in slot 0, there is no other assurance of
|
59 |
+
order for the arguments since they are hash sorted. So, for testing
|
60 |
+
purposes, output produced by this in some other function can only
|
61 |
+
be tested against the output of this function or as one of several
|
62 |
+
options:
|
63 |
+
|
64 |
+
>>> opts = (Add(x, y, evaluate=False), Add(y, x, evaluate=False))
|
65 |
+
>>> a = uAdd(x, y)
|
66 |
+
>>> assert a in opts and a == uAdd(x, y)
|
67 |
+
>>> uAdd(x + 1, x + 2)
|
68 |
+
x + x + 3
|
69 |
+
"""
|
70 |
+
args = list(args)
|
71 |
+
newargs = []
|
72 |
+
co = S.Zero
|
73 |
+
while args:
|
74 |
+
a = args.pop()
|
75 |
+
if a.is_Add:
|
76 |
+
# this will keep nesting from building up
|
77 |
+
# so that x + (x + 1) -> x + x + 1 (3 args)
|
78 |
+
args.extend(a.args)
|
79 |
+
elif a.is_Number:
|
80 |
+
co += a
|
81 |
+
else:
|
82 |
+
newargs.append(a)
|
83 |
+
_addsort(newargs)
|
84 |
+
if co:
|
85 |
+
newargs.insert(0, co)
|
86 |
+
return Add._from_args(newargs)
|
87 |
+
|
88 |
+
|
89 |
+
class Add(Expr, AssocOp):
|
90 |
+
"""
|
91 |
+
Expression representing addition operation for algebraic group.
|
92 |
+
|
93 |
+
.. deprecated:: 1.7
|
94 |
+
|
95 |
+
Using arguments that aren't subclasses of :class:`~.Expr` in core
|
96 |
+
operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
|
97 |
+
deprecated. See :ref:`non-expr-args-deprecated` for details.
|
98 |
+
|
99 |
+
Every argument of ``Add()`` must be ``Expr``. Infix operator ``+``
|
100 |
+
on most scalar objects in SymPy calls this class.
|
101 |
+
|
102 |
+
Another use of ``Add()`` is to represent the structure of abstract
|
103 |
+
addition so that its arguments can be substituted to return different
|
104 |
+
class. Refer to examples section for this.
|
105 |
+
|
106 |
+
``Add()`` evaluates the argument unless ``evaluate=False`` is passed.
|
107 |
+
The evaluation logic includes:
|
108 |
+
|
109 |
+
1. Flattening
|
110 |
+
``Add(x, Add(y, z))`` -> ``Add(x, y, z)``
|
111 |
+
|
112 |
+
2. Identity removing
|
113 |
+
``Add(x, 0, y)`` -> ``Add(x, y)``
|
114 |
+
|
115 |
+
3. Coefficient collecting by ``.as_coeff_Mul()``
|
116 |
+
``Add(x, 2*x)`` -> ``Mul(3, x)``
|
117 |
+
|
118 |
+
4. Term sorting
|
119 |
+
``Add(y, x, 2)`` -> ``Add(2, x, y)``
|
120 |
+
|
121 |
+
If no argument is passed, identity element 0 is returned. If single
|
122 |
+
element is passed, that element is returned.
|
123 |
+
|
124 |
+
Note that ``Add(*args)`` is more efficient than ``sum(args)`` because
|
125 |
+
it flattens the arguments. ``sum(a, b, c, ...)`` recursively adds the
|
126 |
+
arguments as ``a + (b + (c + ...))``, which has quadratic complexity.
|
127 |
+
On the other hand, ``Add(a, b, c, d)`` does not assume nested
|
128 |
+
structure, making the complexity linear.
|
129 |
+
|
130 |
+
Since addition is group operation, every argument should have the
|
131 |
+
same :obj:`sympy.core.kind.Kind()`.
|
132 |
+
|
133 |
+
Examples
|
134 |
+
========
|
135 |
+
|
136 |
+
>>> from sympy import Add, I
|
137 |
+
>>> from sympy.abc import x, y
|
138 |
+
>>> Add(x, 1)
|
139 |
+
x + 1
|
140 |
+
>>> Add(x, x)
|
141 |
+
2*x
|
142 |
+
>>> 2*x**2 + 3*x + I*y + 2*y + 2*x/5 + 1.0*y + 1
|
143 |
+
2*x**2 + 17*x/5 + 3.0*y + I*y + 1
|
144 |
+
|
145 |
+
If ``evaluate=False`` is passed, result is not evaluated.
|
146 |
+
|
147 |
+
>>> Add(1, 2, evaluate=False)
|
148 |
+
1 + 2
|
149 |
+
>>> Add(x, x, evaluate=False)
|
150 |
+
x + x
|
151 |
+
|
152 |
+
``Add()`` also represents the general structure of addition operation.
|
153 |
+
|
154 |
+
>>> from sympy import MatrixSymbol
|
155 |
+
>>> A,B = MatrixSymbol('A', 2,2), MatrixSymbol('B', 2,2)
|
156 |
+
>>> expr = Add(x,y).subs({x:A, y:B})
|
157 |
+
>>> expr
|
158 |
+
A + B
|
159 |
+
>>> type(expr)
|
160 |
+
<class 'sympy.matrices.expressions.matadd.MatAdd'>
|
161 |
+
|
162 |
+
Note that the printers do not display in args order.
|
163 |
+
|
164 |
+
>>> Add(x, 1)
|
165 |
+
x + 1
|
166 |
+
>>> Add(x, 1).args
|
167 |
+
(1, x)
|
168 |
+
|
169 |
+
See Also
|
170 |
+
========
|
171 |
+
|
172 |
+
MatAdd
|
173 |
+
|
174 |
+
"""
|
175 |
+
|
176 |
+
__slots__ = ()
|
177 |
+
|
178 |
+
args: tTuple[Expr, ...]
|
179 |
+
|
180 |
+
is_Add = True
|
181 |
+
|
182 |
+
_args_type = Expr
|
183 |
+
|
184 |
+
@classmethod
|
185 |
+
def flatten(cls, seq):
|
186 |
+
"""
|
187 |
+
Takes the sequence "seq" of nested Adds and returns a flatten list.
|
188 |
+
|
189 |
+
Returns: (commutative_part, noncommutative_part, order_symbols)
|
190 |
+
|
191 |
+
Applies associativity, all terms are commutable with respect to
|
192 |
+
addition.
|
193 |
+
|
194 |
+
NB: the removal of 0 is already handled by AssocOp.__new__
|
195 |
+
|
196 |
+
See Also
|
197 |
+
========
|
198 |
+
|
199 |
+
sympy.core.mul.Mul.flatten
|
200 |
+
|
201 |
+
"""
|
202 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
203 |
+
from sympy.matrices.expressions import MatrixExpr
|
204 |
+
from sympy.tensor.tensor import TensExpr
|
205 |
+
rv = None
|
206 |
+
if len(seq) == 2:
|
207 |
+
a, b = seq
|
208 |
+
if b.is_Rational:
|
209 |
+
a, b = b, a
|
210 |
+
if a.is_Rational:
|
211 |
+
if b.is_Mul:
|
212 |
+
rv = [a, b], [], None
|
213 |
+
if rv:
|
214 |
+
if all(s.is_commutative for s in rv[0]):
|
215 |
+
return rv
|
216 |
+
return [], rv[0], None
|
217 |
+
|
218 |
+
terms = {} # term -> coeff
|
219 |
+
# e.g. x**2 -> 5 for ... + 5*x**2 + ...
|
220 |
+
|
221 |
+
coeff = S.Zero # coefficient (Number or zoo) to always be in slot 0
|
222 |
+
# e.g. 3 + ...
|
223 |
+
order_factors = []
|
224 |
+
|
225 |
+
extra = []
|
226 |
+
|
227 |
+
for o in seq:
|
228 |
+
|
229 |
+
# O(x)
|
230 |
+
if o.is_Order:
|
231 |
+
if o.expr.is_zero:
|
232 |
+
continue
|
233 |
+
for o1 in order_factors:
|
234 |
+
if o1.contains(o):
|
235 |
+
o = None
|
236 |
+
break
|
237 |
+
if o is None:
|
238 |
+
continue
|
239 |
+
order_factors = [o] + [
|
240 |
+
o1 for o1 in order_factors if not o.contains(o1)]
|
241 |
+
continue
|
242 |
+
|
243 |
+
# 3 or NaN
|
244 |
+
elif o.is_Number:
|
245 |
+
if (o is S.NaN or coeff is S.ComplexInfinity and
|
246 |
+
o.is_finite is False) and not extra:
|
247 |
+
# we know for sure the result will be nan
|
248 |
+
return [S.NaN], [], None
|
249 |
+
if coeff.is_Number or isinstance(coeff, AccumBounds):
|
250 |
+
coeff += o
|
251 |
+
if coeff is S.NaN and not extra:
|
252 |
+
# we know for sure the result will be nan
|
253 |
+
return [S.NaN], [], None
|
254 |
+
continue
|
255 |
+
|
256 |
+
elif isinstance(o, AccumBounds):
|
257 |
+
coeff = o.__add__(coeff)
|
258 |
+
continue
|
259 |
+
|
260 |
+
elif isinstance(o, MatrixExpr):
|
261 |
+
# can't add 0 to Matrix so make sure coeff is not 0
|
262 |
+
extra.append(o)
|
263 |
+
continue
|
264 |
+
|
265 |
+
elif isinstance(o, TensExpr):
|
266 |
+
coeff = o.__add__(coeff) if coeff else o
|
267 |
+
continue
|
268 |
+
|
269 |
+
elif o is S.ComplexInfinity:
|
270 |
+
if coeff.is_finite is False and not extra:
|
271 |
+
# we know for sure the result will be nan
|
272 |
+
return [S.NaN], [], None
|
273 |
+
coeff = S.ComplexInfinity
|
274 |
+
continue
|
275 |
+
|
276 |
+
# Add([...])
|
277 |
+
elif o.is_Add:
|
278 |
+
# NB: here we assume Add is always commutative
|
279 |
+
seq.extend(o.args) # TODO zerocopy?
|
280 |
+
continue
|
281 |
+
|
282 |
+
# Mul([...])
|
283 |
+
elif o.is_Mul:
|
284 |
+
c, s = o.as_coeff_Mul()
|
285 |
+
|
286 |
+
# check for unevaluated Pow, e.g. 2**3 or 2**(-1/2)
|
287 |
+
elif o.is_Pow:
|
288 |
+
b, e = o.as_base_exp()
|
289 |
+
if b.is_Number and (e.is_Integer or
|
290 |
+
(e.is_Rational and e.is_negative)):
|
291 |
+
seq.append(b**e)
|
292 |
+
continue
|
293 |
+
c, s = S.One, o
|
294 |
+
|
295 |
+
else:
|
296 |
+
# everything else
|
297 |
+
c = S.One
|
298 |
+
s = o
|
299 |
+
|
300 |
+
# now we have:
|
301 |
+
# o = c*s, where
|
302 |
+
#
|
303 |
+
# c is a Number
|
304 |
+
# s is an expression with number factor extracted
|
305 |
+
# let's collect terms with the same s, so e.g.
|
306 |
+
# 2*x**2 + 3*x**2 -> 5*x**2
|
307 |
+
if s in terms:
|
308 |
+
terms[s] += c
|
309 |
+
if terms[s] is S.NaN and not extra:
|
310 |
+
# we know for sure the result will be nan
|
311 |
+
return [S.NaN], [], None
|
312 |
+
else:
|
313 |
+
terms[s] = c
|
314 |
+
|
315 |
+
# now let's construct new args:
|
316 |
+
# [2*x**2, x**3, 7*x**4, pi, ...]
|
317 |
+
newseq = []
|
318 |
+
noncommutative = False
|
319 |
+
for s, c in terms.items():
|
320 |
+
# 0*s
|
321 |
+
if c.is_zero:
|
322 |
+
continue
|
323 |
+
# 1*s
|
324 |
+
elif c is S.One:
|
325 |
+
newseq.append(s)
|
326 |
+
# c*s
|
327 |
+
else:
|
328 |
+
if s.is_Mul:
|
329 |
+
# Mul, already keeps its arguments in perfect order.
|
330 |
+
# so we can simply put c in slot0 and go the fast way.
|
331 |
+
cs = s._new_rawargs(*((c,) + s.args))
|
332 |
+
newseq.append(cs)
|
333 |
+
elif s.is_Add:
|
334 |
+
# we just re-create the unevaluated Mul
|
335 |
+
newseq.append(Mul(c, s, evaluate=False))
|
336 |
+
else:
|
337 |
+
# alternatively we have to call all Mul's machinery (slow)
|
338 |
+
newseq.append(Mul(c, s))
|
339 |
+
|
340 |
+
noncommutative = noncommutative or not s.is_commutative
|
341 |
+
|
342 |
+
# oo, -oo
|
343 |
+
if coeff is S.Infinity:
|
344 |
+
newseq = [f for f in newseq if not (f.is_extended_nonnegative or f.is_real)]
|
345 |
+
|
346 |
+
elif coeff is S.NegativeInfinity:
|
347 |
+
newseq = [f for f in newseq if not (f.is_extended_nonpositive or f.is_real)]
|
348 |
+
|
349 |
+
if coeff is S.ComplexInfinity:
|
350 |
+
# zoo might be
|
351 |
+
# infinite_real + finite_im
|
352 |
+
# finite_real + infinite_im
|
353 |
+
# infinite_real + infinite_im
|
354 |
+
# addition of a finite real or imaginary number won't be able to
|
355 |
+
# change the zoo nature; adding an infinite qualtity would result
|
356 |
+
# in a NaN condition if it had sign opposite of the infinite
|
357 |
+
# portion of zoo, e.g., infinite_real - infinite_real.
|
358 |
+
newseq = [c for c in newseq if not (c.is_finite and
|
359 |
+
c.is_extended_real is not None)]
|
360 |
+
|
361 |
+
# process O(x)
|
362 |
+
if order_factors:
|
363 |
+
newseq2 = []
|
364 |
+
for t in newseq:
|
365 |
+
for o in order_factors:
|
366 |
+
# x + O(x) -> O(x)
|
367 |
+
if o.contains(t):
|
368 |
+
t = None
|
369 |
+
break
|
370 |
+
# x + O(x**2) -> x + O(x**2)
|
371 |
+
if t is not None:
|
372 |
+
newseq2.append(t)
|
373 |
+
newseq = newseq2 + order_factors
|
374 |
+
# 1 + O(1) -> O(1)
|
375 |
+
for o in order_factors:
|
376 |
+
if o.contains(coeff):
|
377 |
+
coeff = S.Zero
|
378 |
+
break
|
379 |
+
|
380 |
+
# order args canonically
|
381 |
+
_addsort(newseq)
|
382 |
+
|
383 |
+
# current code expects coeff to be first
|
384 |
+
if coeff is not S.Zero:
|
385 |
+
newseq.insert(0, coeff)
|
386 |
+
|
387 |
+
if extra:
|
388 |
+
newseq += extra
|
389 |
+
noncommutative = True
|
390 |
+
|
391 |
+
# we are done
|
392 |
+
if noncommutative:
|
393 |
+
return [], newseq, None
|
394 |
+
else:
|
395 |
+
return newseq, [], None
|
396 |
+
|
397 |
+
@classmethod
|
398 |
+
def class_key(cls):
|
399 |
+
return 3, 1, cls.__name__
|
400 |
+
|
401 |
+
@property
|
402 |
+
def kind(self):
|
403 |
+
k = attrgetter('kind')
|
404 |
+
kinds = map(k, self.args)
|
405 |
+
kinds = frozenset(kinds)
|
406 |
+
if len(kinds) != 1:
|
407 |
+
# Since addition is group operator, kind must be same.
|
408 |
+
# We know that this is unexpected signature, so return this.
|
409 |
+
result = UndefinedKind
|
410 |
+
else:
|
411 |
+
result, = kinds
|
412 |
+
return result
|
413 |
+
|
414 |
+
def could_extract_minus_sign(self):
|
415 |
+
return _could_extract_minus_sign(self)
|
416 |
+
|
417 |
+
@cacheit
|
418 |
+
def as_coeff_add(self, *deps):
|
419 |
+
"""
|
420 |
+
Returns a tuple (coeff, args) where self is treated as an Add and coeff
|
421 |
+
is the Number term and args is a tuple of all other terms.
|
422 |
+
|
423 |
+
Examples
|
424 |
+
========
|
425 |
+
|
426 |
+
>>> from sympy.abc import x
|
427 |
+
>>> (7 + 3*x).as_coeff_add()
|
428 |
+
(7, (3*x,))
|
429 |
+
>>> (7*x).as_coeff_add()
|
430 |
+
(0, (7*x,))
|
431 |
+
"""
|
432 |
+
if deps:
|
433 |
+
l1, l2 = sift(self.args, lambda x: x.has_free(*deps), binary=True)
|
434 |
+
return self._new_rawargs(*l2), tuple(l1)
|
435 |
+
coeff, notrat = self.args[0].as_coeff_add()
|
436 |
+
if coeff is not S.Zero:
|
437 |
+
return coeff, notrat + self.args[1:]
|
438 |
+
return S.Zero, self.args
|
439 |
+
|
440 |
+
def as_coeff_Add(self, rational=False, deps=None):
|
441 |
+
"""
|
442 |
+
Efficiently extract the coefficient of a summation.
|
443 |
+
"""
|
444 |
+
coeff, args = self.args[0], self.args[1:]
|
445 |
+
|
446 |
+
if coeff.is_Number and not rational or coeff.is_Rational:
|
447 |
+
return coeff, self._new_rawargs(*args)
|
448 |
+
return S.Zero, self
|
449 |
+
|
450 |
+
# Note, we intentionally do not implement Add.as_coeff_mul(). Rather, we
|
451 |
+
# let Expr.as_coeff_mul() just always return (S.One, self) for an Add. See
|
452 |
+
# issue 5524.
|
453 |
+
|
454 |
+
def _eval_power(self, e):
|
455 |
+
from .evalf import pure_complex
|
456 |
+
from .relational import is_eq
|
457 |
+
if len(self.args) == 2 and any(_.is_infinite for _ in self.args):
|
458 |
+
if e.is_zero is False and is_eq(e, S.One) is False:
|
459 |
+
# looking for literal a + I*b
|
460 |
+
a, b = self.args
|
461 |
+
if a.coeff(S.ImaginaryUnit):
|
462 |
+
a, b = b, a
|
463 |
+
ico = b.coeff(S.ImaginaryUnit)
|
464 |
+
if ico and ico.is_extended_real and a.is_extended_real:
|
465 |
+
if e.is_extended_negative:
|
466 |
+
return S.Zero
|
467 |
+
if e.is_extended_positive:
|
468 |
+
return S.ComplexInfinity
|
469 |
+
return
|
470 |
+
if e.is_Rational and self.is_number:
|
471 |
+
ri = pure_complex(self)
|
472 |
+
if ri:
|
473 |
+
r, i = ri
|
474 |
+
if e.q == 2:
|
475 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
476 |
+
D = sqrt(r**2 + i**2)
|
477 |
+
if D.is_Rational:
|
478 |
+
from .exprtools import factor_terms
|
479 |
+
from sympy.functions.elementary.complexes import sign
|
480 |
+
from .function import expand_multinomial
|
481 |
+
# (r, i, D) is a Pythagorean triple
|
482 |
+
root = sqrt(factor_terms((D - r)/2))**e.p
|
483 |
+
return root*expand_multinomial((
|
484 |
+
# principle value
|
485 |
+
(D + r)/abs(i) + sign(i)*S.ImaginaryUnit)**e.p)
|
486 |
+
elif e == -1:
|
487 |
+
return _unevaluated_Mul(
|
488 |
+
r - i*S.ImaginaryUnit,
|
489 |
+
1/(r**2 + i**2))
|
490 |
+
elif e.is_Number and abs(e) != 1:
|
491 |
+
# handle the Float case: (2.0 + 4*x)**e -> 4**e*(0.5 + x)**e
|
492 |
+
c, m = zip(*[i.as_coeff_Mul() for i in self.args])
|
493 |
+
if any(i.is_Float for i in c): # XXX should this always be done?
|
494 |
+
big = -1
|
495 |
+
for i in c:
|
496 |
+
if abs(i) >= big:
|
497 |
+
big = abs(i)
|
498 |
+
if big > 0 and not equal_valued(big, 1):
|
499 |
+
from sympy.functions.elementary.complexes import sign
|
500 |
+
bigs = (big, -big)
|
501 |
+
c = [sign(i) if i in bigs else i/big for i in c]
|
502 |
+
addpow = Add(*[c*m for c, m in zip(c, m)])**e
|
503 |
+
return big**e*addpow
|
504 |
+
|
505 |
+
@cacheit
|
506 |
+
def _eval_derivative(self, s):
|
507 |
+
return self.func(*[a.diff(s) for a in self.args])
|
508 |
+
|
509 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
510 |
+
terms = [t.nseries(x, n=n, logx=logx, cdir=cdir) for t in self.args]
|
511 |
+
return self.func(*terms)
|
512 |
+
|
513 |
+
def _matches_simple(self, expr, repl_dict):
|
514 |
+
# handle (w+3).matches('x+5') -> {w: x+2}
|
515 |
+
coeff, terms = self.as_coeff_add()
|
516 |
+
if len(terms) == 1:
|
517 |
+
return terms[0].matches(expr - coeff, repl_dict)
|
518 |
+
return
|
519 |
+
|
520 |
+
def matches(self, expr, repl_dict=None, old=False):
|
521 |
+
return self._matches_commutative(expr, repl_dict, old)
|
522 |
+
|
523 |
+
@staticmethod
|
524 |
+
def _combine_inverse(lhs, rhs):
|
525 |
+
"""
|
526 |
+
Returns lhs - rhs, but treats oo like a symbol so oo - oo
|
527 |
+
returns 0, instead of a nan.
|
528 |
+
"""
|
529 |
+
from sympy.simplify.simplify import signsimp
|
530 |
+
inf = (S.Infinity, S.NegativeInfinity)
|
531 |
+
if lhs.has(*inf) or rhs.has(*inf):
|
532 |
+
from .symbol import Dummy
|
533 |
+
oo = Dummy('oo')
|
534 |
+
reps = {
|
535 |
+
S.Infinity: oo,
|
536 |
+
S.NegativeInfinity: -oo}
|
537 |
+
ireps = {v: k for k, v in reps.items()}
|
538 |
+
eq = lhs.xreplace(reps) - rhs.xreplace(reps)
|
539 |
+
if eq.has(oo):
|
540 |
+
eq = eq.replace(
|
541 |
+
lambda x: x.is_Pow and x.base is oo,
|
542 |
+
lambda x: x.base)
|
543 |
+
rv = eq.xreplace(ireps)
|
544 |
+
else:
|
545 |
+
rv = lhs - rhs
|
546 |
+
srv = signsimp(rv)
|
547 |
+
return srv if srv.is_Number else rv
|
548 |
+
|
549 |
+
@cacheit
|
550 |
+
def as_two_terms(self):
|
551 |
+
"""Return head and tail of self.
|
552 |
+
|
553 |
+
This is the most efficient way to get the head and tail of an
|
554 |
+
expression.
|
555 |
+
|
556 |
+
- if you want only the head, use self.args[0];
|
557 |
+
- if you want to process the arguments of the tail then use
|
558 |
+
self.as_coef_add() which gives the head and a tuple containing
|
559 |
+
the arguments of the tail when treated as an Add.
|
560 |
+
- if you want the coefficient when self is treated as a Mul
|
561 |
+
then use self.as_coeff_mul()[0]
|
562 |
+
|
563 |
+
>>> from sympy.abc import x, y
|
564 |
+
>>> (3*x - 2*y + 5).as_two_terms()
|
565 |
+
(5, 3*x - 2*y)
|
566 |
+
"""
|
567 |
+
return self.args[0], self._new_rawargs(*self.args[1:])
|
568 |
+
|
569 |
+
def as_numer_denom(self):
|
570 |
+
"""
|
571 |
+
Decomposes an expression to its numerator part and its
|
572 |
+
denominator part.
|
573 |
+
|
574 |
+
Examples
|
575 |
+
========
|
576 |
+
|
577 |
+
>>> from sympy.abc import x, y, z
|
578 |
+
>>> (x*y/z).as_numer_denom()
|
579 |
+
(x*y, z)
|
580 |
+
>>> (x*(y + 1)/y**7).as_numer_denom()
|
581 |
+
(x*(y + 1), y**7)
|
582 |
+
|
583 |
+
See Also
|
584 |
+
========
|
585 |
+
|
586 |
+
sympy.core.expr.Expr.as_numer_denom
|
587 |
+
"""
|
588 |
+
# clear rational denominator
|
589 |
+
content, expr = self.primitive()
|
590 |
+
if not isinstance(expr, Add):
|
591 |
+
return Mul(content, expr, evaluate=False).as_numer_denom()
|
592 |
+
ncon, dcon = content.as_numer_denom()
|
593 |
+
|
594 |
+
# collect numerators and denominators of the terms
|
595 |
+
nd = defaultdict(list)
|
596 |
+
for f in expr.args:
|
597 |
+
ni, di = f.as_numer_denom()
|
598 |
+
nd[di].append(ni)
|
599 |
+
|
600 |
+
# check for quick exit
|
601 |
+
if len(nd) == 1:
|
602 |
+
d, n = nd.popitem()
|
603 |
+
return self.func(
|
604 |
+
*[_keep_coeff(ncon, ni) for ni in n]), _keep_coeff(dcon, d)
|
605 |
+
|
606 |
+
# sum up the terms having a common denominator
|
607 |
+
for d, n in nd.items():
|
608 |
+
if len(n) == 1:
|
609 |
+
nd[d] = n[0]
|
610 |
+
else:
|
611 |
+
nd[d] = self.func(*n)
|
612 |
+
|
613 |
+
# assemble single numerator and denominator
|
614 |
+
denoms, numers = [list(i) for i in zip(*iter(nd.items()))]
|
615 |
+
n, d = self.func(*[Mul(*(denoms[:i] + [numers[i]] + denoms[i + 1:]))
|
616 |
+
for i in range(len(numers))]), Mul(*denoms)
|
617 |
+
|
618 |
+
return _keep_coeff(ncon, n), _keep_coeff(dcon, d)
|
619 |
+
|
620 |
+
def _eval_is_polynomial(self, syms):
|
621 |
+
return all(term._eval_is_polynomial(syms) for term in self.args)
|
622 |
+
|
623 |
+
def _eval_is_rational_function(self, syms):
|
624 |
+
return all(term._eval_is_rational_function(syms) for term in self.args)
|
625 |
+
|
626 |
+
def _eval_is_meromorphic(self, x, a):
|
627 |
+
return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args),
|
628 |
+
quick_exit=True)
|
629 |
+
|
630 |
+
def _eval_is_algebraic_expr(self, syms):
|
631 |
+
return all(term._eval_is_algebraic_expr(syms) for term in self.args)
|
632 |
+
|
633 |
+
# assumption methods
|
634 |
+
_eval_is_real = lambda self: _fuzzy_group(
|
635 |
+
(a.is_real for a in self.args), quick_exit=True)
|
636 |
+
_eval_is_extended_real = lambda self: _fuzzy_group(
|
637 |
+
(a.is_extended_real for a in self.args), quick_exit=True)
|
638 |
+
_eval_is_complex = lambda self: _fuzzy_group(
|
639 |
+
(a.is_complex for a in self.args), quick_exit=True)
|
640 |
+
_eval_is_antihermitian = lambda self: _fuzzy_group(
|
641 |
+
(a.is_antihermitian for a in self.args), quick_exit=True)
|
642 |
+
_eval_is_finite = lambda self: _fuzzy_group(
|
643 |
+
(a.is_finite for a in self.args), quick_exit=True)
|
644 |
+
_eval_is_hermitian = lambda self: _fuzzy_group(
|
645 |
+
(a.is_hermitian for a in self.args), quick_exit=True)
|
646 |
+
_eval_is_integer = lambda self: _fuzzy_group(
|
647 |
+
(a.is_integer for a in self.args), quick_exit=True)
|
648 |
+
_eval_is_rational = lambda self: _fuzzy_group(
|
649 |
+
(a.is_rational for a in self.args), quick_exit=True)
|
650 |
+
_eval_is_algebraic = lambda self: _fuzzy_group(
|
651 |
+
(a.is_algebraic for a in self.args), quick_exit=True)
|
652 |
+
_eval_is_commutative = lambda self: _fuzzy_group(
|
653 |
+
a.is_commutative for a in self.args)
|
654 |
+
|
655 |
+
def _eval_is_infinite(self):
|
656 |
+
sawinf = False
|
657 |
+
for a in self.args:
|
658 |
+
ainf = a.is_infinite
|
659 |
+
if ainf is None:
|
660 |
+
return None
|
661 |
+
elif ainf is True:
|
662 |
+
# infinite+infinite might not be infinite
|
663 |
+
if sawinf is True:
|
664 |
+
return None
|
665 |
+
sawinf = True
|
666 |
+
return sawinf
|
667 |
+
|
668 |
+
def _eval_is_imaginary(self):
|
669 |
+
nz = []
|
670 |
+
im_I = []
|
671 |
+
for a in self.args:
|
672 |
+
if a.is_extended_real:
|
673 |
+
if a.is_zero:
|
674 |
+
pass
|
675 |
+
elif a.is_zero is False:
|
676 |
+
nz.append(a)
|
677 |
+
else:
|
678 |
+
return
|
679 |
+
elif a.is_imaginary:
|
680 |
+
im_I.append(a*S.ImaginaryUnit)
|
681 |
+
elif a.is_Mul and S.ImaginaryUnit in a.args:
|
682 |
+
coeff, ai = a.as_coeff_mul(S.ImaginaryUnit)
|
683 |
+
if ai == (S.ImaginaryUnit,) and coeff.is_extended_real:
|
684 |
+
im_I.append(-coeff)
|
685 |
+
else:
|
686 |
+
return
|
687 |
+
else:
|
688 |
+
return
|
689 |
+
b = self.func(*nz)
|
690 |
+
if b != self:
|
691 |
+
if b.is_zero:
|
692 |
+
return fuzzy_not(self.func(*im_I).is_zero)
|
693 |
+
elif b.is_zero is False:
|
694 |
+
return False
|
695 |
+
|
696 |
+
def _eval_is_zero(self):
|
697 |
+
if self.is_commutative is False:
|
698 |
+
# issue 10528: there is no way to know if a nc symbol
|
699 |
+
# is zero or not
|
700 |
+
return
|
701 |
+
nz = []
|
702 |
+
z = 0
|
703 |
+
im_or_z = False
|
704 |
+
im = 0
|
705 |
+
for a in self.args:
|
706 |
+
if a.is_extended_real:
|
707 |
+
if a.is_zero:
|
708 |
+
z += 1
|
709 |
+
elif a.is_zero is False:
|
710 |
+
nz.append(a)
|
711 |
+
else:
|
712 |
+
return
|
713 |
+
elif a.is_imaginary:
|
714 |
+
im += 1
|
715 |
+
elif a.is_Mul and S.ImaginaryUnit in a.args:
|
716 |
+
coeff, ai = a.as_coeff_mul(S.ImaginaryUnit)
|
717 |
+
if ai == (S.ImaginaryUnit,) and coeff.is_extended_real:
|
718 |
+
im_or_z = True
|
719 |
+
else:
|
720 |
+
return
|
721 |
+
else:
|
722 |
+
return
|
723 |
+
if z == len(self.args):
|
724 |
+
return True
|
725 |
+
if len(nz) in [0, len(self.args)]:
|
726 |
+
return None
|
727 |
+
b = self.func(*nz)
|
728 |
+
if b.is_zero:
|
729 |
+
if not im_or_z:
|
730 |
+
if im == 0:
|
731 |
+
return True
|
732 |
+
elif im == 1:
|
733 |
+
return False
|
734 |
+
if b.is_zero is False:
|
735 |
+
return False
|
736 |
+
|
737 |
+
def _eval_is_odd(self):
|
738 |
+
l = [f for f in self.args if not (f.is_even is True)]
|
739 |
+
if not l:
|
740 |
+
return False
|
741 |
+
if l[0].is_odd:
|
742 |
+
return self._new_rawargs(*l[1:]).is_even
|
743 |
+
|
744 |
+
def _eval_is_irrational(self):
|
745 |
+
for t in self.args:
|
746 |
+
a = t.is_irrational
|
747 |
+
if a:
|
748 |
+
others = list(self.args)
|
749 |
+
others.remove(t)
|
750 |
+
if all(x.is_rational is True for x in others):
|
751 |
+
return True
|
752 |
+
return None
|
753 |
+
if a is None:
|
754 |
+
return
|
755 |
+
return False
|
756 |
+
|
757 |
+
def _all_nonneg_or_nonppos(self):
|
758 |
+
nn = np = 0
|
759 |
+
for a in self.args:
|
760 |
+
if a.is_nonnegative:
|
761 |
+
if np:
|
762 |
+
return False
|
763 |
+
nn = 1
|
764 |
+
elif a.is_nonpositive:
|
765 |
+
if nn:
|
766 |
+
return False
|
767 |
+
np = 1
|
768 |
+
else:
|
769 |
+
break
|
770 |
+
else:
|
771 |
+
return True
|
772 |
+
|
773 |
+
def _eval_is_extended_positive(self):
|
774 |
+
if self.is_number:
|
775 |
+
return super()._eval_is_extended_positive()
|
776 |
+
c, a = self.as_coeff_Add()
|
777 |
+
if not c.is_zero:
|
778 |
+
from .exprtools import _monotonic_sign
|
779 |
+
v = _monotonic_sign(a)
|
780 |
+
if v is not None:
|
781 |
+
s = v + c
|
782 |
+
if s != self and s.is_extended_positive and a.is_extended_nonnegative:
|
783 |
+
return True
|
784 |
+
if len(self.free_symbols) == 1:
|
785 |
+
v = _monotonic_sign(self)
|
786 |
+
if v is not None and v != self and v.is_extended_positive:
|
787 |
+
return True
|
788 |
+
pos = nonneg = nonpos = unknown_sign = False
|
789 |
+
saw_INF = set()
|
790 |
+
args = [a for a in self.args if not a.is_zero]
|
791 |
+
if not args:
|
792 |
+
return False
|
793 |
+
for a in args:
|
794 |
+
ispos = a.is_extended_positive
|
795 |
+
infinite = a.is_infinite
|
796 |
+
if infinite:
|
797 |
+
saw_INF.add(fuzzy_or((ispos, a.is_extended_nonnegative)))
|
798 |
+
if True in saw_INF and False in saw_INF:
|
799 |
+
return
|
800 |
+
if ispos:
|
801 |
+
pos = True
|
802 |
+
continue
|
803 |
+
elif a.is_extended_nonnegative:
|
804 |
+
nonneg = True
|
805 |
+
continue
|
806 |
+
elif a.is_extended_nonpositive:
|
807 |
+
nonpos = True
|
808 |
+
continue
|
809 |
+
|
810 |
+
if infinite is None:
|
811 |
+
return
|
812 |
+
unknown_sign = True
|
813 |
+
|
814 |
+
if saw_INF:
|
815 |
+
if len(saw_INF) > 1:
|
816 |
+
return
|
817 |
+
return saw_INF.pop()
|
818 |
+
elif unknown_sign:
|
819 |
+
return
|
820 |
+
elif not nonpos and not nonneg and pos:
|
821 |
+
return True
|
822 |
+
elif not nonpos and pos:
|
823 |
+
return True
|
824 |
+
elif not pos and not nonneg:
|
825 |
+
return False
|
826 |
+
|
827 |
+
def _eval_is_extended_nonnegative(self):
|
828 |
+
if not self.is_number:
|
829 |
+
c, a = self.as_coeff_Add()
|
830 |
+
if not c.is_zero and a.is_extended_nonnegative:
|
831 |
+
from .exprtools import _monotonic_sign
|
832 |
+
v = _monotonic_sign(a)
|
833 |
+
if v is not None:
|
834 |
+
s = v + c
|
835 |
+
if s != self and s.is_extended_nonnegative:
|
836 |
+
return True
|
837 |
+
if len(self.free_symbols) == 1:
|
838 |
+
v = _monotonic_sign(self)
|
839 |
+
if v is not None and v != self and v.is_extended_nonnegative:
|
840 |
+
return True
|
841 |
+
|
842 |
+
def _eval_is_extended_nonpositive(self):
|
843 |
+
if not self.is_number:
|
844 |
+
c, a = self.as_coeff_Add()
|
845 |
+
if not c.is_zero and a.is_extended_nonpositive:
|
846 |
+
from .exprtools import _monotonic_sign
|
847 |
+
v = _monotonic_sign(a)
|
848 |
+
if v is not None:
|
849 |
+
s = v + c
|
850 |
+
if s != self and s.is_extended_nonpositive:
|
851 |
+
return True
|
852 |
+
if len(self.free_symbols) == 1:
|
853 |
+
v = _monotonic_sign(self)
|
854 |
+
if v is not None and v != self and v.is_extended_nonpositive:
|
855 |
+
return True
|
856 |
+
|
857 |
+
def _eval_is_extended_negative(self):
|
858 |
+
if self.is_number:
|
859 |
+
return super()._eval_is_extended_negative()
|
860 |
+
c, a = self.as_coeff_Add()
|
861 |
+
if not c.is_zero:
|
862 |
+
from .exprtools import _monotonic_sign
|
863 |
+
v = _monotonic_sign(a)
|
864 |
+
if v is not None:
|
865 |
+
s = v + c
|
866 |
+
if s != self and s.is_extended_negative and a.is_extended_nonpositive:
|
867 |
+
return True
|
868 |
+
if len(self.free_symbols) == 1:
|
869 |
+
v = _monotonic_sign(self)
|
870 |
+
if v is not None and v != self and v.is_extended_negative:
|
871 |
+
return True
|
872 |
+
neg = nonpos = nonneg = unknown_sign = False
|
873 |
+
saw_INF = set()
|
874 |
+
args = [a for a in self.args if not a.is_zero]
|
875 |
+
if not args:
|
876 |
+
return False
|
877 |
+
for a in args:
|
878 |
+
isneg = a.is_extended_negative
|
879 |
+
infinite = a.is_infinite
|
880 |
+
if infinite:
|
881 |
+
saw_INF.add(fuzzy_or((isneg, a.is_extended_nonpositive)))
|
882 |
+
if True in saw_INF and False in saw_INF:
|
883 |
+
return
|
884 |
+
if isneg:
|
885 |
+
neg = True
|
886 |
+
continue
|
887 |
+
elif a.is_extended_nonpositive:
|
888 |
+
nonpos = True
|
889 |
+
continue
|
890 |
+
elif a.is_extended_nonnegative:
|
891 |
+
nonneg = True
|
892 |
+
continue
|
893 |
+
|
894 |
+
if infinite is None:
|
895 |
+
return
|
896 |
+
unknown_sign = True
|
897 |
+
|
898 |
+
if saw_INF:
|
899 |
+
if len(saw_INF) > 1:
|
900 |
+
return
|
901 |
+
return saw_INF.pop()
|
902 |
+
elif unknown_sign:
|
903 |
+
return
|
904 |
+
elif not nonneg and not nonpos and neg:
|
905 |
+
return True
|
906 |
+
elif not nonneg and neg:
|
907 |
+
return True
|
908 |
+
elif not neg and not nonpos:
|
909 |
+
return False
|
910 |
+
|
911 |
+
def _eval_subs(self, old, new):
|
912 |
+
if not old.is_Add:
|
913 |
+
if old is S.Infinity and -old in self.args:
|
914 |
+
# foo - oo is foo + (-oo) internally
|
915 |
+
return self.xreplace({-old: -new})
|
916 |
+
return None
|
917 |
+
|
918 |
+
coeff_self, terms_self = self.as_coeff_Add()
|
919 |
+
coeff_old, terms_old = old.as_coeff_Add()
|
920 |
+
|
921 |
+
if coeff_self.is_Rational and coeff_old.is_Rational:
|
922 |
+
if terms_self == terms_old: # (2 + a).subs( 3 + a, y) -> -1 + y
|
923 |
+
return self.func(new, coeff_self, -coeff_old)
|
924 |
+
if terms_self == -terms_old: # (2 + a).subs(-3 - a, y) -> -1 - y
|
925 |
+
return self.func(-new, coeff_self, coeff_old)
|
926 |
+
|
927 |
+
if coeff_self.is_Rational and coeff_old.is_Rational \
|
928 |
+
or coeff_self == coeff_old:
|
929 |
+
args_old, args_self = self.func.make_args(
|
930 |
+
terms_old), self.func.make_args(terms_self)
|
931 |
+
if len(args_old) < len(args_self): # (a+b+c).subs(b+c,x) -> a+x
|
932 |
+
self_set = set(args_self)
|
933 |
+
old_set = set(args_old)
|
934 |
+
|
935 |
+
if old_set < self_set:
|
936 |
+
ret_set = self_set - old_set
|
937 |
+
return self.func(new, coeff_self, -coeff_old,
|
938 |
+
*[s._subs(old, new) for s in ret_set])
|
939 |
+
|
940 |
+
args_old = self.func.make_args(
|
941 |
+
-terms_old) # (a+b+c+d).subs(-b-c,x) -> a-x+d
|
942 |
+
old_set = set(args_old)
|
943 |
+
if old_set < self_set:
|
944 |
+
ret_set = self_set - old_set
|
945 |
+
return self.func(-new, coeff_self, coeff_old,
|
946 |
+
*[s._subs(old, new) for s in ret_set])
|
947 |
+
|
948 |
+
def removeO(self):
|
949 |
+
args = [a for a in self.args if not a.is_Order]
|
950 |
+
return self._new_rawargs(*args)
|
951 |
+
|
952 |
+
def getO(self):
|
953 |
+
args = [a for a in self.args if a.is_Order]
|
954 |
+
if args:
|
955 |
+
return self._new_rawargs(*args)
|
956 |
+
|
957 |
+
@cacheit
|
958 |
+
def extract_leading_order(self, symbols, point=None):
|
959 |
+
"""
|
960 |
+
Returns the leading term and its order.
|
961 |
+
|
962 |
+
Examples
|
963 |
+
========
|
964 |
+
|
965 |
+
>>> from sympy.abc import x
|
966 |
+
>>> (x + 1 + 1/x**5).extract_leading_order(x)
|
967 |
+
((x**(-5), O(x**(-5))),)
|
968 |
+
>>> (1 + x).extract_leading_order(x)
|
969 |
+
((1, O(1)),)
|
970 |
+
>>> (x + x**2).extract_leading_order(x)
|
971 |
+
((x, O(x)),)
|
972 |
+
|
973 |
+
"""
|
974 |
+
from sympy.series.order import Order
|
975 |
+
lst = []
|
976 |
+
symbols = list(symbols if is_sequence(symbols) else [symbols])
|
977 |
+
if not point:
|
978 |
+
point = [0]*len(symbols)
|
979 |
+
seq = [(f, Order(f, *zip(symbols, point))) for f in self.args]
|
980 |
+
for ef, of in seq:
|
981 |
+
for e, o in lst:
|
982 |
+
if o.contains(of) and o != of:
|
983 |
+
of = None
|
984 |
+
break
|
985 |
+
if of is None:
|
986 |
+
continue
|
987 |
+
new_lst = [(ef, of)]
|
988 |
+
for e, o in lst:
|
989 |
+
if of.contains(o) and o != of:
|
990 |
+
continue
|
991 |
+
new_lst.append((e, o))
|
992 |
+
lst = new_lst
|
993 |
+
return tuple(lst)
|
994 |
+
|
995 |
+
def as_real_imag(self, deep=True, **hints):
|
996 |
+
"""
|
997 |
+
Return a tuple representing a complex number.
|
998 |
+
|
999 |
+
Examples
|
1000 |
+
========
|
1001 |
+
|
1002 |
+
>>> from sympy import I
|
1003 |
+
>>> (7 + 9*I).as_real_imag()
|
1004 |
+
(7, 9)
|
1005 |
+
>>> ((1 + I)/(1 - I)).as_real_imag()
|
1006 |
+
(0, 1)
|
1007 |
+
>>> ((1 + 2*I)*(1 + 3*I)).as_real_imag()
|
1008 |
+
(-5, 5)
|
1009 |
+
"""
|
1010 |
+
sargs = self.args
|
1011 |
+
re_part, im_part = [], []
|
1012 |
+
for term in sargs:
|
1013 |
+
re, im = term.as_real_imag(deep=deep)
|
1014 |
+
re_part.append(re)
|
1015 |
+
im_part.append(im)
|
1016 |
+
return (self.func(*re_part), self.func(*im_part))
|
1017 |
+
|
1018 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
1019 |
+
from sympy.core.symbol import Dummy, Symbol
|
1020 |
+
from sympy.series.order import Order
|
1021 |
+
from sympy.functions.elementary.exponential import log
|
1022 |
+
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
|
1023 |
+
from .function import expand_mul
|
1024 |
+
|
1025 |
+
o = self.getO()
|
1026 |
+
if o is None:
|
1027 |
+
o = Order(0)
|
1028 |
+
old = self.removeO()
|
1029 |
+
|
1030 |
+
if old.has(Piecewise):
|
1031 |
+
old = piecewise_fold(old)
|
1032 |
+
|
1033 |
+
# This expansion is the last part of expand_log. expand_log also calls
|
1034 |
+
# expand_mul with factor=True, which would be more expensive
|
1035 |
+
if any(isinstance(a, log) for a in self.args):
|
1036 |
+
logflags = {"deep": True, "log": True, "mul": False, "power_exp": False,
|
1037 |
+
"power_base": False, "multinomial": False, "basic": False, "force": False,
|
1038 |
+
"factor": False}
|
1039 |
+
old = old.expand(**logflags)
|
1040 |
+
expr = expand_mul(old)
|
1041 |
+
|
1042 |
+
if not expr.is_Add:
|
1043 |
+
return expr.as_leading_term(x, logx=logx, cdir=cdir)
|
1044 |
+
|
1045 |
+
infinite = [t for t in expr.args if t.is_infinite]
|
1046 |
+
|
1047 |
+
_logx = Dummy('logx') if logx is None else logx
|
1048 |
+
leading_terms = [t.as_leading_term(x, logx=_logx, cdir=cdir) for t in expr.args]
|
1049 |
+
|
1050 |
+
min, new_expr = Order(0), 0
|
1051 |
+
|
1052 |
+
try:
|
1053 |
+
for term in leading_terms:
|
1054 |
+
order = Order(term, x)
|
1055 |
+
if not min or order not in min:
|
1056 |
+
min = order
|
1057 |
+
new_expr = term
|
1058 |
+
elif min in order:
|
1059 |
+
new_expr += term
|
1060 |
+
|
1061 |
+
except TypeError:
|
1062 |
+
return expr
|
1063 |
+
|
1064 |
+
if logx is None:
|
1065 |
+
new_expr = new_expr.subs(_logx, log(x))
|
1066 |
+
|
1067 |
+
is_zero = new_expr.is_zero
|
1068 |
+
if is_zero is None:
|
1069 |
+
new_expr = new_expr.trigsimp().cancel()
|
1070 |
+
is_zero = new_expr.is_zero
|
1071 |
+
if is_zero is True:
|
1072 |
+
# simple leading term analysis gave us cancelled terms but we have to send
|
1073 |
+
# back a term, so compute the leading term (via series)
|
1074 |
+
try:
|
1075 |
+
n0 = min.getn()
|
1076 |
+
except NotImplementedError:
|
1077 |
+
n0 = S.One
|
1078 |
+
if n0.has(Symbol):
|
1079 |
+
n0 = S.One
|
1080 |
+
res = Order(1)
|
1081 |
+
incr = S.One
|
1082 |
+
while res.is_Order:
|
1083 |
+
res = old._eval_nseries(x, n=n0+incr, logx=logx, cdir=cdir).cancel().powsimp().trigsimp()
|
1084 |
+
incr *= 2
|
1085 |
+
return res.as_leading_term(x, logx=logx, cdir=cdir)
|
1086 |
+
|
1087 |
+
elif new_expr is S.NaN:
|
1088 |
+
return old.func._from_args(infinite) + o
|
1089 |
+
|
1090 |
+
else:
|
1091 |
+
return new_expr
|
1092 |
+
|
1093 |
+
def _eval_adjoint(self):
|
1094 |
+
return self.func(*[t.adjoint() for t in self.args])
|
1095 |
+
|
1096 |
+
def _eval_conjugate(self):
|
1097 |
+
return self.func(*[t.conjugate() for t in self.args])
|
1098 |
+
|
1099 |
+
def _eval_transpose(self):
|
1100 |
+
return self.func(*[t.transpose() for t in self.args])
|
1101 |
+
|
1102 |
+
def primitive(self):
|
1103 |
+
"""
|
1104 |
+
Return ``(R, self/R)`` where ``R``` is the Rational GCD of ``self```.
|
1105 |
+
|
1106 |
+
``R`` is collected only from the leading coefficient of each term.
|
1107 |
+
|
1108 |
+
Examples
|
1109 |
+
========
|
1110 |
+
|
1111 |
+
>>> from sympy.abc import x, y
|
1112 |
+
|
1113 |
+
>>> (2*x + 4*y).primitive()
|
1114 |
+
(2, x + 2*y)
|
1115 |
+
|
1116 |
+
>>> (2*x/3 + 4*y/9).primitive()
|
1117 |
+
(2/9, 3*x + 2*y)
|
1118 |
+
|
1119 |
+
>>> (2*x/3 + 4.2*y).primitive()
|
1120 |
+
(1/3, 2*x + 12.6*y)
|
1121 |
+
|
1122 |
+
No subprocessing of term factors is performed:
|
1123 |
+
|
1124 |
+
>>> ((2 + 2*x)*x + 2).primitive()
|
1125 |
+
(1, x*(2*x + 2) + 2)
|
1126 |
+
|
1127 |
+
Recursive processing can be done with the ``as_content_primitive()``
|
1128 |
+
method:
|
1129 |
+
|
1130 |
+
>>> ((2 + 2*x)*x + 2).as_content_primitive()
|
1131 |
+
(2, x*(x + 1) + 1)
|
1132 |
+
|
1133 |
+
See also: primitive() function in polytools.py
|
1134 |
+
|
1135 |
+
"""
|
1136 |
+
|
1137 |
+
terms = []
|
1138 |
+
inf = False
|
1139 |
+
for a in self.args:
|
1140 |
+
c, m = a.as_coeff_Mul()
|
1141 |
+
if not c.is_Rational:
|
1142 |
+
c = S.One
|
1143 |
+
m = a
|
1144 |
+
inf = inf or m is S.ComplexInfinity
|
1145 |
+
terms.append((c.p, c.q, m))
|
1146 |
+
|
1147 |
+
if not inf:
|
1148 |
+
ngcd = reduce(igcd, [t[0] for t in terms], 0)
|
1149 |
+
dlcm = reduce(ilcm, [t[1] for t in terms], 1)
|
1150 |
+
else:
|
1151 |
+
ngcd = reduce(igcd, [t[0] for t in terms if t[1]], 0)
|
1152 |
+
dlcm = reduce(ilcm, [t[1] for t in terms if t[1]], 1)
|
1153 |
+
|
1154 |
+
if ngcd == dlcm == 1:
|
1155 |
+
return S.One, self
|
1156 |
+
if not inf:
|
1157 |
+
for i, (p, q, term) in enumerate(terms):
|
1158 |
+
terms[i] = _keep_coeff(Rational((p//ngcd)*(dlcm//q)), term)
|
1159 |
+
else:
|
1160 |
+
for i, (p, q, term) in enumerate(terms):
|
1161 |
+
if q:
|
1162 |
+
terms[i] = _keep_coeff(Rational((p//ngcd)*(dlcm//q)), term)
|
1163 |
+
else:
|
1164 |
+
terms[i] = _keep_coeff(Rational(p, q), term)
|
1165 |
+
|
1166 |
+
# we don't need a complete re-flattening since no new terms will join
|
1167 |
+
# so we just use the same sort as is used in Add.flatten. When the
|
1168 |
+
# coefficient changes, the ordering of terms may change, e.g.
|
1169 |
+
# (3*x, 6*y) -> (2*y, x)
|
1170 |
+
#
|
1171 |
+
# We do need to make sure that term[0] stays in position 0, however.
|
1172 |
+
#
|
1173 |
+
if terms[0].is_Number or terms[0] is S.ComplexInfinity:
|
1174 |
+
c = terms.pop(0)
|
1175 |
+
else:
|
1176 |
+
c = None
|
1177 |
+
_addsort(terms)
|
1178 |
+
if c:
|
1179 |
+
terms.insert(0, c)
|
1180 |
+
return Rational(ngcd, dlcm), self._new_rawargs(*terms)
|
1181 |
+
|
1182 |
+
def as_content_primitive(self, radical=False, clear=True):
|
1183 |
+
"""Return the tuple (R, self/R) where R is the positive Rational
|
1184 |
+
extracted from self. If radical is True (default is False) then
|
1185 |
+
common radicals will be removed and included as a factor of the
|
1186 |
+
primitive expression.
|
1187 |
+
|
1188 |
+
Examples
|
1189 |
+
========
|
1190 |
+
|
1191 |
+
>>> from sympy import sqrt
|
1192 |
+
>>> (3 + 3*sqrt(2)).as_content_primitive()
|
1193 |
+
(3, 1 + sqrt(2))
|
1194 |
+
|
1195 |
+
Radical content can also be factored out of the primitive:
|
1196 |
+
|
1197 |
+
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
|
1198 |
+
(2, sqrt(2)*(1 + 2*sqrt(5)))
|
1199 |
+
|
1200 |
+
See docstring of Expr.as_content_primitive for more examples.
|
1201 |
+
"""
|
1202 |
+
con, prim = self.func(*[_keep_coeff(*a.as_content_primitive(
|
1203 |
+
radical=radical, clear=clear)) for a in self.args]).primitive()
|
1204 |
+
if not clear and not con.is_Integer and prim.is_Add:
|
1205 |
+
con, d = con.as_numer_denom()
|
1206 |
+
_p = prim/d
|
1207 |
+
if any(a.as_coeff_Mul()[0].is_Integer for a in _p.args):
|
1208 |
+
prim = _p
|
1209 |
+
else:
|
1210 |
+
con /= d
|
1211 |
+
if radical and prim.is_Add:
|
1212 |
+
# look for common radicals that can be removed
|
1213 |
+
args = prim.args
|
1214 |
+
rads = []
|
1215 |
+
common_q = None
|
1216 |
+
for m in args:
|
1217 |
+
term_rads = defaultdict(list)
|
1218 |
+
for ai in Mul.make_args(m):
|
1219 |
+
if ai.is_Pow:
|
1220 |
+
b, e = ai.as_base_exp()
|
1221 |
+
if e.is_Rational and b.is_Integer:
|
1222 |
+
term_rads[e.q].append(abs(int(b))**e.p)
|
1223 |
+
if not term_rads:
|
1224 |
+
break
|
1225 |
+
if common_q is None:
|
1226 |
+
common_q = set(term_rads.keys())
|
1227 |
+
else:
|
1228 |
+
common_q = common_q & set(term_rads.keys())
|
1229 |
+
if not common_q:
|
1230 |
+
break
|
1231 |
+
rads.append(term_rads)
|
1232 |
+
else:
|
1233 |
+
# process rads
|
1234 |
+
# keep only those in common_q
|
1235 |
+
for r in rads:
|
1236 |
+
for q in list(r.keys()):
|
1237 |
+
if q not in common_q:
|
1238 |
+
r.pop(q)
|
1239 |
+
for q in r:
|
1240 |
+
r[q] = Mul(*r[q])
|
1241 |
+
# find the gcd of bases for each q
|
1242 |
+
G = []
|
1243 |
+
for q in common_q:
|
1244 |
+
g = reduce(igcd, [r[q] for r in rads], 0)
|
1245 |
+
if g != 1:
|
1246 |
+
G.append(g**Rational(1, q))
|
1247 |
+
if G:
|
1248 |
+
G = Mul(*G)
|
1249 |
+
args = [ai/G for ai in args]
|
1250 |
+
prim = G*prim.func(*args)
|
1251 |
+
|
1252 |
+
return con, prim
|
1253 |
+
|
1254 |
+
@property
|
1255 |
+
def _sorted_args(self):
|
1256 |
+
from .sorting import default_sort_key
|
1257 |
+
return tuple(sorted(self.args, key=default_sort_key))
|
1258 |
+
|
1259 |
+
def _eval_difference_delta(self, n, step):
|
1260 |
+
from sympy.series.limitseq import difference_delta as dd
|
1261 |
+
return self.func(*[dd(a, n, step) for a in self.args])
|
1262 |
+
|
1263 |
+
@property
|
1264 |
+
def _mpc_(self):
|
1265 |
+
"""
|
1266 |
+
Convert self to an mpmath mpc if possible
|
1267 |
+
"""
|
1268 |
+
from .numbers import Float
|
1269 |
+
re_part, rest = self.as_coeff_Add()
|
1270 |
+
im_part, imag_unit = rest.as_coeff_Mul()
|
1271 |
+
if not imag_unit == S.ImaginaryUnit:
|
1272 |
+
# ValueError may seem more reasonable but since it's a @property,
|
1273 |
+
# we need to use AttributeError to keep from confusing things like
|
1274 |
+
# hasattr.
|
1275 |
+
raise AttributeError("Cannot convert Add to mpc. Must be of the form Number + Number*I")
|
1276 |
+
|
1277 |
+
return (Float(re_part)._mpf_, Float(im_part)._mpf_)
|
1278 |
+
|
1279 |
+
def __neg__(self):
|
1280 |
+
if not global_parameters.distribute:
|
1281 |
+
return super().__neg__()
|
1282 |
+
return Mul(S.NegativeOne, self)
|
1283 |
+
|
1284 |
+
add = AssocOpDispatcher('add')
|
1285 |
+
|
1286 |
+
from .mul import Mul, _keep_coeff, _unevaluated_Mul
|
1287 |
+
from .numbers import Rational
|
llmeval-env/lib/python3.10/site-packages/sympy/core/alphabets.py
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
greeks = ('alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',
|
2 |
+
'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu',
|
3 |
+
'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon',
|
4 |
+
'phi', 'chi', 'psi', 'omega')
|
llmeval-env/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 |
+
]
|
llmeval-env/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()
|
llmeval-env/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
|
llmeval-env/lib/python3.10/site-packages/sympy/core/containers.py
ADDED
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
llmeval-env/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)
|
llmeval-env/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. """
|
llmeval-env/lib/python3.10/site-packages/sympy/core/decorators.py
ADDED
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
SymPy core decorators.
|
3 |
+
|
4 |
+
The purpose of this module is to expose decorators without any other
|
5 |
+
dependencies, so that they can be easily imported anywhere in sympy/core.
|
6 |
+
"""
|
7 |
+
|
8 |
+
from functools import wraps
|
9 |
+
from .sympify import SympifyError, sympify
|
10 |
+
|
11 |
+
|
12 |
+
def _sympifyit(arg, retval=None):
|
13 |
+
"""
|
14 |
+
decorator to smartly _sympify function arguments
|
15 |
+
|
16 |
+
Explanation
|
17 |
+
===========
|
18 |
+
|
19 |
+
@_sympifyit('other', NotImplemented)
|
20 |
+
def add(self, other):
|
21 |
+
...
|
22 |
+
|
23 |
+
In add, other can be thought of as already being a SymPy object.
|
24 |
+
|
25 |
+
If it is not, the code is likely to catch an exception, then other will
|
26 |
+
be explicitly _sympified, and the whole code restarted.
|
27 |
+
|
28 |
+
if _sympify(arg) fails, NotImplemented will be returned
|
29 |
+
|
30 |
+
See also
|
31 |
+
========
|
32 |
+
|
33 |
+
__sympifyit
|
34 |
+
"""
|
35 |
+
def deco(func):
|
36 |
+
return __sympifyit(func, arg, retval)
|
37 |
+
|
38 |
+
return deco
|
39 |
+
|
40 |
+
|
41 |
+
def __sympifyit(func, arg, retval=None):
|
42 |
+
"""Decorator to _sympify `arg` argument for function `func`.
|
43 |
+
|
44 |
+
Do not use directly -- use _sympifyit instead.
|
45 |
+
"""
|
46 |
+
|
47 |
+
# we support f(a,b) only
|
48 |
+
if not func.__code__.co_argcount:
|
49 |
+
raise LookupError("func not found")
|
50 |
+
# only b is _sympified
|
51 |
+
assert func.__code__.co_varnames[1] == arg
|
52 |
+
if retval is None:
|
53 |
+
@wraps(func)
|
54 |
+
def __sympifyit_wrapper(a, b):
|
55 |
+
return func(a, sympify(b, strict=True))
|
56 |
+
|
57 |
+
else:
|
58 |
+
@wraps(func)
|
59 |
+
def __sympifyit_wrapper(a, b):
|
60 |
+
try:
|
61 |
+
# If an external class has _op_priority, it knows how to deal
|
62 |
+
# with SymPy objects. Otherwise, it must be converted.
|
63 |
+
if not hasattr(b, '_op_priority'):
|
64 |
+
b = sympify(b, strict=True)
|
65 |
+
return func(a, b)
|
66 |
+
except SympifyError:
|
67 |
+
return retval
|
68 |
+
|
69 |
+
return __sympifyit_wrapper
|
70 |
+
|
71 |
+
|
72 |
+
def call_highest_priority(method_name):
|
73 |
+
"""A decorator for binary special methods to handle _op_priority.
|
74 |
+
|
75 |
+
Explanation
|
76 |
+
===========
|
77 |
+
|
78 |
+
Binary special methods in Expr and its subclasses use a special attribute
|
79 |
+
'_op_priority' to determine whose special method will be called to
|
80 |
+
handle the operation. In general, the object having the highest value of
|
81 |
+
'_op_priority' will handle the operation. Expr and subclasses that define
|
82 |
+
custom binary special methods (__mul__, etc.) should decorate those
|
83 |
+
methods with this decorator to add the priority logic.
|
84 |
+
|
85 |
+
The ``method_name`` argument is the name of the method of the other class
|
86 |
+
that will be called. Use this decorator in the following manner::
|
87 |
+
|
88 |
+
# Call other.__rmul__ if other._op_priority > self._op_priority
|
89 |
+
@call_highest_priority('__rmul__')
|
90 |
+
def __mul__(self, other):
|
91 |
+
...
|
92 |
+
|
93 |
+
# Call other.__mul__ if other._op_priority > self._op_priority
|
94 |
+
@call_highest_priority('__mul__')
|
95 |
+
def __rmul__(self, other):
|
96 |
+
...
|
97 |
+
"""
|
98 |
+
def priority_decorator(func):
|
99 |
+
@wraps(func)
|
100 |
+
def binary_op_wrapper(self, other):
|
101 |
+
if hasattr(other, '_op_priority'):
|
102 |
+
if other._op_priority > self._op_priority:
|
103 |
+
f = getattr(other, method_name, None)
|
104 |
+
if f is not None:
|
105 |
+
return f(self)
|
106 |
+
return func(self, other)
|
107 |
+
return binary_op_wrapper
|
108 |
+
return priority_decorator
|
109 |
+
|
110 |
+
|
111 |
+
def sympify_method_args(cls):
|
112 |
+
'''Decorator for a class with methods that sympify arguments.
|
113 |
+
|
114 |
+
Explanation
|
115 |
+
===========
|
116 |
+
|
117 |
+
The sympify_method_args decorator is to be used with the sympify_return
|
118 |
+
decorator for automatic sympification of method arguments. This is
|
119 |
+
intended for the common idiom of writing a class like :
|
120 |
+
|
121 |
+
Examples
|
122 |
+
========
|
123 |
+
|
124 |
+
>>> from sympy import Basic, SympifyError, S
|
125 |
+
>>> from sympy.core.sympify import _sympify
|
126 |
+
|
127 |
+
>>> class MyTuple(Basic):
|
128 |
+
... def __add__(self, other):
|
129 |
+
... try:
|
130 |
+
... other = _sympify(other)
|
131 |
+
... except SympifyError:
|
132 |
+
... return NotImplemented
|
133 |
+
... if not isinstance(other, MyTuple):
|
134 |
+
... return NotImplemented
|
135 |
+
... return MyTuple(*(self.args + other.args))
|
136 |
+
|
137 |
+
>>> MyTuple(S(1), S(2)) + MyTuple(S(3), S(4))
|
138 |
+
MyTuple(1, 2, 3, 4)
|
139 |
+
|
140 |
+
In the above it is important that we return NotImplemented when other is
|
141 |
+
not sympifiable and also when the sympified result is not of the expected
|
142 |
+
type. This allows the MyTuple class to be used cooperatively with other
|
143 |
+
classes that overload __add__ and want to do something else in combination
|
144 |
+
with instance of Tuple.
|
145 |
+
|
146 |
+
Using this decorator the above can be written as
|
147 |
+
|
148 |
+
>>> from sympy.core.decorators import sympify_method_args, sympify_return
|
149 |
+
|
150 |
+
>>> @sympify_method_args
|
151 |
+
... class MyTuple(Basic):
|
152 |
+
... @sympify_return([('other', 'MyTuple')], NotImplemented)
|
153 |
+
... def __add__(self, other):
|
154 |
+
... return MyTuple(*(self.args + other.args))
|
155 |
+
|
156 |
+
>>> MyTuple(S(1), S(2)) + MyTuple(S(3), S(4))
|
157 |
+
MyTuple(1, 2, 3, 4)
|
158 |
+
|
159 |
+
The idea here is that the decorators take care of the boiler-plate code
|
160 |
+
for making this happen in each method that potentially needs to accept
|
161 |
+
unsympified arguments. Then the body of e.g. the __add__ method can be
|
162 |
+
written without needing to worry about calling _sympify or checking the
|
163 |
+
type of the resulting object.
|
164 |
+
|
165 |
+
The parameters for sympify_return are a list of tuples of the form
|
166 |
+
(parameter_name, expected_type) and the value to return (e.g.
|
167 |
+
NotImplemented). The expected_type parameter can be a type e.g. Tuple or a
|
168 |
+
string 'Tuple'. Using a string is useful for specifying a Type within its
|
169 |
+
class body (as in the above example).
|
170 |
+
|
171 |
+
Notes: Currently sympify_return only works for methods that take a single
|
172 |
+
argument (not including self). Specifying an expected_type as a string
|
173 |
+
only works for the class in which the method is defined.
|
174 |
+
'''
|
175 |
+
# Extract the wrapped methods from each of the wrapper objects created by
|
176 |
+
# the sympify_return decorator. Doing this here allows us to provide the
|
177 |
+
# cls argument which is used for forward string referencing.
|
178 |
+
for attrname, obj in cls.__dict__.items():
|
179 |
+
if isinstance(obj, _SympifyWrapper):
|
180 |
+
setattr(cls, attrname, obj.make_wrapped(cls))
|
181 |
+
return cls
|
182 |
+
|
183 |
+
|
184 |
+
def sympify_return(*args):
|
185 |
+
'''Function/method decorator to sympify arguments automatically
|
186 |
+
|
187 |
+
See the docstring of sympify_method_args for explanation.
|
188 |
+
'''
|
189 |
+
# Store a wrapper object for the decorated method
|
190 |
+
def wrapper(func):
|
191 |
+
return _SympifyWrapper(func, args)
|
192 |
+
return wrapper
|
193 |
+
|
194 |
+
|
195 |
+
class _SympifyWrapper:
|
196 |
+
'''Internal class used by sympify_return and sympify_method_args'''
|
197 |
+
|
198 |
+
def __init__(self, func, args):
|
199 |
+
self.func = func
|
200 |
+
self.args = args
|
201 |
+
|
202 |
+
def make_wrapped(self, cls):
|
203 |
+
func = self.func
|
204 |
+
parameters, retval = self.args
|
205 |
+
|
206 |
+
# XXX: Handle more than one parameter?
|
207 |
+
[(parameter, expectedcls)] = parameters
|
208 |
+
|
209 |
+
# Handle forward references to the current class using strings
|
210 |
+
if expectedcls == cls.__name__:
|
211 |
+
expectedcls = cls
|
212 |
+
|
213 |
+
# Raise RuntimeError since this is a failure at import time and should
|
214 |
+
# not be recoverable.
|
215 |
+
nargs = func.__code__.co_argcount
|
216 |
+
# we support f(a, b) only
|
217 |
+
if nargs != 2:
|
218 |
+
raise RuntimeError('sympify_return can only be used with 2 argument functions')
|
219 |
+
# only b is _sympified
|
220 |
+
if func.__code__.co_varnames[1] != parameter:
|
221 |
+
raise RuntimeError('parameter name mismatch "%s" in %s' %
|
222 |
+
(parameter, func.__name__))
|
223 |
+
|
224 |
+
@wraps(func)
|
225 |
+
def _func(self, other):
|
226 |
+
# XXX: The check for _op_priority here should be removed. It is
|
227 |
+
# needed to stop mutable matrices from being sympified to
|
228 |
+
# immutable matrices which breaks things in quantum...
|
229 |
+
if not hasattr(other, '_op_priority'):
|
230 |
+
try:
|
231 |
+
other = sympify(other, strict=True)
|
232 |
+
except SympifyError:
|
233 |
+
return retval
|
234 |
+
if not isinstance(other, expectedcls):
|
235 |
+
return retval
|
236 |
+
return func(self, other)
|
237 |
+
|
238 |
+
return _func
|
llmeval-env/lib/python3.10/site-packages/sympy/core/expr.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
llmeval-env/lib/python3.10/site-packages/sympy/core/function.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
llmeval-env/lib/python3.10/site-packages/sympy/core/logic.py
ADDED
@@ -0,0 +1,427 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
llmeval-env/lib/python3.10/site-packages/sympy/core/mod.py
ADDED
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .add import Add
|
2 |
+
from .exprtools import gcd_terms
|
3 |
+
from .function import Function
|
4 |
+
from .kind import NumberKind
|
5 |
+
from .logic import fuzzy_and, fuzzy_not
|
6 |
+
from .mul import Mul
|
7 |
+
from .numbers import equal_valued
|
8 |
+
from .singleton import S
|
9 |
+
|
10 |
+
|
11 |
+
class Mod(Function):
|
12 |
+
"""Represents a modulo operation on symbolic expressions.
|
13 |
+
|
14 |
+
Parameters
|
15 |
+
==========
|
16 |
+
|
17 |
+
p : Expr
|
18 |
+
Dividend.
|
19 |
+
|
20 |
+
q : Expr
|
21 |
+
Divisor.
|
22 |
+
|
23 |
+
Notes
|
24 |
+
=====
|
25 |
+
|
26 |
+
The convention used is the same as Python's: the remainder always has the
|
27 |
+
same sign as the divisor.
|
28 |
+
|
29 |
+
Examples
|
30 |
+
========
|
31 |
+
|
32 |
+
>>> from sympy.abc import x, y
|
33 |
+
>>> x**2 % y
|
34 |
+
Mod(x**2, y)
|
35 |
+
>>> _.subs({x: 5, y: 6})
|
36 |
+
1
|
37 |
+
|
38 |
+
"""
|
39 |
+
|
40 |
+
kind = NumberKind
|
41 |
+
|
42 |
+
@classmethod
|
43 |
+
def eval(cls, p, q):
|
44 |
+
def number_eval(p, q):
|
45 |
+
"""Try to return p % q if both are numbers or +/-p is known
|
46 |
+
to be less than or equal q.
|
47 |
+
"""
|
48 |
+
|
49 |
+
if q.is_zero:
|
50 |
+
raise ZeroDivisionError("Modulo by zero")
|
51 |
+
if p is S.NaN or q is S.NaN or p.is_finite is False or q.is_finite is False:
|
52 |
+
return S.NaN
|
53 |
+
if p is S.Zero or p in (q, -q) or (p.is_integer and q == 1):
|
54 |
+
return S.Zero
|
55 |
+
|
56 |
+
if q.is_Number:
|
57 |
+
if p.is_Number:
|
58 |
+
return p%q
|
59 |
+
if q == 2:
|
60 |
+
if p.is_even:
|
61 |
+
return S.Zero
|
62 |
+
elif p.is_odd:
|
63 |
+
return S.One
|
64 |
+
|
65 |
+
if hasattr(p, '_eval_Mod'):
|
66 |
+
rv = getattr(p, '_eval_Mod')(q)
|
67 |
+
if rv is not None:
|
68 |
+
return rv
|
69 |
+
|
70 |
+
# by ratio
|
71 |
+
r = p/q
|
72 |
+
if r.is_integer:
|
73 |
+
return S.Zero
|
74 |
+
try:
|
75 |
+
d = int(r)
|
76 |
+
except TypeError:
|
77 |
+
pass
|
78 |
+
else:
|
79 |
+
if isinstance(d, int):
|
80 |
+
rv = p - d*q
|
81 |
+
if (rv*q < 0) == True:
|
82 |
+
rv += q
|
83 |
+
return rv
|
84 |
+
|
85 |
+
# by difference
|
86 |
+
# -2|q| < p < 2|q|
|
87 |
+
d = abs(p)
|
88 |
+
for _ in range(2):
|
89 |
+
d -= abs(q)
|
90 |
+
if d.is_negative:
|
91 |
+
if q.is_positive:
|
92 |
+
if p.is_positive:
|
93 |
+
return d + q
|
94 |
+
elif p.is_negative:
|
95 |
+
return -d
|
96 |
+
elif q.is_negative:
|
97 |
+
if p.is_positive:
|
98 |
+
return d
|
99 |
+
elif p.is_negative:
|
100 |
+
return -d + q
|
101 |
+
break
|
102 |
+
|
103 |
+
rv = number_eval(p, q)
|
104 |
+
if rv is not None:
|
105 |
+
return rv
|
106 |
+
|
107 |
+
# denest
|
108 |
+
if isinstance(p, cls):
|
109 |
+
qinner = p.args[1]
|
110 |
+
if qinner % q == 0:
|
111 |
+
return cls(p.args[0], q)
|
112 |
+
elif (qinner*(q - qinner)).is_nonnegative:
|
113 |
+
# |qinner| < |q| and have same sign
|
114 |
+
return p
|
115 |
+
elif isinstance(-p, cls):
|
116 |
+
qinner = (-p).args[1]
|
117 |
+
if qinner % q == 0:
|
118 |
+
return cls(-(-p).args[0], q)
|
119 |
+
elif (qinner*(q + qinner)).is_nonpositive:
|
120 |
+
# |qinner| < |q| and have different sign
|
121 |
+
return p
|
122 |
+
elif isinstance(p, Add):
|
123 |
+
# separating into modulus and non modulus
|
124 |
+
both_l = non_mod_l, mod_l = [], []
|
125 |
+
for arg in p.args:
|
126 |
+
both_l[isinstance(arg, cls)].append(arg)
|
127 |
+
# if q same for all
|
128 |
+
if mod_l and all(inner.args[1] == q for inner in mod_l):
|
129 |
+
net = Add(*non_mod_l) + Add(*[i.args[0] for i in mod_l])
|
130 |
+
return cls(net, q)
|
131 |
+
|
132 |
+
elif isinstance(p, Mul):
|
133 |
+
# separating into modulus and non modulus
|
134 |
+
both_l = non_mod_l, mod_l = [], []
|
135 |
+
for arg in p.args:
|
136 |
+
both_l[isinstance(arg, cls)].append(arg)
|
137 |
+
|
138 |
+
if mod_l and all(inner.args[1] == q for inner in mod_l) and all(t.is_integer for t in p.args) and q.is_integer:
|
139 |
+
# finding distributive term
|
140 |
+
non_mod_l = [cls(x, q) for x in non_mod_l]
|
141 |
+
mod = []
|
142 |
+
non_mod = []
|
143 |
+
for j in non_mod_l:
|
144 |
+
if isinstance(j, cls):
|
145 |
+
mod.append(j.args[0])
|
146 |
+
else:
|
147 |
+
non_mod.append(j)
|
148 |
+
prod_mod = Mul(*mod)
|
149 |
+
prod_non_mod = Mul(*non_mod)
|
150 |
+
prod_mod1 = Mul(*[i.args[0] for i in mod_l])
|
151 |
+
net = prod_mod1*prod_mod
|
152 |
+
return prod_non_mod*cls(net, q)
|
153 |
+
|
154 |
+
if q.is_Integer and q is not S.One:
|
155 |
+
non_mod_l = [i % q if i.is_Integer and (i % q is not S.Zero) else i for
|
156 |
+
i in non_mod_l]
|
157 |
+
|
158 |
+
p = Mul(*(non_mod_l + mod_l))
|
159 |
+
|
160 |
+
# XXX other possibilities?
|
161 |
+
|
162 |
+
from sympy.polys.polyerrors import PolynomialError
|
163 |
+
from sympy.polys.polytools import gcd
|
164 |
+
|
165 |
+
# extract gcd; any further simplification should be done by the user
|
166 |
+
try:
|
167 |
+
G = gcd(p, q)
|
168 |
+
if not equal_valued(G, 1):
|
169 |
+
p, q = [gcd_terms(i/G, clear=False, fraction=False)
|
170 |
+
for i in (p, q)]
|
171 |
+
except PolynomialError: # issue 21373
|
172 |
+
G = S.One
|
173 |
+
pwas, qwas = p, q
|
174 |
+
|
175 |
+
# simplify terms
|
176 |
+
# (x + y + 2) % x -> Mod(y + 2, x)
|
177 |
+
if p.is_Add:
|
178 |
+
args = []
|
179 |
+
for i in p.args:
|
180 |
+
a = cls(i, q)
|
181 |
+
if a.count(cls) > i.count(cls):
|
182 |
+
args.append(i)
|
183 |
+
else:
|
184 |
+
args.append(a)
|
185 |
+
if args != list(p.args):
|
186 |
+
p = Add(*args)
|
187 |
+
|
188 |
+
else:
|
189 |
+
# handle coefficients if they are not Rational
|
190 |
+
# since those are not handled by factor_terms
|
191 |
+
# e.g. Mod(.6*x, .3*y) -> 0.3*Mod(2*x, y)
|
192 |
+
cp, p = p.as_coeff_Mul()
|
193 |
+
cq, q = q.as_coeff_Mul()
|
194 |
+
ok = False
|
195 |
+
if not cp.is_Rational or not cq.is_Rational:
|
196 |
+
r = cp % cq
|
197 |
+
if equal_valued(r, 0):
|
198 |
+
G *= cq
|
199 |
+
p *= int(cp/cq)
|
200 |
+
ok = True
|
201 |
+
if not ok:
|
202 |
+
p = cp*p
|
203 |
+
q = cq*q
|
204 |
+
|
205 |
+
# simple -1 extraction
|
206 |
+
if p.could_extract_minus_sign() and q.could_extract_minus_sign():
|
207 |
+
G, p, q = [-i for i in (G, p, q)]
|
208 |
+
|
209 |
+
# check again to see if p and q can now be handled as numbers
|
210 |
+
rv = number_eval(p, q)
|
211 |
+
if rv is not None:
|
212 |
+
return rv*G
|
213 |
+
|
214 |
+
# put 1.0 from G on inside
|
215 |
+
if G.is_Float and equal_valued(G, 1):
|
216 |
+
p *= G
|
217 |
+
return cls(p, q, evaluate=False)
|
218 |
+
elif G.is_Mul and G.args[0].is_Float and equal_valued(G.args[0], 1):
|
219 |
+
p = G.args[0]*p
|
220 |
+
G = Mul._from_args(G.args[1:])
|
221 |
+
return G*cls(p, q, evaluate=(p, q) != (pwas, qwas))
|
222 |
+
|
223 |
+
def _eval_is_integer(self):
|
224 |
+
p, q = self.args
|
225 |
+
if fuzzy_and([p.is_integer, q.is_integer, fuzzy_not(q.is_zero)]):
|
226 |
+
return True
|
227 |
+
|
228 |
+
def _eval_is_nonnegative(self):
|
229 |
+
if self.args[1].is_positive:
|
230 |
+
return True
|
231 |
+
|
232 |
+
def _eval_is_nonpositive(self):
|
233 |
+
if self.args[1].is_negative:
|
234 |
+
return True
|
235 |
+
|
236 |
+
def _eval_rewrite_as_floor(self, a, b, **kwargs):
|
237 |
+
from sympy.functions.elementary.integers import floor
|
238 |
+
return a - b*floor(a/b)
|
llmeval-env/lib/python3.10/site-packages/sympy/core/multidimensional.py
ADDED
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Provides functionality for multidimensional usage of scalar-functions.
|
3 |
+
|
4 |
+
Read the vectorize docstring for more details.
|
5 |
+
"""
|
6 |
+
|
7 |
+
from functools import wraps
|
8 |
+
|
9 |
+
|
10 |
+
def apply_on_element(f, args, kwargs, n):
|
11 |
+
"""
|
12 |
+
Returns a structure with the same dimension as the specified argument,
|
13 |
+
where each basic element is replaced by the function f applied on it. All
|
14 |
+
other arguments stay the same.
|
15 |
+
"""
|
16 |
+
# Get the specified argument.
|
17 |
+
if isinstance(n, int):
|
18 |
+
structure = args[n]
|
19 |
+
is_arg = True
|
20 |
+
elif isinstance(n, str):
|
21 |
+
structure = kwargs[n]
|
22 |
+
is_arg = False
|
23 |
+
|
24 |
+
# Define reduced function that is only dependent on the specified argument.
|
25 |
+
def f_reduced(x):
|
26 |
+
if hasattr(x, "__iter__"):
|
27 |
+
return list(map(f_reduced, x))
|
28 |
+
else:
|
29 |
+
if is_arg:
|
30 |
+
args[n] = x
|
31 |
+
else:
|
32 |
+
kwargs[n] = x
|
33 |
+
return f(*args, **kwargs)
|
34 |
+
|
35 |
+
# f_reduced will call itself recursively so that in the end f is applied to
|
36 |
+
# all basic elements.
|
37 |
+
return list(map(f_reduced, structure))
|
38 |
+
|
39 |
+
|
40 |
+
def iter_copy(structure):
|
41 |
+
"""
|
42 |
+
Returns a copy of an iterable object (also copying all embedded iterables).
|
43 |
+
"""
|
44 |
+
return [iter_copy(i) if hasattr(i, "__iter__") else i for i in structure]
|
45 |
+
|
46 |
+
|
47 |
+
def structure_copy(structure):
|
48 |
+
"""
|
49 |
+
Returns a copy of the given structure (numpy-array, list, iterable, ..).
|
50 |
+
"""
|
51 |
+
if hasattr(structure, "copy"):
|
52 |
+
return structure.copy()
|
53 |
+
return iter_copy(structure)
|
54 |
+
|
55 |
+
|
56 |
+
class vectorize:
|
57 |
+
"""
|
58 |
+
Generalizes a function taking scalars to accept multidimensional arguments.
|
59 |
+
|
60 |
+
Examples
|
61 |
+
========
|
62 |
+
|
63 |
+
>>> from sympy import vectorize, diff, sin, symbols, Function
|
64 |
+
>>> x, y, z = symbols('x y z')
|
65 |
+
>>> f, g, h = list(map(Function, 'fgh'))
|
66 |
+
|
67 |
+
>>> @vectorize(0)
|
68 |
+
... def vsin(x):
|
69 |
+
... return sin(x)
|
70 |
+
|
71 |
+
>>> vsin([1, x, y])
|
72 |
+
[sin(1), sin(x), sin(y)]
|
73 |
+
|
74 |
+
>>> @vectorize(0, 1)
|
75 |
+
... def vdiff(f, y):
|
76 |
+
... return diff(f, y)
|
77 |
+
|
78 |
+
>>> vdiff([f(x, y, z), g(x, y, z), h(x, y, z)], [x, y, z])
|
79 |
+
[[Derivative(f(x, y, z), x), Derivative(f(x, y, z), y), Derivative(f(x, y, z), z)], [Derivative(g(x, y, z), x), Derivative(g(x, y, z), y), Derivative(g(x, y, z), z)], [Derivative(h(x, y, z), x), Derivative(h(x, y, z), y), Derivative(h(x, y, z), z)]]
|
80 |
+
"""
|
81 |
+
def __init__(self, *mdargs):
|
82 |
+
"""
|
83 |
+
The given numbers and strings characterize the arguments that will be
|
84 |
+
treated as data structures, where the decorated function will be applied
|
85 |
+
to every single element.
|
86 |
+
If no argument is given, everything is treated multidimensional.
|
87 |
+
"""
|
88 |
+
for a in mdargs:
|
89 |
+
if not isinstance(a, (int, str)):
|
90 |
+
raise TypeError("a is of invalid type")
|
91 |
+
self.mdargs = mdargs
|
92 |
+
|
93 |
+
def __call__(self, f):
|
94 |
+
"""
|
95 |
+
Returns a wrapper for the one-dimensional function that can handle
|
96 |
+
multidimensional arguments.
|
97 |
+
"""
|
98 |
+
@wraps(f)
|
99 |
+
def wrapper(*args, **kwargs):
|
100 |
+
# Get arguments that should be treated multidimensional
|
101 |
+
if self.mdargs:
|
102 |
+
mdargs = self.mdargs
|
103 |
+
else:
|
104 |
+
mdargs = range(len(args)) + kwargs.keys()
|
105 |
+
|
106 |
+
arglength = len(args)
|
107 |
+
|
108 |
+
for n in mdargs:
|
109 |
+
if isinstance(n, int):
|
110 |
+
if n >= arglength:
|
111 |
+
continue
|
112 |
+
entry = args[n]
|
113 |
+
is_arg = True
|
114 |
+
elif isinstance(n, str):
|
115 |
+
try:
|
116 |
+
entry = kwargs[n]
|
117 |
+
except KeyError:
|
118 |
+
continue
|
119 |
+
is_arg = False
|
120 |
+
if hasattr(entry, "__iter__"):
|
121 |
+
# Create now a copy of the given array and manipulate then
|
122 |
+
# the entries directly.
|
123 |
+
if is_arg:
|
124 |
+
args = list(args)
|
125 |
+
args[n] = structure_copy(entry)
|
126 |
+
else:
|
127 |
+
kwargs[n] = structure_copy(entry)
|
128 |
+
result = apply_on_element(wrapper, args, kwargs, n)
|
129 |
+
return result
|
130 |
+
return f(*args, **kwargs)
|
131 |
+
return wrapper
|
llmeval-env/lib/python3.10/site-packages/sympy/core/numbers.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
llmeval-env/lib/python3.10/site-packages/sympy/core/operations.py
ADDED
@@ -0,0 +1,722 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
llmeval-env/lib/python3.10/site-packages/sympy/core/power.py
ADDED
@@ -0,0 +1,2004 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
from typing import Callable
|
3 |
+
from math import log as _log, sqrt as _sqrt
|
4 |
+
from itertools import product
|
5 |
+
|
6 |
+
from .sympify import _sympify
|
7 |
+
from .cache import cacheit
|
8 |
+
from .singleton import S
|
9 |
+
from .expr import Expr
|
10 |
+
from .evalf import PrecisionExhausted
|
11 |
+
from .function import (expand_complex, expand_multinomial,
|
12 |
+
expand_mul, _mexpand, PoleError)
|
13 |
+
from .logic import fuzzy_bool, fuzzy_not, fuzzy_and, fuzzy_or
|
14 |
+
from .parameters import global_parameters
|
15 |
+
from .relational import is_gt, is_lt
|
16 |
+
from .kind import NumberKind, UndefinedKind
|
17 |
+
from sympy.external.gmpy import HAS_GMPY, gmpy
|
18 |
+
from sympy.utilities.iterables import sift
|
19 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
20 |
+
from sympy.utilities.misc import as_int
|
21 |
+
from sympy.multipledispatch import Dispatcher
|
22 |
+
|
23 |
+
from mpmath.libmp import sqrtrem as mpmath_sqrtrem
|
24 |
+
|
25 |
+
|
26 |
+
|
27 |
+
def isqrt(n):
|
28 |
+
"""Return the largest integer less than or equal to sqrt(n)."""
|
29 |
+
if n < 0:
|
30 |
+
raise ValueError("n must be nonnegative")
|
31 |
+
n = int(n)
|
32 |
+
|
33 |
+
# Fast path: with IEEE 754 binary64 floats and a correctly-rounded
|
34 |
+
# math.sqrt, int(math.sqrt(n)) works for any integer n satisfying 0 <= n <
|
35 |
+
# 4503599761588224 = 2**52 + 2**27. But Python doesn't guarantee either
|
36 |
+
# IEEE 754 format floats *or* correct rounding of math.sqrt, so check the
|
37 |
+
# answer and fall back to the slow method if necessary.
|
38 |
+
if n < 4503599761588224:
|
39 |
+
s = int(_sqrt(n))
|
40 |
+
if 0 <= n - s*s <= 2*s:
|
41 |
+
return s
|
42 |
+
|
43 |
+
return integer_nthroot(n, 2)[0]
|
44 |
+
|
45 |
+
|
46 |
+
def integer_nthroot(y, n):
|
47 |
+
"""
|
48 |
+
Return a tuple containing x = floor(y**(1/n))
|
49 |
+
and a boolean indicating whether the result is exact (that is,
|
50 |
+
whether x**n == y).
|
51 |
+
|
52 |
+
Examples
|
53 |
+
========
|
54 |
+
|
55 |
+
>>> from sympy import integer_nthroot
|
56 |
+
>>> integer_nthroot(16, 2)
|
57 |
+
(4, True)
|
58 |
+
>>> integer_nthroot(26, 2)
|
59 |
+
(5, False)
|
60 |
+
|
61 |
+
To simply determine if a number is a perfect square, the is_square
|
62 |
+
function should be used:
|
63 |
+
|
64 |
+
>>> from sympy.ntheory.primetest import is_square
|
65 |
+
>>> is_square(26)
|
66 |
+
False
|
67 |
+
|
68 |
+
See Also
|
69 |
+
========
|
70 |
+
sympy.ntheory.primetest.is_square
|
71 |
+
integer_log
|
72 |
+
"""
|
73 |
+
y, n = as_int(y), as_int(n)
|
74 |
+
if y < 0:
|
75 |
+
raise ValueError("y must be nonnegative")
|
76 |
+
if n < 1:
|
77 |
+
raise ValueError("n must be positive")
|
78 |
+
if HAS_GMPY and n < 2**63:
|
79 |
+
# Currently it works only for n < 2**63, else it produces TypeError
|
80 |
+
# sympy issue: https://github.com/sympy/sympy/issues/18374
|
81 |
+
# gmpy2 issue: https://github.com/aleaxit/gmpy/issues/257
|
82 |
+
if HAS_GMPY >= 2:
|
83 |
+
x, t = gmpy.iroot(y, n)
|
84 |
+
else:
|
85 |
+
x, t = gmpy.root(y, n)
|
86 |
+
return as_int(x), bool(t)
|
87 |
+
return _integer_nthroot_python(y, n)
|
88 |
+
|
89 |
+
def _integer_nthroot_python(y, n):
|
90 |
+
if y in (0, 1):
|
91 |
+
return y, True
|
92 |
+
if n == 1:
|
93 |
+
return y, True
|
94 |
+
if n == 2:
|
95 |
+
x, rem = mpmath_sqrtrem(y)
|
96 |
+
return int(x), not rem
|
97 |
+
if n >= y.bit_length():
|
98 |
+
return 1, False
|
99 |
+
# Get initial estimate for Newton's method. Care must be taken to
|
100 |
+
# avoid overflow
|
101 |
+
try:
|
102 |
+
guess = int(y**(1./n) + 0.5)
|
103 |
+
except OverflowError:
|
104 |
+
exp = _log(y, 2)/n
|
105 |
+
if exp > 53:
|
106 |
+
shift = int(exp - 53)
|
107 |
+
guess = int(2.0**(exp - shift) + 1) << shift
|
108 |
+
else:
|
109 |
+
guess = int(2.0**exp)
|
110 |
+
if guess > 2**50:
|
111 |
+
# Newton iteration
|
112 |
+
xprev, x = -1, guess
|
113 |
+
while 1:
|
114 |
+
t = x**(n - 1)
|
115 |
+
xprev, x = x, ((n - 1)*x + y//t)//n
|
116 |
+
if abs(x - xprev) < 2:
|
117 |
+
break
|
118 |
+
else:
|
119 |
+
x = guess
|
120 |
+
# Compensate
|
121 |
+
t = x**n
|
122 |
+
while t < y:
|
123 |
+
x += 1
|
124 |
+
t = x**n
|
125 |
+
while t > y:
|
126 |
+
x -= 1
|
127 |
+
t = x**n
|
128 |
+
return int(x), t == y # int converts long to int if possible
|
129 |
+
|
130 |
+
|
131 |
+
def integer_log(y, x):
|
132 |
+
r"""
|
133 |
+
Returns ``(e, bool)`` where e is the largest nonnegative integer
|
134 |
+
such that :math:`|y| \geq |x^e|` and ``bool`` is True if $y = x^e$.
|
135 |
+
|
136 |
+
Examples
|
137 |
+
========
|
138 |
+
|
139 |
+
>>> from sympy import integer_log
|
140 |
+
>>> integer_log(125, 5)
|
141 |
+
(3, True)
|
142 |
+
>>> integer_log(17, 9)
|
143 |
+
(1, False)
|
144 |
+
>>> integer_log(4, -2)
|
145 |
+
(2, True)
|
146 |
+
>>> integer_log(-125,-5)
|
147 |
+
(3, True)
|
148 |
+
|
149 |
+
See Also
|
150 |
+
========
|
151 |
+
integer_nthroot
|
152 |
+
sympy.ntheory.primetest.is_square
|
153 |
+
sympy.ntheory.factor_.multiplicity
|
154 |
+
sympy.ntheory.factor_.perfect_power
|
155 |
+
"""
|
156 |
+
if x == 1:
|
157 |
+
raise ValueError('x cannot take value as 1')
|
158 |
+
if y == 0:
|
159 |
+
raise ValueError('y cannot take value as 0')
|
160 |
+
|
161 |
+
if x in (-2, 2):
|
162 |
+
x = int(x)
|
163 |
+
y = as_int(y)
|
164 |
+
e = y.bit_length() - 1
|
165 |
+
return e, x**e == y
|
166 |
+
if x < 0:
|
167 |
+
n, b = integer_log(y if y > 0 else -y, -x)
|
168 |
+
return n, b and bool(n % 2 if y < 0 else not n % 2)
|
169 |
+
|
170 |
+
x = as_int(x)
|
171 |
+
y = as_int(y)
|
172 |
+
r = e = 0
|
173 |
+
while y >= x:
|
174 |
+
d = x
|
175 |
+
m = 1
|
176 |
+
while y >= d:
|
177 |
+
y, rem = divmod(y, d)
|
178 |
+
r = r or rem
|
179 |
+
e += m
|
180 |
+
if y > d:
|
181 |
+
d *= d
|
182 |
+
m *= 2
|
183 |
+
return e, r == 0 and y == 1
|
184 |
+
|
185 |
+
|
186 |
+
class Pow(Expr):
|
187 |
+
"""
|
188 |
+
Defines the expression x**y as "x raised to a power y"
|
189 |
+
|
190 |
+
.. deprecated:: 1.7
|
191 |
+
|
192 |
+
Using arguments that aren't subclasses of :class:`~.Expr` in core
|
193 |
+
operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
|
194 |
+
deprecated. See :ref:`non-expr-args-deprecated` for details.
|
195 |
+
|
196 |
+
Singleton definitions involving (0, 1, -1, oo, -oo, I, -I):
|
197 |
+
|
198 |
+
+--------------+---------+-----------------------------------------------+
|
199 |
+
| expr | value | reason |
|
200 |
+
+==============+=========+===============================================+
|
201 |
+
| z**0 | 1 | Although arguments over 0**0 exist, see [2]. |
|
202 |
+
+--------------+---------+-----------------------------------------------+
|
203 |
+
| z**1 | z | |
|
204 |
+
+--------------+---------+-----------------------------------------------+
|
205 |
+
| (-oo)**(-1) | 0 | |
|
206 |
+
+--------------+---------+-----------------------------------------------+
|
207 |
+
| (-1)**-1 | -1 | |
|
208 |
+
+--------------+---------+-----------------------------------------------+
|
209 |
+
| S.Zero**-1 | zoo | This is not strictly true, as 0**-1 may be |
|
210 |
+
| | | undefined, but is convenient in some contexts |
|
211 |
+
| | | where the base is assumed to be positive. |
|
212 |
+
+--------------+---------+-----------------------------------------------+
|
213 |
+
| 1**-1 | 1 | |
|
214 |
+
+--------------+---------+-----------------------------------------------+
|
215 |
+
| oo**-1 | 0 | |
|
216 |
+
+--------------+---------+-----------------------------------------------+
|
217 |
+
| 0**oo | 0 | Because for all complex numbers z near |
|
218 |
+
| | | 0, z**oo -> 0. |
|
219 |
+
+--------------+---------+-----------------------------------------------+
|
220 |
+
| 0**-oo | zoo | This is not strictly true, as 0**oo may be |
|
221 |
+
| | | oscillating between positive and negative |
|
222 |
+
| | | values or rotating in the complex plane. |
|
223 |
+
| | | It is convenient, however, when the base |
|
224 |
+
| | | is positive. |
|
225 |
+
+--------------+---------+-----------------------------------------------+
|
226 |
+
| 1**oo | nan | Because there are various cases where |
|
227 |
+
| 1**-oo | | lim(x(t),t)=1, lim(y(t),t)=oo (or -oo), |
|
228 |
+
| | | but lim( x(t)**y(t), t) != 1. See [3]. |
|
229 |
+
+--------------+---------+-----------------------------------------------+
|
230 |
+
| b**zoo | nan | Because b**z has no limit as z -> zoo |
|
231 |
+
+--------------+---------+-----------------------------------------------+
|
232 |
+
| (-1)**oo | nan | Because of oscillations in the limit. |
|
233 |
+
| (-1)**(-oo) | | |
|
234 |
+
+--------------+---------+-----------------------------------------------+
|
235 |
+
| oo**oo | oo | |
|
236 |
+
+--------------+---------+-----------------------------------------------+
|
237 |
+
| oo**-oo | 0 | |
|
238 |
+
+--------------+---------+-----------------------------------------------+
|
239 |
+
| (-oo)**oo | nan | |
|
240 |
+
| (-oo)**-oo | | |
|
241 |
+
+--------------+---------+-----------------------------------------------+
|
242 |
+
| oo**I | nan | oo**e could probably be best thought of as |
|
243 |
+
| (-oo)**I | | the limit of x**e for real x as x tends to |
|
244 |
+
| | | oo. If e is I, then the limit does not exist |
|
245 |
+
| | | and nan is used to indicate that. |
|
246 |
+
+--------------+---------+-----------------------------------------------+
|
247 |
+
| oo**(1+I) | zoo | If the real part of e is positive, then the |
|
248 |
+
| (-oo)**(1+I) | | limit of abs(x**e) is oo. So the limit value |
|
249 |
+
| | | is zoo. |
|
250 |
+
+--------------+---------+-----------------------------------------------+
|
251 |
+
| oo**(-1+I) | 0 | If the real part of e is negative, then the |
|
252 |
+
| -oo**(-1+I) | | limit is 0. |
|
253 |
+
+--------------+---------+-----------------------------------------------+
|
254 |
+
|
255 |
+
Because symbolic computations are more flexible than floating point
|
256 |
+
calculations and we prefer to never return an incorrect answer,
|
257 |
+
we choose not to conform to all IEEE 754 conventions. This helps
|
258 |
+
us avoid extra test-case code in the calculation of limits.
|
259 |
+
|
260 |
+
See Also
|
261 |
+
========
|
262 |
+
|
263 |
+
sympy.core.numbers.Infinity
|
264 |
+
sympy.core.numbers.NegativeInfinity
|
265 |
+
sympy.core.numbers.NaN
|
266 |
+
|
267 |
+
References
|
268 |
+
==========
|
269 |
+
|
270 |
+
.. [1] https://en.wikipedia.org/wiki/Exponentiation
|
271 |
+
.. [2] https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero
|
272 |
+
.. [3] https://en.wikipedia.org/wiki/Indeterminate_forms
|
273 |
+
|
274 |
+
"""
|
275 |
+
is_Pow = True
|
276 |
+
|
277 |
+
__slots__ = ('is_commutative',)
|
278 |
+
|
279 |
+
args: tuple[Expr, Expr]
|
280 |
+
_args: tuple[Expr, Expr]
|
281 |
+
|
282 |
+
@cacheit
|
283 |
+
def __new__(cls, b, e, evaluate=None):
|
284 |
+
if evaluate is None:
|
285 |
+
evaluate = global_parameters.evaluate
|
286 |
+
|
287 |
+
b = _sympify(b)
|
288 |
+
e = _sympify(e)
|
289 |
+
|
290 |
+
# XXX: This can be removed when non-Expr args are disallowed rather
|
291 |
+
# than deprecated.
|
292 |
+
from .relational import Relational
|
293 |
+
if isinstance(b, Relational) or isinstance(e, Relational):
|
294 |
+
raise TypeError('Relational cannot be used in Pow')
|
295 |
+
|
296 |
+
# XXX: This should raise TypeError once deprecation period is over:
|
297 |
+
for arg in [b, e]:
|
298 |
+
if not isinstance(arg, Expr):
|
299 |
+
sympy_deprecation_warning(
|
300 |
+
f"""
|
301 |
+
Using non-Expr arguments in Pow is deprecated (in this case, one of the
|
302 |
+
arguments is of type {type(arg).__name__!r}).
|
303 |
+
|
304 |
+
If you really did intend to construct a power with this base, use the **
|
305 |
+
operator instead.""",
|
306 |
+
deprecated_since_version="1.7",
|
307 |
+
active_deprecations_target="non-expr-args-deprecated",
|
308 |
+
stacklevel=4,
|
309 |
+
)
|
310 |
+
|
311 |
+
if evaluate:
|
312 |
+
if e is S.ComplexInfinity:
|
313 |
+
return S.NaN
|
314 |
+
if e is S.Infinity:
|
315 |
+
if is_gt(b, S.One):
|
316 |
+
return S.Infinity
|
317 |
+
if is_gt(b, S.NegativeOne) and is_lt(b, S.One):
|
318 |
+
return S.Zero
|
319 |
+
if is_lt(b, S.NegativeOne):
|
320 |
+
if b.is_finite:
|
321 |
+
return S.ComplexInfinity
|
322 |
+
if b.is_finite is False:
|
323 |
+
return S.NaN
|
324 |
+
if e is S.Zero:
|
325 |
+
return S.One
|
326 |
+
elif e is S.One:
|
327 |
+
return b
|
328 |
+
elif e == -1 and not b:
|
329 |
+
return S.ComplexInfinity
|
330 |
+
elif e.__class__.__name__ == "AccumulationBounds":
|
331 |
+
if b == S.Exp1:
|
332 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
333 |
+
return AccumBounds(Pow(b, e.min), Pow(b, e.max))
|
334 |
+
# autosimplification if base is a number and exp odd/even
|
335 |
+
# if base is Number then the base will end up positive; we
|
336 |
+
# do not do this with arbitrary expressions since symbolic
|
337 |
+
# cancellation might occur as in (x - 1)/(1 - x) -> -1. If
|
338 |
+
# we returned Piecewise((-1, Ne(x, 1))) for such cases then
|
339 |
+
# we could do this...but we don't
|
340 |
+
elif (e.is_Symbol and e.is_integer or e.is_Integer
|
341 |
+
) and (b.is_number and b.is_Mul or b.is_Number
|
342 |
+
) and b.could_extract_minus_sign():
|
343 |
+
if e.is_even:
|
344 |
+
b = -b
|
345 |
+
elif e.is_odd:
|
346 |
+
return -Pow(-b, e)
|
347 |
+
if S.NaN in (b, e): # XXX S.NaN**x -> S.NaN under assumption that x != 0
|
348 |
+
return S.NaN
|
349 |
+
elif b is S.One:
|
350 |
+
if abs(e).is_infinite:
|
351 |
+
return S.NaN
|
352 |
+
return S.One
|
353 |
+
else:
|
354 |
+
# recognize base as E
|
355 |
+
from sympy.functions.elementary.exponential import exp_polar
|
356 |
+
if not e.is_Atom and b is not S.Exp1 and not isinstance(b, exp_polar):
|
357 |
+
from .exprtools import factor_terms
|
358 |
+
from sympy.functions.elementary.exponential import log
|
359 |
+
from sympy.simplify.radsimp import fraction
|
360 |
+
c, ex = factor_terms(e, sign=False).as_coeff_Mul()
|
361 |
+
num, den = fraction(ex)
|
362 |
+
if isinstance(den, log) and den.args[0] == b:
|
363 |
+
return S.Exp1**(c*num)
|
364 |
+
elif den.is_Add:
|
365 |
+
from sympy.functions.elementary.complexes import sign, im
|
366 |
+
s = sign(im(b))
|
367 |
+
if s.is_Number and s and den == \
|
368 |
+
log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi:
|
369 |
+
return S.Exp1**(c*num)
|
370 |
+
|
371 |
+
obj = b._eval_power(e)
|
372 |
+
if obj is not None:
|
373 |
+
return obj
|
374 |
+
obj = Expr.__new__(cls, b, e)
|
375 |
+
obj = cls._exec_constructor_postprocessors(obj)
|
376 |
+
if not isinstance(obj, Pow):
|
377 |
+
return obj
|
378 |
+
obj.is_commutative = (b.is_commutative and e.is_commutative)
|
379 |
+
return obj
|
380 |
+
|
381 |
+
def inverse(self, argindex=1):
|
382 |
+
if self.base == S.Exp1:
|
383 |
+
from sympy.functions.elementary.exponential import log
|
384 |
+
return log
|
385 |
+
return None
|
386 |
+
|
387 |
+
@property
|
388 |
+
def base(self) -> Expr:
|
389 |
+
return self._args[0]
|
390 |
+
|
391 |
+
@property
|
392 |
+
def exp(self) -> Expr:
|
393 |
+
return self._args[1]
|
394 |
+
|
395 |
+
@property
|
396 |
+
def kind(self):
|
397 |
+
if self.exp.kind is NumberKind:
|
398 |
+
return self.base.kind
|
399 |
+
else:
|
400 |
+
return UndefinedKind
|
401 |
+
|
402 |
+
@classmethod
|
403 |
+
def class_key(cls):
|
404 |
+
return 3, 2, cls.__name__
|
405 |
+
|
406 |
+
def _eval_refine(self, assumptions):
|
407 |
+
from sympy.assumptions.ask import ask, Q
|
408 |
+
b, e = self.as_base_exp()
|
409 |
+
if ask(Q.integer(e), assumptions) and b.could_extract_minus_sign():
|
410 |
+
if ask(Q.even(e), assumptions):
|
411 |
+
return Pow(-b, e)
|
412 |
+
elif ask(Q.odd(e), assumptions):
|
413 |
+
return -Pow(-b, e)
|
414 |
+
|
415 |
+
def _eval_power(self, other):
|
416 |
+
b, e = self.as_base_exp()
|
417 |
+
if b is S.NaN:
|
418 |
+
return (b**e)**other # let __new__ handle it
|
419 |
+
|
420 |
+
s = None
|
421 |
+
if other.is_integer:
|
422 |
+
s = 1
|
423 |
+
elif b.is_polar: # e.g. exp_polar, besselj, var('p', polar=True)...
|
424 |
+
s = 1
|
425 |
+
elif e.is_extended_real is not None:
|
426 |
+
from sympy.functions.elementary.complexes import arg, im, re, sign
|
427 |
+
from sympy.functions.elementary.exponential import exp, log
|
428 |
+
from sympy.functions.elementary.integers import floor
|
429 |
+
# helper functions ===========================
|
430 |
+
def _half(e):
|
431 |
+
"""Return True if the exponent has a literal 2 as the
|
432 |
+
denominator, else None."""
|
433 |
+
if getattr(e, 'q', None) == 2:
|
434 |
+
return True
|
435 |
+
n, d = e.as_numer_denom()
|
436 |
+
if n.is_integer and d == 2:
|
437 |
+
return True
|
438 |
+
def _n2(e):
|
439 |
+
"""Return ``e`` evaluated to a Number with 2 significant
|
440 |
+
digits, else None."""
|
441 |
+
try:
|
442 |
+
rv = e.evalf(2, strict=True)
|
443 |
+
if rv.is_Number:
|
444 |
+
return rv
|
445 |
+
except PrecisionExhausted:
|
446 |
+
pass
|
447 |
+
# ===================================================
|
448 |
+
if e.is_extended_real:
|
449 |
+
# we need _half(other) with constant floor or
|
450 |
+
# floor(S.Half - e*arg(b)/2/pi) == 0
|
451 |
+
|
452 |
+
|
453 |
+
# handle -1 as special case
|
454 |
+
if e == -1:
|
455 |
+
# floor arg. is 1/2 + arg(b)/2/pi
|
456 |
+
if _half(other):
|
457 |
+
if b.is_negative is True:
|
458 |
+
return S.NegativeOne**other*Pow(-b, e*other)
|
459 |
+
elif b.is_negative is False: # XXX ok if im(b) != 0?
|
460 |
+
return Pow(b, -other)
|
461 |
+
elif e.is_even:
|
462 |
+
if b.is_extended_real:
|
463 |
+
b = abs(b)
|
464 |
+
if b.is_imaginary:
|
465 |
+
b = abs(im(b))*S.ImaginaryUnit
|
466 |
+
|
467 |
+
if (abs(e) < 1) == True or e == 1:
|
468 |
+
s = 1 # floor = 0
|
469 |
+
elif b.is_extended_nonnegative:
|
470 |
+
s = 1 # floor = 0
|
471 |
+
elif re(b).is_extended_nonnegative and (abs(e) < 2) == True:
|
472 |
+
s = 1 # floor = 0
|
473 |
+
elif _half(other):
|
474 |
+
s = exp(2*S.Pi*S.ImaginaryUnit*other*floor(
|
475 |
+
S.Half - e*arg(b)/(2*S.Pi)))
|
476 |
+
if s.is_extended_real and _n2(sign(s) - s) == 0:
|
477 |
+
s = sign(s)
|
478 |
+
else:
|
479 |
+
s = None
|
480 |
+
else:
|
481 |
+
# e.is_extended_real is False requires:
|
482 |
+
# _half(other) with constant floor or
|
483 |
+
# floor(S.Half - im(e*log(b))/2/pi) == 0
|
484 |
+
try:
|
485 |
+
s = exp(2*S.ImaginaryUnit*S.Pi*other*
|
486 |
+
floor(S.Half - im(e*log(b))/2/S.Pi))
|
487 |
+
# be careful to test that s is -1 or 1 b/c sign(I) == I:
|
488 |
+
# so check that s is real
|
489 |
+
if s.is_extended_real and _n2(sign(s) - s) == 0:
|
490 |
+
s = sign(s)
|
491 |
+
else:
|
492 |
+
s = None
|
493 |
+
except PrecisionExhausted:
|
494 |
+
s = None
|
495 |
+
|
496 |
+
if s is not None:
|
497 |
+
return s*Pow(b, e*other)
|
498 |
+
|
499 |
+
def _eval_Mod(self, q):
|
500 |
+
r"""A dispatched function to compute `b^e \bmod q`, dispatched
|
501 |
+
by ``Mod``.
|
502 |
+
|
503 |
+
Notes
|
504 |
+
=====
|
505 |
+
|
506 |
+
Algorithms:
|
507 |
+
|
508 |
+
1. For unevaluated integer power, use built-in ``pow`` function
|
509 |
+
with 3 arguments, if powers are not too large wrt base.
|
510 |
+
|
511 |
+
2. For very large powers, use totient reduction if $e \ge \log(m)$.
|
512 |
+
Bound on m, is for safe factorization memory wise i.e. $m^{1/4}$.
|
513 |
+
For pollard-rho to be faster than built-in pow $\log(e) > m^{1/4}$
|
514 |
+
check is added.
|
515 |
+
|
516 |
+
3. For any unevaluated power found in `b` or `e`, the step 2
|
517 |
+
will be recursed down to the base and the exponent
|
518 |
+
such that the $b \bmod q$ becomes the new base and
|
519 |
+
$\phi(q) + e \bmod \phi(q)$ becomes the new exponent, and then
|
520 |
+
the computation for the reduced expression can be done.
|
521 |
+
"""
|
522 |
+
|
523 |
+
base, exp = self.base, self.exp
|
524 |
+
|
525 |
+
if exp.is_integer and exp.is_positive:
|
526 |
+
if q.is_integer and base % q == 0:
|
527 |
+
return S.Zero
|
528 |
+
|
529 |
+
from sympy.ntheory.factor_ import totient
|
530 |
+
|
531 |
+
if base.is_Integer and exp.is_Integer and q.is_Integer:
|
532 |
+
b, e, m = int(base), int(exp), int(q)
|
533 |
+
mb = m.bit_length()
|
534 |
+
if mb <= 80 and e >= mb and e.bit_length()**4 >= m:
|
535 |
+
phi = int(totient(m))
|
536 |
+
return Integer(pow(b, phi + e%phi, m))
|
537 |
+
return Integer(pow(b, e, m))
|
538 |
+
|
539 |
+
from .mod import Mod
|
540 |
+
|
541 |
+
if isinstance(base, Pow) and base.is_integer and base.is_number:
|
542 |
+
base = Mod(base, q)
|
543 |
+
return Mod(Pow(base, exp, evaluate=False), q)
|
544 |
+
|
545 |
+
if isinstance(exp, Pow) and exp.is_integer and exp.is_number:
|
546 |
+
bit_length = int(q).bit_length()
|
547 |
+
# XXX Mod-Pow actually attempts to do a hanging evaluation
|
548 |
+
# if this dispatched function returns None.
|
549 |
+
# May need some fixes in the dispatcher itself.
|
550 |
+
if bit_length <= 80:
|
551 |
+
phi = totient(q)
|
552 |
+
exp = phi + Mod(exp, phi)
|
553 |
+
return Mod(Pow(base, exp, evaluate=False), q)
|
554 |
+
|
555 |
+
def _eval_is_even(self):
|
556 |
+
if self.exp.is_integer and self.exp.is_positive:
|
557 |
+
return self.base.is_even
|
558 |
+
|
559 |
+
def _eval_is_negative(self):
|
560 |
+
ext_neg = Pow._eval_is_extended_negative(self)
|
561 |
+
if ext_neg is True:
|
562 |
+
return self.is_finite
|
563 |
+
return ext_neg
|
564 |
+
|
565 |
+
def _eval_is_extended_positive(self):
|
566 |
+
if self.base == self.exp:
|
567 |
+
if self.base.is_extended_nonnegative:
|
568 |
+
return True
|
569 |
+
elif self.base.is_positive:
|
570 |
+
if self.exp.is_real:
|
571 |
+
return True
|
572 |
+
elif self.base.is_extended_negative:
|
573 |
+
if self.exp.is_even:
|
574 |
+
return True
|
575 |
+
if self.exp.is_odd:
|
576 |
+
return False
|
577 |
+
elif self.base.is_zero:
|
578 |
+
if self.exp.is_extended_real:
|
579 |
+
return self.exp.is_zero
|
580 |
+
elif self.base.is_extended_nonpositive:
|
581 |
+
if self.exp.is_odd:
|
582 |
+
return False
|
583 |
+
elif self.base.is_imaginary:
|
584 |
+
if self.exp.is_integer:
|
585 |
+
m = self.exp % 4
|
586 |
+
if m.is_zero:
|
587 |
+
return True
|
588 |
+
if m.is_integer and m.is_zero is False:
|
589 |
+
return False
|
590 |
+
if self.exp.is_imaginary:
|
591 |
+
from sympy.functions.elementary.exponential import log
|
592 |
+
return log(self.base).is_imaginary
|
593 |
+
|
594 |
+
def _eval_is_extended_negative(self):
|
595 |
+
if self.exp is S.Half:
|
596 |
+
if self.base.is_complex or self.base.is_extended_real:
|
597 |
+
return False
|
598 |
+
if self.base.is_extended_negative:
|
599 |
+
if self.exp.is_odd and self.base.is_finite:
|
600 |
+
return True
|
601 |
+
if self.exp.is_even:
|
602 |
+
return False
|
603 |
+
elif self.base.is_extended_positive:
|
604 |
+
if self.exp.is_extended_real:
|
605 |
+
return False
|
606 |
+
elif self.base.is_zero:
|
607 |
+
if self.exp.is_extended_real:
|
608 |
+
return False
|
609 |
+
elif self.base.is_extended_nonnegative:
|
610 |
+
if self.exp.is_extended_nonnegative:
|
611 |
+
return False
|
612 |
+
elif self.base.is_extended_nonpositive:
|
613 |
+
if self.exp.is_even:
|
614 |
+
return False
|
615 |
+
elif self.base.is_extended_real:
|
616 |
+
if self.exp.is_even:
|
617 |
+
return False
|
618 |
+
|
619 |
+
def _eval_is_zero(self):
|
620 |
+
if self.base.is_zero:
|
621 |
+
if self.exp.is_extended_positive:
|
622 |
+
return True
|
623 |
+
elif self.exp.is_extended_nonpositive:
|
624 |
+
return False
|
625 |
+
elif self.base == S.Exp1:
|
626 |
+
return self.exp is S.NegativeInfinity
|
627 |
+
elif self.base.is_zero is False:
|
628 |
+
if self.base.is_finite and self.exp.is_finite:
|
629 |
+
return False
|
630 |
+
elif self.exp.is_negative:
|
631 |
+
return self.base.is_infinite
|
632 |
+
elif self.exp.is_nonnegative:
|
633 |
+
return False
|
634 |
+
elif self.exp.is_infinite and self.exp.is_extended_real:
|
635 |
+
if (1 - abs(self.base)).is_extended_positive:
|
636 |
+
return self.exp.is_extended_positive
|
637 |
+
elif (1 - abs(self.base)).is_extended_negative:
|
638 |
+
return self.exp.is_extended_negative
|
639 |
+
elif self.base.is_finite and self.exp.is_negative:
|
640 |
+
# when self.base.is_zero is None
|
641 |
+
return False
|
642 |
+
|
643 |
+
def _eval_is_integer(self):
|
644 |
+
b, e = self.args
|
645 |
+
if b.is_rational:
|
646 |
+
if b.is_integer is False and e.is_positive:
|
647 |
+
return False # rat**nonneg
|
648 |
+
if b.is_integer and e.is_integer:
|
649 |
+
if b is S.NegativeOne:
|
650 |
+
return True
|
651 |
+
if e.is_nonnegative or e.is_positive:
|
652 |
+
return True
|
653 |
+
if b.is_integer and e.is_negative and (e.is_finite or e.is_integer):
|
654 |
+
if fuzzy_not((b - 1).is_zero) and fuzzy_not((b + 1).is_zero):
|
655 |
+
return False
|
656 |
+
if b.is_Number and e.is_Number:
|
657 |
+
check = self.func(*self.args)
|
658 |
+
return check.is_Integer
|
659 |
+
if e.is_negative and b.is_positive and (b - 1).is_positive:
|
660 |
+
return False
|
661 |
+
if e.is_negative and b.is_negative and (b + 1).is_negative:
|
662 |
+
return False
|
663 |
+
|
664 |
+
def _eval_is_extended_real(self):
|
665 |
+
if self.base is S.Exp1:
|
666 |
+
if self.exp.is_extended_real:
|
667 |
+
return True
|
668 |
+
elif self.exp.is_imaginary:
|
669 |
+
return (2*S.ImaginaryUnit*self.exp/S.Pi).is_even
|
670 |
+
|
671 |
+
from sympy.functions.elementary.exponential import log, exp
|
672 |
+
real_b = self.base.is_extended_real
|
673 |
+
if real_b is None:
|
674 |
+
if self.base.func == exp and self.base.exp.is_imaginary:
|
675 |
+
return self.exp.is_imaginary
|
676 |
+
if self.base.func == Pow and self.base.base is S.Exp1 and self.base.exp.is_imaginary:
|
677 |
+
return self.exp.is_imaginary
|
678 |
+
return
|
679 |
+
real_e = self.exp.is_extended_real
|
680 |
+
if real_e is None:
|
681 |
+
return
|
682 |
+
if real_b and real_e:
|
683 |
+
if self.base.is_extended_positive:
|
684 |
+
return True
|
685 |
+
elif self.base.is_extended_nonnegative and self.exp.is_extended_nonnegative:
|
686 |
+
return True
|
687 |
+
elif self.exp.is_integer and self.base.is_extended_nonzero:
|
688 |
+
return True
|
689 |
+
elif self.exp.is_integer and self.exp.is_nonnegative:
|
690 |
+
return True
|
691 |
+
elif self.base.is_extended_negative:
|
692 |
+
if self.exp.is_Rational:
|
693 |
+
return False
|
694 |
+
if real_e and self.exp.is_extended_negative and self.base.is_zero is False:
|
695 |
+
return Pow(self.base, -self.exp).is_extended_real
|
696 |
+
im_b = self.base.is_imaginary
|
697 |
+
im_e = self.exp.is_imaginary
|
698 |
+
if im_b:
|
699 |
+
if self.exp.is_integer:
|
700 |
+
if self.exp.is_even:
|
701 |
+
return True
|
702 |
+
elif self.exp.is_odd:
|
703 |
+
return False
|
704 |
+
elif im_e and log(self.base).is_imaginary:
|
705 |
+
return True
|
706 |
+
elif self.exp.is_Add:
|
707 |
+
c, a = self.exp.as_coeff_Add()
|
708 |
+
if c and c.is_Integer:
|
709 |
+
return Mul(
|
710 |
+
self.base**c, self.base**a, evaluate=False).is_extended_real
|
711 |
+
elif self.base in (-S.ImaginaryUnit, S.ImaginaryUnit):
|
712 |
+
if (self.exp/2).is_integer is False:
|
713 |
+
return False
|
714 |
+
if real_b and im_e:
|
715 |
+
if self.base is S.NegativeOne:
|
716 |
+
return True
|
717 |
+
c = self.exp.coeff(S.ImaginaryUnit)
|
718 |
+
if c:
|
719 |
+
if self.base.is_rational and c.is_rational:
|
720 |
+
if self.base.is_nonzero and (self.base - 1).is_nonzero and c.is_nonzero:
|
721 |
+
return False
|
722 |
+
ok = (c*log(self.base)/S.Pi).is_integer
|
723 |
+
if ok is not None:
|
724 |
+
return ok
|
725 |
+
|
726 |
+
if real_b is False and real_e: # we already know it's not imag
|
727 |
+
from sympy.functions.elementary.complexes import arg
|
728 |
+
i = arg(self.base)*self.exp/S.Pi
|
729 |
+
if i.is_complex: # finite
|
730 |
+
return i.is_integer
|
731 |
+
|
732 |
+
def _eval_is_complex(self):
|
733 |
+
|
734 |
+
if self.base == S.Exp1:
|
735 |
+
return fuzzy_or([self.exp.is_complex, self.exp.is_extended_negative])
|
736 |
+
|
737 |
+
if all(a.is_complex for a in self.args) and self._eval_is_finite():
|
738 |
+
return True
|
739 |
+
|
740 |
+
def _eval_is_imaginary(self):
|
741 |
+
if self.base.is_commutative is False:
|
742 |
+
return False
|
743 |
+
|
744 |
+
if self.base.is_imaginary:
|
745 |
+
if self.exp.is_integer:
|
746 |
+
odd = self.exp.is_odd
|
747 |
+
if odd is not None:
|
748 |
+
return odd
|
749 |
+
return
|
750 |
+
|
751 |
+
if self.base == S.Exp1:
|
752 |
+
f = 2 * self.exp / (S.Pi*S.ImaginaryUnit)
|
753 |
+
# exp(pi*integer) = 1 or -1, so not imaginary
|
754 |
+
if f.is_even:
|
755 |
+
return False
|
756 |
+
# exp(pi*integer + pi/2) = I or -I, so it is imaginary
|
757 |
+
if f.is_odd:
|
758 |
+
return True
|
759 |
+
return None
|
760 |
+
|
761 |
+
if self.exp.is_imaginary:
|
762 |
+
from sympy.functions.elementary.exponential import log
|
763 |
+
imlog = log(self.base).is_imaginary
|
764 |
+
if imlog is not None:
|
765 |
+
return False # I**i -> real; (2*I)**i -> complex ==> not imaginary
|
766 |
+
|
767 |
+
if self.base.is_extended_real and self.exp.is_extended_real:
|
768 |
+
if self.base.is_positive:
|
769 |
+
return False
|
770 |
+
else:
|
771 |
+
rat = self.exp.is_rational
|
772 |
+
if not rat:
|
773 |
+
return rat
|
774 |
+
if self.exp.is_integer:
|
775 |
+
return False
|
776 |
+
else:
|
777 |
+
half = (2*self.exp).is_integer
|
778 |
+
if half:
|
779 |
+
return self.base.is_negative
|
780 |
+
return half
|
781 |
+
|
782 |
+
if self.base.is_extended_real is False: # we already know it's not imag
|
783 |
+
from sympy.functions.elementary.complexes import arg
|
784 |
+
i = arg(self.base)*self.exp/S.Pi
|
785 |
+
isodd = (2*i).is_odd
|
786 |
+
if isodd is not None:
|
787 |
+
return isodd
|
788 |
+
|
789 |
+
def _eval_is_odd(self):
|
790 |
+
if self.exp.is_integer:
|
791 |
+
if self.exp.is_positive:
|
792 |
+
return self.base.is_odd
|
793 |
+
elif self.exp.is_nonnegative and self.base.is_odd:
|
794 |
+
return True
|
795 |
+
elif self.base is S.NegativeOne:
|
796 |
+
return True
|
797 |
+
|
798 |
+
def _eval_is_finite(self):
|
799 |
+
if self.exp.is_negative:
|
800 |
+
if self.base.is_zero:
|
801 |
+
return False
|
802 |
+
if self.base.is_infinite or self.base.is_nonzero:
|
803 |
+
return True
|
804 |
+
c1 = self.base.is_finite
|
805 |
+
if c1 is None:
|
806 |
+
return
|
807 |
+
c2 = self.exp.is_finite
|
808 |
+
if c2 is None:
|
809 |
+
return
|
810 |
+
if c1 and c2:
|
811 |
+
if self.exp.is_nonnegative or fuzzy_not(self.base.is_zero):
|
812 |
+
return True
|
813 |
+
|
814 |
+
def _eval_is_prime(self):
|
815 |
+
'''
|
816 |
+
An integer raised to the n(>=2)-th power cannot be a prime.
|
817 |
+
'''
|
818 |
+
if self.base.is_integer and self.exp.is_integer and (self.exp - 1).is_positive:
|
819 |
+
return False
|
820 |
+
|
821 |
+
def _eval_is_composite(self):
|
822 |
+
"""
|
823 |
+
A power is composite if both base and exponent are greater than 1
|
824 |
+
"""
|
825 |
+
if (self.base.is_integer and self.exp.is_integer and
|
826 |
+
((self.base - 1).is_positive and (self.exp - 1).is_positive or
|
827 |
+
(self.base + 1).is_negative and self.exp.is_positive and self.exp.is_even)):
|
828 |
+
return True
|
829 |
+
|
830 |
+
def _eval_is_polar(self):
|
831 |
+
return self.base.is_polar
|
832 |
+
|
833 |
+
def _eval_subs(self, old, new):
|
834 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
835 |
+
|
836 |
+
if isinstance(self.exp, AccumBounds):
|
837 |
+
b = self.base.subs(old, new)
|
838 |
+
e = self.exp.subs(old, new)
|
839 |
+
if isinstance(e, AccumBounds):
|
840 |
+
return e.__rpow__(b)
|
841 |
+
return self.func(b, e)
|
842 |
+
|
843 |
+
from sympy.functions.elementary.exponential import exp, log
|
844 |
+
|
845 |
+
def _check(ct1, ct2, old):
|
846 |
+
"""Return (bool, pow, remainder_pow) where, if bool is True, then the
|
847 |
+
exponent of Pow `old` will combine with `pow` so the substitution
|
848 |
+
is valid, otherwise bool will be False.
|
849 |
+
|
850 |
+
For noncommutative objects, `pow` will be an integer, and a factor
|
851 |
+
`Pow(old.base, remainder_pow)` needs to be included. If there is
|
852 |
+
no such factor, None is returned. For commutative objects,
|
853 |
+
remainder_pow is always None.
|
854 |
+
|
855 |
+
cti are the coefficient and terms of an exponent of self or old
|
856 |
+
In this _eval_subs routine a change like (b**(2*x)).subs(b**x, y)
|
857 |
+
will give y**2 since (b**x)**2 == b**(2*x); if that equality does
|
858 |
+
not hold then the substitution should not occur so `bool` will be
|
859 |
+
False.
|
860 |
+
|
861 |
+
"""
|
862 |
+
coeff1, terms1 = ct1
|
863 |
+
coeff2, terms2 = ct2
|
864 |
+
if terms1 == terms2:
|
865 |
+
if old.is_commutative:
|
866 |
+
# Allow fractional powers for commutative objects
|
867 |
+
pow = coeff1/coeff2
|
868 |
+
try:
|
869 |
+
as_int(pow, strict=False)
|
870 |
+
combines = True
|
871 |
+
except ValueError:
|
872 |
+
b, e = old.as_base_exp()
|
873 |
+
# These conditions ensure that (b**e)**f == b**(e*f) for any f
|
874 |
+
combines = b.is_positive and e.is_real or b.is_nonnegative and e.is_nonnegative
|
875 |
+
|
876 |
+
return combines, pow, None
|
877 |
+
else:
|
878 |
+
# With noncommutative symbols, substitute only integer powers
|
879 |
+
if not isinstance(terms1, tuple):
|
880 |
+
terms1 = (terms1,)
|
881 |
+
if not all(term.is_integer for term in terms1):
|
882 |
+
return False, None, None
|
883 |
+
|
884 |
+
try:
|
885 |
+
# Round pow toward zero
|
886 |
+
pow, remainder = divmod(as_int(coeff1), as_int(coeff2))
|
887 |
+
if pow < 0 and remainder != 0:
|
888 |
+
pow += 1
|
889 |
+
remainder -= as_int(coeff2)
|
890 |
+
|
891 |
+
if remainder == 0:
|
892 |
+
remainder_pow = None
|
893 |
+
else:
|
894 |
+
remainder_pow = Mul(remainder, *terms1)
|
895 |
+
|
896 |
+
return True, pow, remainder_pow
|
897 |
+
except ValueError:
|
898 |
+
# Can't substitute
|
899 |
+
pass
|
900 |
+
|
901 |
+
return False, None, None
|
902 |
+
|
903 |
+
if old == self.base or (old == exp and self.base == S.Exp1):
|
904 |
+
if new.is_Function and isinstance(new, Callable):
|
905 |
+
return new(self.exp._subs(old, new))
|
906 |
+
else:
|
907 |
+
return new**self.exp._subs(old, new)
|
908 |
+
|
909 |
+
# issue 10829: (4**x - 3*y + 2).subs(2**x, y) -> y**2 - 3*y + 2
|
910 |
+
if isinstance(old, self.func) and self.exp == old.exp:
|
911 |
+
l = log(self.base, old.base)
|
912 |
+
if l.is_Number:
|
913 |
+
return Pow(new, l)
|
914 |
+
|
915 |
+
if isinstance(old, self.func) and self.base == old.base:
|
916 |
+
if self.exp.is_Add is False:
|
917 |
+
ct1 = self.exp.as_independent(Symbol, as_Add=False)
|
918 |
+
ct2 = old.exp.as_independent(Symbol, as_Add=False)
|
919 |
+
ok, pow, remainder_pow = _check(ct1, ct2, old)
|
920 |
+
if ok:
|
921 |
+
# issue 5180: (x**(6*y)).subs(x**(3*y),z)->z**2
|
922 |
+
result = self.func(new, pow)
|
923 |
+
if remainder_pow is not None:
|
924 |
+
result = Mul(result, Pow(old.base, remainder_pow))
|
925 |
+
return result
|
926 |
+
else: # b**(6*x + a).subs(b**(3*x), y) -> y**2 * b**a
|
927 |
+
# exp(exp(x) + exp(x**2)).subs(exp(exp(x)), w) -> w * exp(exp(x**2))
|
928 |
+
oarg = old.exp
|
929 |
+
new_l = []
|
930 |
+
o_al = []
|
931 |
+
ct2 = oarg.as_coeff_mul()
|
932 |
+
for a in self.exp.args:
|
933 |
+
newa = a._subs(old, new)
|
934 |
+
ct1 = newa.as_coeff_mul()
|
935 |
+
ok, pow, remainder_pow = _check(ct1, ct2, old)
|
936 |
+
if ok:
|
937 |
+
new_l.append(new**pow)
|
938 |
+
if remainder_pow is not None:
|
939 |
+
o_al.append(remainder_pow)
|
940 |
+
continue
|
941 |
+
elif not old.is_commutative and not newa.is_integer:
|
942 |
+
# If any term in the exponent is non-integer,
|
943 |
+
# we do not do any substitutions in the noncommutative case
|
944 |
+
return
|
945 |
+
o_al.append(newa)
|
946 |
+
if new_l:
|
947 |
+
expo = Add(*o_al)
|
948 |
+
new_l.append(Pow(self.base, expo, evaluate=False) if expo != 1 else self.base)
|
949 |
+
return Mul(*new_l)
|
950 |
+
|
951 |
+
if (isinstance(old, exp) or (old.is_Pow and old.base is S.Exp1)) and self.exp.is_extended_real and self.base.is_positive:
|
952 |
+
ct1 = old.exp.as_independent(Symbol, as_Add=False)
|
953 |
+
ct2 = (self.exp*log(self.base)).as_independent(
|
954 |
+
Symbol, as_Add=False)
|
955 |
+
ok, pow, remainder_pow = _check(ct1, ct2, old)
|
956 |
+
if ok:
|
957 |
+
result = self.func(new, pow) # (2**x).subs(exp(x*log(2)), z) -> z
|
958 |
+
if remainder_pow is not None:
|
959 |
+
result = Mul(result, Pow(old.base, remainder_pow))
|
960 |
+
return result
|
961 |
+
|
962 |
+
def as_base_exp(self):
|
963 |
+
"""Return base and exp of self.
|
964 |
+
|
965 |
+
Explanation
|
966 |
+
===========
|
967 |
+
|
968 |
+
If base a Rational less than 1, then return 1/Rational, -exp.
|
969 |
+
If this extra processing is not needed, the base and exp
|
970 |
+
properties will give the raw arguments.
|
971 |
+
|
972 |
+
Examples
|
973 |
+
========
|
974 |
+
|
975 |
+
>>> from sympy import Pow, S
|
976 |
+
>>> p = Pow(S.Half, 2, evaluate=False)
|
977 |
+
>>> p.as_base_exp()
|
978 |
+
(2, -2)
|
979 |
+
>>> p.args
|
980 |
+
(1/2, 2)
|
981 |
+
>>> p.base, p.exp
|
982 |
+
(1/2, 2)
|
983 |
+
|
984 |
+
"""
|
985 |
+
|
986 |
+
b, e = self.args
|
987 |
+
if b.is_Rational and b.p < b.q and b.p > 0:
|
988 |
+
return 1/b, -e
|
989 |
+
return b, e
|
990 |
+
|
991 |
+
def _eval_adjoint(self):
|
992 |
+
from sympy.functions.elementary.complexes import adjoint
|
993 |
+
i, p = self.exp.is_integer, self.base.is_positive
|
994 |
+
if i:
|
995 |
+
return adjoint(self.base)**self.exp
|
996 |
+
if p:
|
997 |
+
return self.base**adjoint(self.exp)
|
998 |
+
if i is False and p is False:
|
999 |
+
expanded = expand_complex(self)
|
1000 |
+
if expanded != self:
|
1001 |
+
return adjoint(expanded)
|
1002 |
+
|
1003 |
+
def _eval_conjugate(self):
|
1004 |
+
from sympy.functions.elementary.complexes import conjugate as c
|
1005 |
+
i, p = self.exp.is_integer, self.base.is_positive
|
1006 |
+
if i:
|
1007 |
+
return c(self.base)**self.exp
|
1008 |
+
if p:
|
1009 |
+
return self.base**c(self.exp)
|
1010 |
+
if i is False and p is False:
|
1011 |
+
expanded = expand_complex(self)
|
1012 |
+
if expanded != self:
|
1013 |
+
return c(expanded)
|
1014 |
+
if self.is_extended_real:
|
1015 |
+
return self
|
1016 |
+
|
1017 |
+
def _eval_transpose(self):
|
1018 |
+
from sympy.functions.elementary.complexes import transpose
|
1019 |
+
if self.base == S.Exp1:
|
1020 |
+
return self.func(S.Exp1, self.exp.transpose())
|
1021 |
+
i, p = self.exp.is_integer, (self.base.is_complex or self.base.is_infinite)
|
1022 |
+
if p:
|
1023 |
+
return self.base**self.exp
|
1024 |
+
if i:
|
1025 |
+
return transpose(self.base)**self.exp
|
1026 |
+
if i is False and p is False:
|
1027 |
+
expanded = expand_complex(self)
|
1028 |
+
if expanded != self:
|
1029 |
+
return transpose(expanded)
|
1030 |
+
|
1031 |
+
def _eval_expand_power_exp(self, **hints):
|
1032 |
+
"""a**(n + m) -> a**n*a**m"""
|
1033 |
+
b = self.base
|
1034 |
+
e = self.exp
|
1035 |
+
if b == S.Exp1:
|
1036 |
+
from sympy.concrete.summations import Sum
|
1037 |
+
if isinstance(e, Sum) and e.is_commutative:
|
1038 |
+
from sympy.concrete.products import Product
|
1039 |
+
return Product(self.func(b, e.function), *e.limits)
|
1040 |
+
if e.is_Add and (hints.get('force', False) or
|
1041 |
+
b.is_zero is False or e._all_nonneg_or_nonppos()):
|
1042 |
+
if e.is_commutative:
|
1043 |
+
return Mul(*[self.func(b, x) for x in e.args])
|
1044 |
+
if b.is_commutative:
|
1045 |
+
c, nc = sift(e.args, lambda x: x.is_commutative, binary=True)
|
1046 |
+
if c:
|
1047 |
+
return Mul(*[self.func(b, x) for x in c]
|
1048 |
+
)*b**Add._from_args(nc)
|
1049 |
+
return self
|
1050 |
+
|
1051 |
+
def _eval_expand_power_base(self, **hints):
|
1052 |
+
"""(a*b)**n -> a**n * b**n"""
|
1053 |
+
force = hints.get('force', False)
|
1054 |
+
|
1055 |
+
b = self.base
|
1056 |
+
e = self.exp
|
1057 |
+
if not b.is_Mul:
|
1058 |
+
return self
|
1059 |
+
|
1060 |
+
cargs, nc = b.args_cnc(split_1=False)
|
1061 |
+
|
1062 |
+
# expand each term - this is top-level-only
|
1063 |
+
# expansion but we have to watch out for things
|
1064 |
+
# that don't have an _eval_expand method
|
1065 |
+
if nc:
|
1066 |
+
nc = [i._eval_expand_power_base(**hints)
|
1067 |
+
if hasattr(i, '_eval_expand_power_base') else i
|
1068 |
+
for i in nc]
|
1069 |
+
|
1070 |
+
if e.is_Integer:
|
1071 |
+
if e.is_positive:
|
1072 |
+
rv = Mul(*nc*e)
|
1073 |
+
else:
|
1074 |
+
rv = Mul(*[i**-1 for i in nc[::-1]]*-e)
|
1075 |
+
if cargs:
|
1076 |
+
rv *= Mul(*cargs)**e
|
1077 |
+
return rv
|
1078 |
+
|
1079 |
+
if not cargs:
|
1080 |
+
return self.func(Mul(*nc), e, evaluate=False)
|
1081 |
+
|
1082 |
+
nc = [Mul(*nc)]
|
1083 |
+
|
1084 |
+
# sift the commutative bases
|
1085 |
+
other, maybe_real = sift(cargs, lambda x: x.is_extended_real is False,
|
1086 |
+
binary=True)
|
1087 |
+
def pred(x):
|
1088 |
+
if x is S.ImaginaryUnit:
|
1089 |
+
return S.ImaginaryUnit
|
1090 |
+
polar = x.is_polar
|
1091 |
+
if polar:
|
1092 |
+
return True
|
1093 |
+
if polar is None:
|
1094 |
+
return fuzzy_bool(x.is_extended_nonnegative)
|
1095 |
+
sifted = sift(maybe_real, pred)
|
1096 |
+
nonneg = sifted[True]
|
1097 |
+
other += sifted[None]
|
1098 |
+
neg = sifted[False]
|
1099 |
+
imag = sifted[S.ImaginaryUnit]
|
1100 |
+
if imag:
|
1101 |
+
I = S.ImaginaryUnit
|
1102 |
+
i = len(imag) % 4
|
1103 |
+
if i == 0:
|
1104 |
+
pass
|
1105 |
+
elif i == 1:
|
1106 |
+
other.append(I)
|
1107 |
+
elif i == 2:
|
1108 |
+
if neg:
|
1109 |
+
nonn = -neg.pop()
|
1110 |
+
if nonn is not S.One:
|
1111 |
+
nonneg.append(nonn)
|
1112 |
+
else:
|
1113 |
+
neg.append(S.NegativeOne)
|
1114 |
+
else:
|
1115 |
+
if neg:
|
1116 |
+
nonn = -neg.pop()
|
1117 |
+
if nonn is not S.One:
|
1118 |
+
nonneg.append(nonn)
|
1119 |
+
else:
|
1120 |
+
neg.append(S.NegativeOne)
|
1121 |
+
other.append(I)
|
1122 |
+
del imag
|
1123 |
+
|
1124 |
+
# bring out the bases that can be separated from the base
|
1125 |
+
|
1126 |
+
if force or e.is_integer:
|
1127 |
+
# treat all commutatives the same and put nc in other
|
1128 |
+
cargs = nonneg + neg + other
|
1129 |
+
other = nc
|
1130 |
+
else:
|
1131 |
+
# this is just like what is happening automatically, except
|
1132 |
+
# that now we are doing it for an arbitrary exponent for which
|
1133 |
+
# no automatic expansion is done
|
1134 |
+
|
1135 |
+
assert not e.is_Integer
|
1136 |
+
|
1137 |
+
# handle negatives by making them all positive and putting
|
1138 |
+
# the residual -1 in other
|
1139 |
+
if len(neg) > 1:
|
1140 |
+
o = S.One
|
1141 |
+
if not other and neg[0].is_Number:
|
1142 |
+
o *= neg.pop(0)
|
1143 |
+
if len(neg) % 2:
|
1144 |
+
o = -o
|
1145 |
+
for n in neg:
|
1146 |
+
nonneg.append(-n)
|
1147 |
+
if o is not S.One:
|
1148 |
+
other.append(o)
|
1149 |
+
elif neg and other:
|
1150 |
+
if neg[0].is_Number and neg[0] is not S.NegativeOne:
|
1151 |
+
other.append(S.NegativeOne)
|
1152 |
+
nonneg.append(-neg[0])
|
1153 |
+
else:
|
1154 |
+
other.extend(neg)
|
1155 |
+
else:
|
1156 |
+
other.extend(neg)
|
1157 |
+
del neg
|
1158 |
+
|
1159 |
+
cargs = nonneg
|
1160 |
+
other += nc
|
1161 |
+
|
1162 |
+
rv = S.One
|
1163 |
+
if cargs:
|
1164 |
+
if e.is_Rational:
|
1165 |
+
npow, cargs = sift(cargs, lambda x: x.is_Pow and
|
1166 |
+
x.exp.is_Rational and x.base.is_number,
|
1167 |
+
binary=True)
|
1168 |
+
rv = Mul(*[self.func(b.func(*b.args), e) for b in npow])
|
1169 |
+
rv *= Mul(*[self.func(b, e, evaluate=False) for b in cargs])
|
1170 |
+
if other:
|
1171 |
+
rv *= self.func(Mul(*other), e, evaluate=False)
|
1172 |
+
return rv
|
1173 |
+
|
1174 |
+
def _eval_expand_multinomial(self, **hints):
|
1175 |
+
"""(a + b + ..)**n -> a**n + n*a**(n-1)*b + .., n is nonzero integer"""
|
1176 |
+
|
1177 |
+
base, exp = self.args
|
1178 |
+
result = self
|
1179 |
+
|
1180 |
+
if exp.is_Rational and exp.p > 0 and base.is_Add:
|
1181 |
+
if not exp.is_Integer:
|
1182 |
+
n = Integer(exp.p // exp.q)
|
1183 |
+
|
1184 |
+
if not n:
|
1185 |
+
return result
|
1186 |
+
else:
|
1187 |
+
radical, result = self.func(base, exp - n), []
|
1188 |
+
|
1189 |
+
expanded_base_n = self.func(base, n)
|
1190 |
+
if expanded_base_n.is_Pow:
|
1191 |
+
expanded_base_n = \
|
1192 |
+
expanded_base_n._eval_expand_multinomial()
|
1193 |
+
for term in Add.make_args(expanded_base_n):
|
1194 |
+
result.append(term*radical)
|
1195 |
+
|
1196 |
+
return Add(*result)
|
1197 |
+
|
1198 |
+
n = int(exp)
|
1199 |
+
|
1200 |
+
if base.is_commutative:
|
1201 |
+
order_terms, other_terms = [], []
|
1202 |
+
|
1203 |
+
for b in base.args:
|
1204 |
+
if b.is_Order:
|
1205 |
+
order_terms.append(b)
|
1206 |
+
else:
|
1207 |
+
other_terms.append(b)
|
1208 |
+
|
1209 |
+
if order_terms:
|
1210 |
+
# (f(x) + O(x^n))^m -> f(x)^m + m*f(x)^{m-1} *O(x^n)
|
1211 |
+
f = Add(*other_terms)
|
1212 |
+
o = Add(*order_terms)
|
1213 |
+
|
1214 |
+
if n == 2:
|
1215 |
+
return expand_multinomial(f**n, deep=False) + n*f*o
|
1216 |
+
else:
|
1217 |
+
g = expand_multinomial(f**(n - 1), deep=False)
|
1218 |
+
return expand_mul(f*g, deep=False) + n*g*o
|
1219 |
+
|
1220 |
+
if base.is_number:
|
1221 |
+
# Efficiently expand expressions of the form (a + b*I)**n
|
1222 |
+
# where 'a' and 'b' are real numbers and 'n' is integer.
|
1223 |
+
a, b = base.as_real_imag()
|
1224 |
+
|
1225 |
+
if a.is_Rational and b.is_Rational:
|
1226 |
+
if not a.is_Integer:
|
1227 |
+
if not b.is_Integer:
|
1228 |
+
k = self.func(a.q * b.q, n)
|
1229 |
+
a, b = a.p*b.q, a.q*b.p
|
1230 |
+
else:
|
1231 |
+
k = self.func(a.q, n)
|
1232 |
+
a, b = a.p, a.q*b
|
1233 |
+
elif not b.is_Integer:
|
1234 |
+
k = self.func(b.q, n)
|
1235 |
+
a, b = a*b.q, b.p
|
1236 |
+
else:
|
1237 |
+
k = 1
|
1238 |
+
|
1239 |
+
a, b, c, d = int(a), int(b), 1, 0
|
1240 |
+
|
1241 |
+
while n:
|
1242 |
+
if n & 1:
|
1243 |
+
c, d = a*c - b*d, b*c + a*d
|
1244 |
+
n -= 1
|
1245 |
+
a, b = a*a - b*b, 2*a*b
|
1246 |
+
n //= 2
|
1247 |
+
|
1248 |
+
I = S.ImaginaryUnit
|
1249 |
+
|
1250 |
+
if k == 1:
|
1251 |
+
return c + I*d
|
1252 |
+
else:
|
1253 |
+
return Integer(c)/k + I*d/k
|
1254 |
+
|
1255 |
+
p = other_terms
|
1256 |
+
# (x + y)**3 -> x**3 + 3*x**2*y + 3*x*y**2 + y**3
|
1257 |
+
# in this particular example:
|
1258 |
+
# p = [x,y]; n = 3
|
1259 |
+
# so now it's easy to get the correct result -- we get the
|
1260 |
+
# coefficients first:
|
1261 |
+
from sympy.ntheory.multinomial import multinomial_coefficients
|
1262 |
+
from sympy.polys.polyutils import basic_from_dict
|
1263 |
+
expansion_dict = multinomial_coefficients(len(p), n)
|
1264 |
+
# in our example: {(3, 0): 1, (1, 2): 3, (0, 3): 1, (2, 1): 3}
|
1265 |
+
# and now construct the expression.
|
1266 |
+
return basic_from_dict(expansion_dict, *p)
|
1267 |
+
else:
|
1268 |
+
if n == 2:
|
1269 |
+
return Add(*[f*g for f in base.args for g in base.args])
|
1270 |
+
else:
|
1271 |
+
multi = (base**(n - 1))._eval_expand_multinomial()
|
1272 |
+
if multi.is_Add:
|
1273 |
+
return Add(*[f*g for f in base.args
|
1274 |
+
for g in multi.args])
|
1275 |
+
else:
|
1276 |
+
# XXX can this ever happen if base was an Add?
|
1277 |
+
return Add(*[f*multi for f in base.args])
|
1278 |
+
elif (exp.is_Rational and exp.p < 0 and base.is_Add and
|
1279 |
+
abs(exp.p) > exp.q):
|
1280 |
+
return 1 / self.func(base, -exp)._eval_expand_multinomial()
|
1281 |
+
elif exp.is_Add and base.is_Number and (hints.get('force', False) or
|
1282 |
+
base.is_zero is False or exp._all_nonneg_or_nonppos()):
|
1283 |
+
# a + b a b
|
1284 |
+
# n --> n n, where n, a, b are Numbers
|
1285 |
+
# XXX should be in expand_power_exp?
|
1286 |
+
coeff, tail = [], []
|
1287 |
+
for term in exp.args:
|
1288 |
+
if term.is_Number:
|
1289 |
+
coeff.append(self.func(base, term))
|
1290 |
+
else:
|
1291 |
+
tail.append(term)
|
1292 |
+
return Mul(*(coeff + [self.func(base, Add._from_args(tail))]))
|
1293 |
+
else:
|
1294 |
+
return result
|
1295 |
+
|
1296 |
+
def as_real_imag(self, deep=True, **hints):
|
1297 |
+
if self.exp.is_Integer:
|
1298 |
+
from sympy.polys.polytools import poly
|
1299 |
+
|
1300 |
+
exp = self.exp
|
1301 |
+
re_e, im_e = self.base.as_real_imag(deep=deep)
|
1302 |
+
if not im_e:
|
1303 |
+
return self, S.Zero
|
1304 |
+
a, b = symbols('a b', cls=Dummy)
|
1305 |
+
if exp >= 0:
|
1306 |
+
if re_e.is_Number and im_e.is_Number:
|
1307 |
+
# We can be more efficient in this case
|
1308 |
+
expr = expand_multinomial(self.base**exp)
|
1309 |
+
if expr != self:
|
1310 |
+
return expr.as_real_imag()
|
1311 |
+
|
1312 |
+
expr = poly(
|
1313 |
+
(a + b)**exp) # a = re, b = im; expr = (a + b*I)**exp
|
1314 |
+
else:
|
1315 |
+
mag = re_e**2 + im_e**2
|
1316 |
+
re_e, im_e = re_e/mag, -im_e/mag
|
1317 |
+
if re_e.is_Number and im_e.is_Number:
|
1318 |
+
# We can be more efficient in this case
|
1319 |
+
expr = expand_multinomial((re_e + im_e*S.ImaginaryUnit)**-exp)
|
1320 |
+
if expr != self:
|
1321 |
+
return expr.as_real_imag()
|
1322 |
+
|
1323 |
+
expr = poly((a + b)**-exp)
|
1324 |
+
|
1325 |
+
# Terms with even b powers will be real
|
1326 |
+
r = [i for i in expr.terms() if not i[0][1] % 2]
|
1327 |
+
re_part = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
|
1328 |
+
# Terms with odd b powers will be imaginary
|
1329 |
+
r = [i for i in expr.terms() if i[0][1] % 4 == 1]
|
1330 |
+
im_part1 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
|
1331 |
+
r = [i for i in expr.terms() if i[0][1] % 4 == 3]
|
1332 |
+
im_part3 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
|
1333 |
+
|
1334 |
+
return (re_part.subs({a: re_e, b: S.ImaginaryUnit*im_e}),
|
1335 |
+
im_part1.subs({a: re_e, b: im_e}) + im_part3.subs({a: re_e, b: -im_e}))
|
1336 |
+
|
1337 |
+
from sympy.functions.elementary.trigonometric import atan2, cos, sin
|
1338 |
+
|
1339 |
+
if self.exp.is_Rational:
|
1340 |
+
re_e, im_e = self.base.as_real_imag(deep=deep)
|
1341 |
+
|
1342 |
+
if im_e.is_zero and self.exp is S.Half:
|
1343 |
+
if re_e.is_extended_nonnegative:
|
1344 |
+
return self, S.Zero
|
1345 |
+
if re_e.is_extended_nonpositive:
|
1346 |
+
return S.Zero, (-self.base)**self.exp
|
1347 |
+
|
1348 |
+
# XXX: This is not totally correct since for x**(p/q) with
|
1349 |
+
# x being imaginary there are actually q roots, but
|
1350 |
+
# only a single one is returned from here.
|
1351 |
+
r = self.func(self.func(re_e, 2) + self.func(im_e, 2), S.Half)
|
1352 |
+
|
1353 |
+
t = atan2(im_e, re_e)
|
1354 |
+
|
1355 |
+
rp, tp = self.func(r, self.exp), t*self.exp
|
1356 |
+
|
1357 |
+
return rp*cos(tp), rp*sin(tp)
|
1358 |
+
elif self.base is S.Exp1:
|
1359 |
+
from sympy.functions.elementary.exponential import exp
|
1360 |
+
re_e, im_e = self.exp.as_real_imag()
|
1361 |
+
if deep:
|
1362 |
+
re_e = re_e.expand(deep, **hints)
|
1363 |
+
im_e = im_e.expand(deep, **hints)
|
1364 |
+
c, s = cos(im_e), sin(im_e)
|
1365 |
+
return exp(re_e)*c, exp(re_e)*s
|
1366 |
+
else:
|
1367 |
+
from sympy.functions.elementary.complexes import im, re
|
1368 |
+
if deep:
|
1369 |
+
hints['complex'] = False
|
1370 |
+
|
1371 |
+
expanded = self.expand(deep, **hints)
|
1372 |
+
if hints.get('ignore') == expanded:
|
1373 |
+
return None
|
1374 |
+
else:
|
1375 |
+
return (re(expanded), im(expanded))
|
1376 |
+
else:
|
1377 |
+
return re(self), im(self)
|
1378 |
+
|
1379 |
+
def _eval_derivative(self, s):
|
1380 |
+
from sympy.functions.elementary.exponential import log
|
1381 |
+
dbase = self.base.diff(s)
|
1382 |
+
dexp = self.exp.diff(s)
|
1383 |
+
return self * (dexp * log(self.base) + dbase * self.exp/self.base)
|
1384 |
+
|
1385 |
+
def _eval_evalf(self, prec):
|
1386 |
+
base, exp = self.as_base_exp()
|
1387 |
+
if base == S.Exp1:
|
1388 |
+
# Use mpmath function associated to class "exp":
|
1389 |
+
from sympy.functions.elementary.exponential import exp as exp_function
|
1390 |
+
return exp_function(self.exp, evaluate=False)._eval_evalf(prec)
|
1391 |
+
base = base._evalf(prec)
|
1392 |
+
if not exp.is_Integer:
|
1393 |
+
exp = exp._evalf(prec)
|
1394 |
+
if exp.is_negative and base.is_number and base.is_extended_real is False:
|
1395 |
+
base = base.conjugate() / (base * base.conjugate())._evalf(prec)
|
1396 |
+
exp = -exp
|
1397 |
+
return self.func(base, exp).expand()
|
1398 |
+
return self.func(base, exp)
|
1399 |
+
|
1400 |
+
def _eval_is_polynomial(self, syms):
|
1401 |
+
if self.exp.has(*syms):
|
1402 |
+
return False
|
1403 |
+
|
1404 |
+
if self.base.has(*syms):
|
1405 |
+
return bool(self.base._eval_is_polynomial(syms) and
|
1406 |
+
self.exp.is_Integer and (self.exp >= 0))
|
1407 |
+
else:
|
1408 |
+
return True
|
1409 |
+
|
1410 |
+
def _eval_is_rational(self):
|
1411 |
+
# The evaluation of self.func below can be very expensive in the case
|
1412 |
+
# of integer**integer if the exponent is large. We should try to exit
|
1413 |
+
# before that if possible:
|
1414 |
+
if (self.exp.is_integer and self.base.is_rational
|
1415 |
+
and fuzzy_not(fuzzy_and([self.exp.is_negative, self.base.is_zero]))):
|
1416 |
+
return True
|
1417 |
+
p = self.func(*self.as_base_exp()) # in case it's unevaluated
|
1418 |
+
if not p.is_Pow:
|
1419 |
+
return p.is_rational
|
1420 |
+
b, e = p.as_base_exp()
|
1421 |
+
if e.is_Rational and b.is_Rational:
|
1422 |
+
# we didn't check that e is not an Integer
|
1423 |
+
# because Rational**Integer autosimplifies
|
1424 |
+
return False
|
1425 |
+
if e.is_integer:
|
1426 |
+
if b.is_rational:
|
1427 |
+
if fuzzy_not(b.is_zero) or e.is_nonnegative:
|
1428 |
+
return True
|
1429 |
+
if b == e: # always rational, even for 0**0
|
1430 |
+
return True
|
1431 |
+
elif b.is_irrational:
|
1432 |
+
return e.is_zero
|
1433 |
+
if b is S.Exp1:
|
1434 |
+
if e.is_rational and e.is_nonzero:
|
1435 |
+
return False
|
1436 |
+
|
1437 |
+
def _eval_is_algebraic(self):
|
1438 |
+
def _is_one(expr):
|
1439 |
+
try:
|
1440 |
+
return (expr - 1).is_zero
|
1441 |
+
except ValueError:
|
1442 |
+
# when the operation is not allowed
|
1443 |
+
return False
|
1444 |
+
|
1445 |
+
if self.base.is_zero or _is_one(self.base):
|
1446 |
+
return True
|
1447 |
+
elif self.base is S.Exp1:
|
1448 |
+
s = self.func(*self.args)
|
1449 |
+
if s.func == self.func:
|
1450 |
+
if self.exp.is_nonzero:
|
1451 |
+
if self.exp.is_algebraic:
|
1452 |
+
return False
|
1453 |
+
elif (self.exp/S.Pi).is_rational:
|
1454 |
+
return False
|
1455 |
+
elif (self.exp/(S.ImaginaryUnit*S.Pi)).is_rational:
|
1456 |
+
return True
|
1457 |
+
else:
|
1458 |
+
return s.is_algebraic
|
1459 |
+
elif self.exp.is_rational:
|
1460 |
+
if self.base.is_algebraic is False:
|
1461 |
+
return self.exp.is_zero
|
1462 |
+
if self.base.is_zero is False:
|
1463 |
+
if self.exp.is_nonzero:
|
1464 |
+
return self.base.is_algebraic
|
1465 |
+
elif self.base.is_algebraic:
|
1466 |
+
return True
|
1467 |
+
if self.exp.is_positive:
|
1468 |
+
return self.base.is_algebraic
|
1469 |
+
elif self.base.is_algebraic and self.exp.is_algebraic:
|
1470 |
+
if ((fuzzy_not(self.base.is_zero)
|
1471 |
+
and fuzzy_not(_is_one(self.base)))
|
1472 |
+
or self.base.is_integer is False
|
1473 |
+
or self.base.is_irrational):
|
1474 |
+
return self.exp.is_rational
|
1475 |
+
|
1476 |
+
def _eval_is_rational_function(self, syms):
|
1477 |
+
if self.exp.has(*syms):
|
1478 |
+
return False
|
1479 |
+
|
1480 |
+
if self.base.has(*syms):
|
1481 |
+
return self.base._eval_is_rational_function(syms) and \
|
1482 |
+
self.exp.is_Integer
|
1483 |
+
else:
|
1484 |
+
return True
|
1485 |
+
|
1486 |
+
def _eval_is_meromorphic(self, x, a):
|
1487 |
+
# f**g is meromorphic if g is an integer and f is meromorphic.
|
1488 |
+
# E**(log(f)*g) is meromorphic if log(f)*g is meromorphic
|
1489 |
+
# and finite.
|
1490 |
+
base_merom = self.base._eval_is_meromorphic(x, a)
|
1491 |
+
exp_integer = self.exp.is_Integer
|
1492 |
+
if exp_integer:
|
1493 |
+
return base_merom
|
1494 |
+
|
1495 |
+
exp_merom = self.exp._eval_is_meromorphic(x, a)
|
1496 |
+
if base_merom is False:
|
1497 |
+
# f**g = E**(log(f)*g) may be meromorphic if the
|
1498 |
+
# singularities of log(f) and g cancel each other,
|
1499 |
+
# for example, if g = 1/log(f). Hence,
|
1500 |
+
return False if exp_merom else None
|
1501 |
+
elif base_merom is None:
|
1502 |
+
return None
|
1503 |
+
|
1504 |
+
b = self.base.subs(x, a)
|
1505 |
+
# b is extended complex as base is meromorphic.
|
1506 |
+
# log(base) is finite and meromorphic when b != 0, zoo.
|
1507 |
+
b_zero = b.is_zero
|
1508 |
+
if b_zero:
|
1509 |
+
log_defined = False
|
1510 |
+
else:
|
1511 |
+
log_defined = fuzzy_and((b.is_finite, fuzzy_not(b_zero)))
|
1512 |
+
|
1513 |
+
if log_defined is False: # zero or pole of base
|
1514 |
+
return exp_integer # False or None
|
1515 |
+
elif log_defined is None:
|
1516 |
+
return None
|
1517 |
+
|
1518 |
+
if not exp_merom:
|
1519 |
+
return exp_merom # False or None
|
1520 |
+
|
1521 |
+
return self.exp.subs(x, a).is_finite
|
1522 |
+
|
1523 |
+
def _eval_is_algebraic_expr(self, syms):
|
1524 |
+
if self.exp.has(*syms):
|
1525 |
+
return False
|
1526 |
+
|
1527 |
+
if self.base.has(*syms):
|
1528 |
+
return self.base._eval_is_algebraic_expr(syms) and \
|
1529 |
+
self.exp.is_Rational
|
1530 |
+
else:
|
1531 |
+
return True
|
1532 |
+
|
1533 |
+
def _eval_rewrite_as_exp(self, base, expo, **kwargs):
|
1534 |
+
from sympy.functions.elementary.exponential import exp, log
|
1535 |
+
|
1536 |
+
if base.is_zero or base.has(exp) or expo.has(exp):
|
1537 |
+
return base**expo
|
1538 |
+
|
1539 |
+
if base.has(Symbol):
|
1540 |
+
# delay evaluation if expo is non symbolic
|
1541 |
+
# (as exp(x*log(5)) automatically reduces to x**5)
|
1542 |
+
if global_parameters.exp_is_pow:
|
1543 |
+
return Pow(S.Exp1, log(base)*expo, evaluate=expo.has(Symbol))
|
1544 |
+
else:
|
1545 |
+
return exp(log(base)*expo, evaluate=expo.has(Symbol))
|
1546 |
+
|
1547 |
+
else:
|
1548 |
+
from sympy.functions.elementary.complexes import arg, Abs
|
1549 |
+
return exp((log(Abs(base)) + S.ImaginaryUnit*arg(base))*expo)
|
1550 |
+
|
1551 |
+
def as_numer_denom(self):
|
1552 |
+
if not self.is_commutative:
|
1553 |
+
return self, S.One
|
1554 |
+
base, exp = self.as_base_exp()
|
1555 |
+
n, d = base.as_numer_denom()
|
1556 |
+
# this should be the same as ExpBase.as_numer_denom wrt
|
1557 |
+
# exponent handling
|
1558 |
+
neg_exp = exp.is_negative
|
1559 |
+
if exp.is_Mul and not neg_exp and not exp.is_positive:
|
1560 |
+
neg_exp = exp.could_extract_minus_sign()
|
1561 |
+
int_exp = exp.is_integer
|
1562 |
+
# the denominator cannot be separated from the numerator if
|
1563 |
+
# its sign is unknown unless the exponent is an integer, e.g.
|
1564 |
+
# sqrt(a/b) != sqrt(a)/sqrt(b) when a=1 and b=-1. But if the
|
1565 |
+
# denominator is negative the numerator and denominator can
|
1566 |
+
# be negated and the denominator (now positive) separated.
|
1567 |
+
if not (d.is_extended_real or int_exp):
|
1568 |
+
n = base
|
1569 |
+
d = S.One
|
1570 |
+
dnonpos = d.is_nonpositive
|
1571 |
+
if dnonpos:
|
1572 |
+
n, d = -n, -d
|
1573 |
+
elif dnonpos is None and not int_exp:
|
1574 |
+
n = base
|
1575 |
+
d = S.One
|
1576 |
+
if neg_exp:
|
1577 |
+
n, d = d, n
|
1578 |
+
exp = -exp
|
1579 |
+
if exp.is_infinite:
|
1580 |
+
if n is S.One and d is not S.One:
|
1581 |
+
return n, self.func(d, exp)
|
1582 |
+
if n is not S.One and d is S.One:
|
1583 |
+
return self.func(n, exp), d
|
1584 |
+
return self.func(n, exp), self.func(d, exp)
|
1585 |
+
|
1586 |
+
def matches(self, expr, repl_dict=None, old=False):
|
1587 |
+
expr = _sympify(expr)
|
1588 |
+
if repl_dict is None:
|
1589 |
+
repl_dict = {}
|
1590 |
+
|
1591 |
+
# special case, pattern = 1 and expr.exp can match to 0
|
1592 |
+
if expr is S.One:
|
1593 |
+
d = self.exp.matches(S.Zero, repl_dict)
|
1594 |
+
if d is not None:
|
1595 |
+
return d
|
1596 |
+
|
1597 |
+
# make sure the expression to be matched is an Expr
|
1598 |
+
if not isinstance(expr, Expr):
|
1599 |
+
return None
|
1600 |
+
|
1601 |
+
b, e = expr.as_base_exp()
|
1602 |
+
|
1603 |
+
# special case number
|
1604 |
+
sb, se = self.as_base_exp()
|
1605 |
+
if sb.is_Symbol and se.is_Integer and expr:
|
1606 |
+
if e.is_rational:
|
1607 |
+
return sb.matches(b**(e/se), repl_dict)
|
1608 |
+
return sb.matches(expr**(1/se), repl_dict)
|
1609 |
+
|
1610 |
+
d = repl_dict.copy()
|
1611 |
+
d = self.base.matches(b, d)
|
1612 |
+
if d is None:
|
1613 |
+
return None
|
1614 |
+
|
1615 |
+
d = self.exp.xreplace(d).matches(e, d)
|
1616 |
+
if d is None:
|
1617 |
+
return Expr.matches(self, expr, repl_dict)
|
1618 |
+
return d
|
1619 |
+
|
1620 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
1621 |
+
# NOTE! This function is an important part of the gruntz algorithm
|
1622 |
+
# for computing limits. It has to return a generalized power
|
1623 |
+
# series with coefficients in C(log, log(x)). In more detail:
|
1624 |
+
# It has to return an expression
|
1625 |
+
# c_0*x**e_0 + c_1*x**e_1 + ... (finitely many terms)
|
1626 |
+
# where e_i are numbers (not necessarily integers) and c_i are
|
1627 |
+
# expressions involving only numbers, the log function, and log(x).
|
1628 |
+
# The series expansion of b**e is computed as follows:
|
1629 |
+
# 1) We express b as f*(1 + g) where f is the leading term of b.
|
1630 |
+
# g has order O(x**d) where d is strictly positive.
|
1631 |
+
# 2) Then b**e = (f**e)*((1 + g)**e).
|
1632 |
+
# (1 + g)**e is computed using binomial series.
|
1633 |
+
from sympy.functions.elementary.exponential import exp, log
|
1634 |
+
from sympy.series.limits import limit
|
1635 |
+
from sympy.series.order import Order
|
1636 |
+
from sympy.core.sympify import sympify
|
1637 |
+
if self.base is S.Exp1:
|
1638 |
+
e_series = self.exp.nseries(x, n=n, logx=logx)
|
1639 |
+
if e_series.is_Order:
|
1640 |
+
return 1 + e_series
|
1641 |
+
e0 = limit(e_series.removeO(), x, 0)
|
1642 |
+
if e0 is S.NegativeInfinity:
|
1643 |
+
return Order(x**n, x)
|
1644 |
+
if e0 is S.Infinity:
|
1645 |
+
return self
|
1646 |
+
t = e_series - e0
|
1647 |
+
exp_series = term = exp(e0)
|
1648 |
+
# series of exp(e0 + t) in t
|
1649 |
+
for i in range(1, n):
|
1650 |
+
term *= t/i
|
1651 |
+
term = term.nseries(x, n=n, logx=logx)
|
1652 |
+
exp_series += term
|
1653 |
+
exp_series += Order(t**n, x)
|
1654 |
+
from sympy.simplify.powsimp import powsimp
|
1655 |
+
return powsimp(exp_series, deep=True, combine='exp')
|
1656 |
+
from sympy.simplify.powsimp import powdenest
|
1657 |
+
from .numbers import _illegal
|
1658 |
+
self = powdenest(self, force=True).trigsimp()
|
1659 |
+
b, e = self.as_base_exp()
|
1660 |
+
|
1661 |
+
if e.has(*_illegal):
|
1662 |
+
raise PoleError()
|
1663 |
+
|
1664 |
+
if e.has(x):
|
1665 |
+
return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
|
1666 |
+
|
1667 |
+
if logx is not None and b.has(log):
|
1668 |
+
from .symbol import Wild
|
1669 |
+
c, ex = symbols('c, ex', cls=Wild, exclude=[x])
|
1670 |
+
b = b.replace(log(c*x**ex), log(c) + ex*logx)
|
1671 |
+
self = b**e
|
1672 |
+
|
1673 |
+
b = b.removeO()
|
1674 |
+
try:
|
1675 |
+
from sympy.functions.special.gamma_functions import polygamma
|
1676 |
+
if b.has(polygamma, S.EulerGamma) and logx is not None:
|
1677 |
+
raise ValueError()
|
1678 |
+
_, m = b.leadterm(x)
|
1679 |
+
except (ValueError, NotImplementedError, PoleError):
|
1680 |
+
b = b._eval_nseries(x, n=max(2, n), logx=logx, cdir=cdir).removeO()
|
1681 |
+
if b.has(S.NaN, S.ComplexInfinity):
|
1682 |
+
raise NotImplementedError()
|
1683 |
+
_, m = b.leadterm(x)
|
1684 |
+
|
1685 |
+
if e.has(log):
|
1686 |
+
from sympy.simplify.simplify import logcombine
|
1687 |
+
e = logcombine(e).cancel()
|
1688 |
+
|
1689 |
+
if not (m.is_zero or e.is_number and e.is_real):
|
1690 |
+
if self == self._eval_as_leading_term(x, logx=logx, cdir=cdir):
|
1691 |
+
res = exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
|
1692 |
+
if res == exp(e*log(b)):
|
1693 |
+
return self
|
1694 |
+
return res
|
1695 |
+
|
1696 |
+
f = b.as_leading_term(x, logx=logx)
|
1697 |
+
g = (b/f - S.One).cancel(expand=False)
|
1698 |
+
if not m.is_number:
|
1699 |
+
raise NotImplementedError()
|
1700 |
+
maxpow = n - m*e
|
1701 |
+
if maxpow.has(Symbol):
|
1702 |
+
maxpow = sympify(n)
|
1703 |
+
|
1704 |
+
if maxpow.is_negative:
|
1705 |
+
return Order(x**(m*e), x)
|
1706 |
+
|
1707 |
+
if g.is_zero:
|
1708 |
+
r = f**e
|
1709 |
+
if r != self:
|
1710 |
+
r += Order(x**n, x)
|
1711 |
+
return r
|
1712 |
+
|
1713 |
+
def coeff_exp(term, x):
|
1714 |
+
coeff, exp = S.One, S.Zero
|
1715 |
+
for factor in Mul.make_args(term):
|
1716 |
+
if factor.has(x):
|
1717 |
+
base, exp = factor.as_base_exp()
|
1718 |
+
if base != x:
|
1719 |
+
try:
|
1720 |
+
return term.leadterm(x)
|
1721 |
+
except ValueError:
|
1722 |
+
return term, S.Zero
|
1723 |
+
else:
|
1724 |
+
coeff *= factor
|
1725 |
+
return coeff, exp
|
1726 |
+
|
1727 |
+
def mul(d1, d2):
|
1728 |
+
res = {}
|
1729 |
+
for e1, e2 in product(d1, d2):
|
1730 |
+
ex = e1 + e2
|
1731 |
+
if ex < maxpow:
|
1732 |
+
res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
|
1733 |
+
return res
|
1734 |
+
|
1735 |
+
try:
|
1736 |
+
c, d = g.leadterm(x, logx=logx)
|
1737 |
+
except (ValueError, NotImplementedError):
|
1738 |
+
if limit(g/x**maxpow, x, 0) == 0:
|
1739 |
+
# g has higher order zero
|
1740 |
+
return f**e + e*f**e*g # first term of binomial series
|
1741 |
+
else:
|
1742 |
+
raise NotImplementedError()
|
1743 |
+
if c.is_Float and d == S.Zero:
|
1744 |
+
# Convert floats like 0.5 to exact SymPy numbers like S.Half, to
|
1745 |
+
# prevent rounding errors which can induce wrong values of d leading
|
1746 |
+
# to a NotImplementedError being returned from the block below.
|
1747 |
+
from sympy.simplify.simplify import nsimplify
|
1748 |
+
_, d = nsimplify(g).leadterm(x, logx=logx)
|
1749 |
+
if not d.is_positive:
|
1750 |
+
g = g.simplify()
|
1751 |
+
if g.is_zero:
|
1752 |
+
return f**e
|
1753 |
+
_, d = g.leadterm(x, logx=logx)
|
1754 |
+
if not d.is_positive:
|
1755 |
+
g = ((b - f)/f).expand()
|
1756 |
+
_, d = g.leadterm(x, logx=logx)
|
1757 |
+
if not d.is_positive:
|
1758 |
+
raise NotImplementedError()
|
1759 |
+
|
1760 |
+
from sympy.functions.elementary.integers import ceiling
|
1761 |
+
gpoly = g._eval_nseries(x, n=ceiling(maxpow), logx=logx, cdir=cdir).removeO()
|
1762 |
+
gterms = {}
|
1763 |
+
|
1764 |
+
for term in Add.make_args(gpoly):
|
1765 |
+
co1, e1 = coeff_exp(term, x)
|
1766 |
+
gterms[e1] = gterms.get(e1, S.Zero) + co1
|
1767 |
+
|
1768 |
+
k = S.One
|
1769 |
+
terms = {S.Zero: S.One}
|
1770 |
+
tk = gterms
|
1771 |
+
|
1772 |
+
from sympy.functions.combinatorial.factorials import factorial, ff
|
1773 |
+
|
1774 |
+
while (k*d - maxpow).is_negative:
|
1775 |
+
coeff = ff(e, k)/factorial(k)
|
1776 |
+
for ex in tk:
|
1777 |
+
terms[ex] = terms.get(ex, S.Zero) + coeff*tk[ex]
|
1778 |
+
tk = mul(tk, gterms)
|
1779 |
+
k += S.One
|
1780 |
+
|
1781 |
+
from sympy.functions.elementary.complexes import im
|
1782 |
+
|
1783 |
+
if not e.is_integer and m.is_zero and f.is_negative:
|
1784 |
+
ndir = (b - f).dir(x, cdir)
|
1785 |
+
if im(ndir).is_negative:
|
1786 |
+
inco, inex = coeff_exp(f**e*(-1)**(-2*e), x)
|
1787 |
+
elif im(ndir).is_zero:
|
1788 |
+
inco, inex = coeff_exp(exp(e*log(b)).as_leading_term(x, logx=logx, cdir=cdir), x)
|
1789 |
+
else:
|
1790 |
+
inco, inex = coeff_exp(f**e, x)
|
1791 |
+
else:
|
1792 |
+
inco, inex = coeff_exp(f**e, x)
|
1793 |
+
res = S.Zero
|
1794 |
+
|
1795 |
+
for e1 in terms:
|
1796 |
+
ex = e1 + inex
|
1797 |
+
res += terms[e1]*inco*x**(ex)
|
1798 |
+
|
1799 |
+
if not (e.is_integer and e.is_positive and (e*d - n).is_nonpositive and
|
1800 |
+
res == _mexpand(self)):
|
1801 |
+
try:
|
1802 |
+
res += Order(x**n, x)
|
1803 |
+
except NotImplementedError:
|
1804 |
+
return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
|
1805 |
+
return res
|
1806 |
+
|
1807 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
1808 |
+
from sympy.functions.elementary.exponential import exp, log
|
1809 |
+
e = self.exp
|
1810 |
+
b = self.base
|
1811 |
+
if self.base is S.Exp1:
|
1812 |
+
arg = e.as_leading_term(x, logx=logx)
|
1813 |
+
arg0 = arg.subs(x, 0)
|
1814 |
+
if arg0 is S.NaN:
|
1815 |
+
arg0 = arg.limit(x, 0)
|
1816 |
+
if arg0.is_infinite is False:
|
1817 |
+
return S.Exp1**arg0
|
1818 |
+
raise PoleError("Cannot expand %s around 0" % (self))
|
1819 |
+
elif e.has(x):
|
1820 |
+
lt = exp(e * log(b))
|
1821 |
+
return lt.as_leading_term(x, logx=logx, cdir=cdir)
|
1822 |
+
else:
|
1823 |
+
from sympy.functions.elementary.complexes import im
|
1824 |
+
try:
|
1825 |
+
f = b.as_leading_term(x, logx=logx, cdir=cdir)
|
1826 |
+
except PoleError:
|
1827 |
+
return self
|
1828 |
+
if not e.is_integer and f.is_negative and not f.has(x):
|
1829 |
+
ndir = (b - f).dir(x, cdir)
|
1830 |
+
if im(ndir).is_negative:
|
1831 |
+
# Normally, f**e would evaluate to exp(e*log(f)) but on branch cuts
|
1832 |
+
# an other value is expected through the following computation
|
1833 |
+
# exp(e*(log(f) - 2*pi*I)) == f**e*exp(-2*e*pi*I) == f**e*(-1)**(-2*e).
|
1834 |
+
return self.func(f, e) * (-1)**(-2*e)
|
1835 |
+
elif im(ndir).is_zero:
|
1836 |
+
log_leadterm = log(b)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
1837 |
+
if log_leadterm.is_infinite is False:
|
1838 |
+
return exp(e*log_leadterm)
|
1839 |
+
return self.func(f, e)
|
1840 |
+
|
1841 |
+
@cacheit
|
1842 |
+
def _taylor_term(self, n, x, *previous_terms): # of (1 + x)**e
|
1843 |
+
from sympy.functions.combinatorial.factorials import binomial
|
1844 |
+
return binomial(self.exp, n) * self.func(x, n)
|
1845 |
+
|
1846 |
+
def taylor_term(self, n, x, *previous_terms):
|
1847 |
+
if self.base is not S.Exp1:
|
1848 |
+
return super().taylor_term(n, x, *previous_terms)
|
1849 |
+
if n < 0:
|
1850 |
+
return S.Zero
|
1851 |
+
if n == 0:
|
1852 |
+
return S.One
|
1853 |
+
from .sympify import sympify
|
1854 |
+
x = sympify(x)
|
1855 |
+
if previous_terms:
|
1856 |
+
p = previous_terms[-1]
|
1857 |
+
if p is not None:
|
1858 |
+
return p * x / n
|
1859 |
+
from sympy.functions.combinatorial.factorials import factorial
|
1860 |
+
return x**n/factorial(n)
|
1861 |
+
|
1862 |
+
def _eval_rewrite_as_sin(self, base, exp):
|
1863 |
+
if self.base is S.Exp1:
|
1864 |
+
from sympy.functions.elementary.trigonometric import sin
|
1865 |
+
return sin(S.ImaginaryUnit*self.exp + S.Pi/2) - S.ImaginaryUnit*sin(S.ImaginaryUnit*self.exp)
|
1866 |
+
|
1867 |
+
def _eval_rewrite_as_cos(self, base, exp):
|
1868 |
+
if self.base is S.Exp1:
|
1869 |
+
from sympy.functions.elementary.trigonometric import cos
|
1870 |
+
return cos(S.ImaginaryUnit*self.exp) + S.ImaginaryUnit*cos(S.ImaginaryUnit*self.exp + S.Pi/2)
|
1871 |
+
|
1872 |
+
def _eval_rewrite_as_tanh(self, base, exp):
|
1873 |
+
if self.base is S.Exp1:
|
1874 |
+
from sympy.functions.elementary.hyperbolic import tanh
|
1875 |
+
return (1 + tanh(self.exp/2))/(1 - tanh(self.exp/2))
|
1876 |
+
|
1877 |
+
def _eval_rewrite_as_sqrt(self, base, exp, **kwargs):
|
1878 |
+
from sympy.functions.elementary.trigonometric import sin, cos
|
1879 |
+
if base is not S.Exp1:
|
1880 |
+
return None
|
1881 |
+
if exp.is_Mul:
|
1882 |
+
coeff = exp.coeff(S.Pi * S.ImaginaryUnit)
|
1883 |
+
if coeff and coeff.is_number:
|
1884 |
+
cosine, sine = cos(S.Pi*coeff), sin(S.Pi*coeff)
|
1885 |
+
if not isinstance(cosine, cos) and not isinstance (sine, sin):
|
1886 |
+
return cosine + S.ImaginaryUnit*sine
|
1887 |
+
|
1888 |
+
def as_content_primitive(self, radical=False, clear=True):
|
1889 |
+
"""Return the tuple (R, self/R) where R is the positive Rational
|
1890 |
+
extracted from self.
|
1891 |
+
|
1892 |
+
Examples
|
1893 |
+
========
|
1894 |
+
|
1895 |
+
>>> from sympy import sqrt
|
1896 |
+
>>> sqrt(4 + 4*sqrt(2)).as_content_primitive()
|
1897 |
+
(2, sqrt(1 + sqrt(2)))
|
1898 |
+
>>> sqrt(3 + 3*sqrt(2)).as_content_primitive()
|
1899 |
+
(1, sqrt(3)*sqrt(1 + sqrt(2)))
|
1900 |
+
|
1901 |
+
>>> from sympy import expand_power_base, powsimp, Mul
|
1902 |
+
>>> from sympy.abc import x, y
|
1903 |
+
|
1904 |
+
>>> ((2*x + 2)**2).as_content_primitive()
|
1905 |
+
(4, (x + 1)**2)
|
1906 |
+
>>> (4**((1 + y)/2)).as_content_primitive()
|
1907 |
+
(2, 4**(y/2))
|
1908 |
+
>>> (3**((1 + y)/2)).as_content_primitive()
|
1909 |
+
(1, 3**((y + 1)/2))
|
1910 |
+
>>> (3**((5 + y)/2)).as_content_primitive()
|
1911 |
+
(9, 3**((y + 1)/2))
|
1912 |
+
>>> eq = 3**(2 + 2*x)
|
1913 |
+
>>> powsimp(eq) == eq
|
1914 |
+
True
|
1915 |
+
>>> eq.as_content_primitive()
|
1916 |
+
(9, 3**(2*x))
|
1917 |
+
>>> powsimp(Mul(*_))
|
1918 |
+
3**(2*x + 2)
|
1919 |
+
|
1920 |
+
>>> eq = (2 + 2*x)**y
|
1921 |
+
>>> s = expand_power_base(eq); s.is_Mul, s
|
1922 |
+
(False, (2*x + 2)**y)
|
1923 |
+
>>> eq.as_content_primitive()
|
1924 |
+
(1, (2*(x + 1))**y)
|
1925 |
+
>>> s = expand_power_base(_[1]); s.is_Mul, s
|
1926 |
+
(True, 2**y*(x + 1)**y)
|
1927 |
+
|
1928 |
+
See docstring of Expr.as_content_primitive for more examples.
|
1929 |
+
"""
|
1930 |
+
|
1931 |
+
b, e = self.as_base_exp()
|
1932 |
+
b = _keep_coeff(*b.as_content_primitive(radical=radical, clear=clear))
|
1933 |
+
ce, pe = e.as_content_primitive(radical=radical, clear=clear)
|
1934 |
+
if b.is_Rational:
|
1935 |
+
#e
|
1936 |
+
#= ce*pe
|
1937 |
+
#= ce*(h + t)
|
1938 |
+
#= ce*h + ce*t
|
1939 |
+
#=> self
|
1940 |
+
#= b**(ce*h)*b**(ce*t)
|
1941 |
+
#= b**(cehp/cehq)*b**(ce*t)
|
1942 |
+
#= b**(iceh + r/cehq)*b**(ce*t)
|
1943 |
+
#= b**(iceh)*b**(r/cehq)*b**(ce*t)
|
1944 |
+
#= b**(iceh)*b**(ce*t + r/cehq)
|
1945 |
+
h, t = pe.as_coeff_Add()
|
1946 |
+
if h.is_Rational and b != S.Zero:
|
1947 |
+
ceh = ce*h
|
1948 |
+
c = self.func(b, ceh)
|
1949 |
+
r = S.Zero
|
1950 |
+
if not c.is_Rational:
|
1951 |
+
iceh, r = divmod(ceh.p, ceh.q)
|
1952 |
+
c = self.func(b, iceh)
|
1953 |
+
return c, self.func(b, _keep_coeff(ce, t + r/ce/ceh.q))
|
1954 |
+
e = _keep_coeff(ce, pe)
|
1955 |
+
# b**e = (h*t)**e = h**e*t**e = c*m*t**e
|
1956 |
+
if e.is_Rational and b.is_Mul:
|
1957 |
+
h, t = b.as_content_primitive(radical=radical, clear=clear) # h is positive
|
1958 |
+
c, m = self.func(h, e).as_coeff_Mul() # so c is positive
|
1959 |
+
m, me = m.as_base_exp()
|
1960 |
+
if m is S.One or me == e: # probably always true
|
1961 |
+
# return the following, not return c, m*Pow(t, e)
|
1962 |
+
# which would change Pow into Mul; we let SymPy
|
1963 |
+
# decide what to do by using the unevaluated Mul, e.g
|
1964 |
+
# should it stay as sqrt(2 + 2*sqrt(5)) or become
|
1965 |
+
# sqrt(2)*sqrt(1 + sqrt(5))
|
1966 |
+
return c, self.func(_keep_coeff(m, t), e)
|
1967 |
+
return S.One, self.func(b, e)
|
1968 |
+
|
1969 |
+
def is_constant(self, *wrt, **flags):
|
1970 |
+
expr = self
|
1971 |
+
if flags.get('simplify', True):
|
1972 |
+
expr = expr.simplify()
|
1973 |
+
b, e = expr.as_base_exp()
|
1974 |
+
bz = b.equals(0)
|
1975 |
+
if bz: # recalculate with assumptions in case it's unevaluated
|
1976 |
+
new = b**e
|
1977 |
+
if new != expr:
|
1978 |
+
return new.is_constant()
|
1979 |
+
econ = e.is_constant(*wrt)
|
1980 |
+
bcon = b.is_constant(*wrt)
|
1981 |
+
if bcon:
|
1982 |
+
if econ:
|
1983 |
+
return True
|
1984 |
+
bz = b.equals(0)
|
1985 |
+
if bz is False:
|
1986 |
+
return False
|
1987 |
+
elif bcon is None:
|
1988 |
+
return None
|
1989 |
+
|
1990 |
+
return e.equals(0)
|
1991 |
+
|
1992 |
+
def _eval_difference_delta(self, n, step):
|
1993 |
+
b, e = self.args
|
1994 |
+
if e.has(n) and not b.has(n):
|
1995 |
+
new_e = e.subs(n, n + step)
|
1996 |
+
return (b**(new_e - e) - 1) * self
|
1997 |
+
|
1998 |
+
power = Dispatcher('power')
|
1999 |
+
power.add((object, object), Pow)
|
2000 |
+
|
2001 |
+
from .add import Add
|
2002 |
+
from .numbers import Integer
|
2003 |
+
from .mul import Mul, _keep_coeff
|
2004 |
+
from .symbol import Symbol, Dummy, symbols
|
llmeval-env/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')
|
llmeval-env/lib/python3.10/site-packages/sympy/core/relational.py
ADDED
@@ -0,0 +1,1587 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
llmeval-env/lib/python3.10/site-packages/sympy/core/rules.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Replacement rules.
|
3 |
+
"""
|
4 |
+
|
5 |
+
class Transform:
|
6 |
+
"""
|
7 |
+
Immutable mapping that can be used as a generic transformation rule.
|
8 |
+
|
9 |
+
Parameters
|
10 |
+
==========
|
11 |
+
|
12 |
+
transform : callable
|
13 |
+
Computes the value corresponding to any key.
|
14 |
+
|
15 |
+
filter : callable, optional
|
16 |
+
If supplied, specifies which objects are in the mapping.
|
17 |
+
|
18 |
+
Examples
|
19 |
+
========
|
20 |
+
|
21 |
+
>>> from sympy.core.rules import Transform
|
22 |
+
>>> from sympy.abc import x
|
23 |
+
|
24 |
+
This Transform will return, as a value, one more than the key:
|
25 |
+
|
26 |
+
>>> add1 = Transform(lambda x: x + 1)
|
27 |
+
>>> add1[1]
|
28 |
+
2
|
29 |
+
>>> add1[x]
|
30 |
+
x + 1
|
31 |
+
|
32 |
+
By default, all values are considered to be in the dictionary. If a filter
|
33 |
+
is supplied, only the objects for which it returns True are considered as
|
34 |
+
being in the dictionary:
|
35 |
+
|
36 |
+
>>> add1_odd = Transform(lambda x: x + 1, lambda x: x%2 == 1)
|
37 |
+
>>> 2 in add1_odd
|
38 |
+
False
|
39 |
+
>>> add1_odd.get(2, 0)
|
40 |
+
0
|
41 |
+
>>> 3 in add1_odd
|
42 |
+
True
|
43 |
+
>>> add1_odd[3]
|
44 |
+
4
|
45 |
+
>>> add1_odd.get(3, 0)
|
46 |
+
4
|
47 |
+
"""
|
48 |
+
|
49 |
+
def __init__(self, transform, filter=lambda x: True):
|
50 |
+
self._transform = transform
|
51 |
+
self._filter = filter
|
52 |
+
|
53 |
+
def __contains__(self, item):
|
54 |
+
return self._filter(item)
|
55 |
+
|
56 |
+
def __getitem__(self, key):
|
57 |
+
if self._filter(key):
|
58 |
+
return self._transform(key)
|
59 |
+
else:
|
60 |
+
raise KeyError(key)
|
61 |
+
|
62 |
+
def get(self, item, default=None):
|
63 |
+
if item in self:
|
64 |
+
return self[item]
|
65 |
+
else:
|
66 |
+
return default
|
llmeval-env/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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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
llmeval-env/lib/python3.10/site-packages/sympy/core/symbol.py
ADDED
@@ -0,0 +1,945 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from .assumptions import StdFactKB, _assume_defined
|
4 |
+
from .basic import Basic, Atom
|
5 |
+
from .cache import cacheit
|
6 |
+
from .containers import Tuple
|
7 |
+
from .expr import Expr, AtomicExpr
|
8 |
+
from .function import AppliedUndef, FunctionClass
|
9 |
+
from .kind import NumberKind, UndefinedKind
|
10 |
+
from .logic import fuzzy_bool
|
11 |
+
from .singleton import S
|
12 |
+
from .sorting import ordered
|
13 |
+
from .sympify import sympify
|
14 |
+
from sympy.logic.boolalg import Boolean
|
15 |
+
from sympy.utilities.iterables import sift, is_sequence
|
16 |
+
from sympy.utilities.misc import filldedent
|
17 |
+
|
18 |
+
import string
|
19 |
+
import re as _re
|
20 |
+
import random
|
21 |
+
from itertools import product
|
22 |
+
from typing import Any
|
23 |
+
|
24 |
+
|
25 |
+
class Str(Atom):
|
26 |
+
"""
|
27 |
+
Represents string in SymPy.
|
28 |
+
|
29 |
+
Explanation
|
30 |
+
===========
|
31 |
+
|
32 |
+
Previously, ``Symbol`` was used where string is needed in ``args`` of SymPy
|
33 |
+
objects, e.g. denoting the name of the instance. However, since ``Symbol``
|
34 |
+
represents mathematical scalar, this class should be used instead.
|
35 |
+
|
36 |
+
"""
|
37 |
+
__slots__ = ('name',)
|
38 |
+
|
39 |
+
def __new__(cls, name, **kwargs):
|
40 |
+
if not isinstance(name, str):
|
41 |
+
raise TypeError("name should be a string, not %s" % repr(type(name)))
|
42 |
+
obj = Expr.__new__(cls, **kwargs)
|
43 |
+
obj.name = name
|
44 |
+
return obj
|
45 |
+
|
46 |
+
def __getnewargs__(self):
|
47 |
+
return (self.name,)
|
48 |
+
|
49 |
+
def _hashable_content(self):
|
50 |
+
return (self.name,)
|
51 |
+
|
52 |
+
|
53 |
+
def _filter_assumptions(kwargs):
|
54 |
+
"""Split the given dict into assumptions and non-assumptions.
|
55 |
+
Keys are taken as assumptions if they correspond to an
|
56 |
+
entry in ``_assume_defined``.
|
57 |
+
"""
|
58 |
+
assumptions, nonassumptions = map(dict, sift(kwargs.items(),
|
59 |
+
lambda i: i[0] in _assume_defined,
|
60 |
+
binary=True))
|
61 |
+
Symbol._sanitize(assumptions)
|
62 |
+
return assumptions, nonassumptions
|
63 |
+
|
64 |
+
def _symbol(s, matching_symbol=None, **assumptions):
|
65 |
+
"""Return s if s is a Symbol, else if s is a string, return either
|
66 |
+
the matching_symbol if the names are the same or else a new symbol
|
67 |
+
with the same assumptions as the matching symbol (or the
|
68 |
+
assumptions as provided).
|
69 |
+
|
70 |
+
Examples
|
71 |
+
========
|
72 |
+
|
73 |
+
>>> from sympy import Symbol
|
74 |
+
>>> from sympy.core.symbol import _symbol
|
75 |
+
>>> _symbol('y')
|
76 |
+
y
|
77 |
+
>>> _.is_real is None
|
78 |
+
True
|
79 |
+
>>> _symbol('y', real=True).is_real
|
80 |
+
True
|
81 |
+
|
82 |
+
>>> x = Symbol('x')
|
83 |
+
>>> _symbol(x, real=True)
|
84 |
+
x
|
85 |
+
>>> _.is_real is None # ignore attribute if s is a Symbol
|
86 |
+
True
|
87 |
+
|
88 |
+
Below, the variable sym has the name 'foo':
|
89 |
+
|
90 |
+
>>> sym = Symbol('foo', real=True)
|
91 |
+
|
92 |
+
Since 'x' is not the same as sym's name, a new symbol is created:
|
93 |
+
|
94 |
+
>>> _symbol('x', sym).name
|
95 |
+
'x'
|
96 |
+
|
97 |
+
It will acquire any assumptions give:
|
98 |
+
|
99 |
+
>>> _symbol('x', sym, real=False).is_real
|
100 |
+
False
|
101 |
+
|
102 |
+
Since 'foo' is the same as sym's name, sym is returned
|
103 |
+
|
104 |
+
>>> _symbol('foo', sym)
|
105 |
+
foo
|
106 |
+
|
107 |
+
Any assumptions given are ignored:
|
108 |
+
|
109 |
+
>>> _symbol('foo', sym, real=False).is_real
|
110 |
+
True
|
111 |
+
|
112 |
+
NB: the symbol here may not be the same as a symbol with the same
|
113 |
+
name defined elsewhere as a result of different assumptions.
|
114 |
+
|
115 |
+
See Also
|
116 |
+
========
|
117 |
+
|
118 |
+
sympy.core.symbol.Symbol
|
119 |
+
|
120 |
+
"""
|
121 |
+
if isinstance(s, str):
|
122 |
+
if matching_symbol and matching_symbol.name == s:
|
123 |
+
return matching_symbol
|
124 |
+
return Symbol(s, **assumptions)
|
125 |
+
elif isinstance(s, Symbol):
|
126 |
+
return s
|
127 |
+
else:
|
128 |
+
raise ValueError('symbol must be string for symbol name or Symbol')
|
129 |
+
|
130 |
+
def uniquely_named_symbol(xname, exprs=(), compare=str, modify=None, **assumptions):
|
131 |
+
"""
|
132 |
+
Return a symbol whose name is derivated from *xname* but is unique
|
133 |
+
from any other symbols in *exprs*.
|
134 |
+
|
135 |
+
*xname* and symbol names in *exprs* are passed to *compare* to be
|
136 |
+
converted to comparable forms. If ``compare(xname)`` is not unique,
|
137 |
+
it is recursively passed to *modify* until unique name is acquired.
|
138 |
+
|
139 |
+
Parameters
|
140 |
+
==========
|
141 |
+
|
142 |
+
xname : str or Symbol
|
143 |
+
Base name for the new symbol.
|
144 |
+
|
145 |
+
exprs : Expr or iterable of Expr
|
146 |
+
Expressions whose symbols are compared to *xname*.
|
147 |
+
|
148 |
+
compare : function
|
149 |
+
Unary function which transforms *xname* and symbol names from
|
150 |
+
*exprs* to comparable form.
|
151 |
+
|
152 |
+
modify : function
|
153 |
+
Unary function which modifies the string. Default is appending
|
154 |
+
the number, or increasing the number if exists.
|
155 |
+
|
156 |
+
Examples
|
157 |
+
========
|
158 |
+
|
159 |
+
By default, a number is appended to *xname* to generate unique name.
|
160 |
+
If the number already exists, it is recursively increased.
|
161 |
+
|
162 |
+
>>> from sympy.core.symbol import uniquely_named_symbol, Symbol
|
163 |
+
>>> uniquely_named_symbol('x', Symbol('x'))
|
164 |
+
x0
|
165 |
+
>>> uniquely_named_symbol('x', (Symbol('x'), Symbol('x0')))
|
166 |
+
x1
|
167 |
+
>>> uniquely_named_symbol('x0', (Symbol('x1'), Symbol('x0')))
|
168 |
+
x2
|
169 |
+
|
170 |
+
Name generation can be controlled by passing *modify* parameter.
|
171 |
+
|
172 |
+
>>> from sympy.abc import x
|
173 |
+
>>> uniquely_named_symbol('x', x, modify=lambda s: 2*s)
|
174 |
+
xx
|
175 |
+
|
176 |
+
"""
|
177 |
+
def numbered_string_incr(s, start=0):
|
178 |
+
if not s:
|
179 |
+
return str(start)
|
180 |
+
i = len(s) - 1
|
181 |
+
while i != -1:
|
182 |
+
if not s[i].isdigit():
|
183 |
+
break
|
184 |
+
i -= 1
|
185 |
+
n = str(int(s[i + 1:] or start - 1) + 1)
|
186 |
+
return s[:i + 1] + n
|
187 |
+
|
188 |
+
default = None
|
189 |
+
if is_sequence(xname):
|
190 |
+
xname, default = xname
|
191 |
+
x = compare(xname)
|
192 |
+
if not exprs:
|
193 |
+
return _symbol(x, default, **assumptions)
|
194 |
+
if not is_sequence(exprs):
|
195 |
+
exprs = [exprs]
|
196 |
+
names = set().union(
|
197 |
+
[i.name for e in exprs for i in e.atoms(Symbol)] +
|
198 |
+
[i.func.name for e in exprs for i in e.atoms(AppliedUndef)])
|
199 |
+
if modify is None:
|
200 |
+
modify = numbered_string_incr
|
201 |
+
while any(x == compare(s) for s in names):
|
202 |
+
x = modify(x)
|
203 |
+
return _symbol(x, default, **assumptions)
|
204 |
+
_uniquely_named_symbol = uniquely_named_symbol
|
205 |
+
|
206 |
+
class Symbol(AtomicExpr, Boolean):
|
207 |
+
"""
|
208 |
+
Assumptions:
|
209 |
+
commutative = True
|
210 |
+
|
211 |
+
You can override the default assumptions in the constructor.
|
212 |
+
|
213 |
+
Examples
|
214 |
+
========
|
215 |
+
|
216 |
+
>>> from sympy import symbols
|
217 |
+
>>> A,B = symbols('A,B', commutative = False)
|
218 |
+
>>> bool(A*B != B*A)
|
219 |
+
True
|
220 |
+
>>> bool(A*B*2 == 2*A*B) == True # multiplication by scalars is commutative
|
221 |
+
True
|
222 |
+
|
223 |
+
"""
|
224 |
+
|
225 |
+
is_comparable = False
|
226 |
+
|
227 |
+
__slots__ = ('name', '_assumptions_orig', '_assumptions0')
|
228 |
+
|
229 |
+
name: str
|
230 |
+
|
231 |
+
is_Symbol = True
|
232 |
+
is_symbol = True
|
233 |
+
|
234 |
+
@property
|
235 |
+
def kind(self):
|
236 |
+
if self.is_commutative:
|
237 |
+
return NumberKind
|
238 |
+
return UndefinedKind
|
239 |
+
|
240 |
+
@property
|
241 |
+
def _diff_wrt(self):
|
242 |
+
"""Allow derivatives wrt Symbols.
|
243 |
+
|
244 |
+
Examples
|
245 |
+
========
|
246 |
+
|
247 |
+
>>> from sympy import Symbol
|
248 |
+
>>> x = Symbol('x')
|
249 |
+
>>> x._diff_wrt
|
250 |
+
True
|
251 |
+
"""
|
252 |
+
return True
|
253 |
+
|
254 |
+
@staticmethod
|
255 |
+
def _sanitize(assumptions, obj=None):
|
256 |
+
"""Remove None, convert values to bool, check commutativity *in place*.
|
257 |
+
"""
|
258 |
+
|
259 |
+
# be strict about commutativity: cannot be None
|
260 |
+
is_commutative = fuzzy_bool(assumptions.get('commutative', True))
|
261 |
+
if is_commutative is None:
|
262 |
+
whose = '%s ' % obj.__name__ if obj else ''
|
263 |
+
raise ValueError(
|
264 |
+
'%scommutativity must be True or False.' % whose)
|
265 |
+
|
266 |
+
# sanitize other assumptions so 1 -> True and 0 -> False
|
267 |
+
for key in list(assumptions.keys()):
|
268 |
+
v = assumptions[key]
|
269 |
+
if v is None:
|
270 |
+
assumptions.pop(key)
|
271 |
+
continue
|
272 |
+
assumptions[key] = bool(v)
|
273 |
+
|
274 |
+
def _merge(self, assumptions):
|
275 |
+
base = self.assumptions0
|
276 |
+
for k in set(assumptions) & set(base):
|
277 |
+
if assumptions[k] != base[k]:
|
278 |
+
raise ValueError(filldedent('''
|
279 |
+
non-matching assumptions for %s: existing value
|
280 |
+
is %s and new value is %s''' % (
|
281 |
+
k, base[k], assumptions[k])))
|
282 |
+
base.update(assumptions)
|
283 |
+
return base
|
284 |
+
|
285 |
+
def __new__(cls, name, **assumptions):
|
286 |
+
"""Symbols are identified by name and assumptions::
|
287 |
+
|
288 |
+
>>> from sympy import Symbol
|
289 |
+
>>> Symbol("x") == Symbol("x")
|
290 |
+
True
|
291 |
+
>>> Symbol("x", real=True) == Symbol("x", real=False)
|
292 |
+
False
|
293 |
+
|
294 |
+
"""
|
295 |
+
cls._sanitize(assumptions, cls)
|
296 |
+
return Symbol.__xnew_cached_(cls, name, **assumptions)
|
297 |
+
|
298 |
+
@staticmethod
|
299 |
+
def __xnew__(cls, name, **assumptions): # never cached (e.g. dummy)
|
300 |
+
if not isinstance(name, str):
|
301 |
+
raise TypeError("name should be a string, not %s" % repr(type(name)))
|
302 |
+
|
303 |
+
# This is retained purely so that srepr can include commutative=True if
|
304 |
+
# that was explicitly specified but not if it was not. Ideally srepr
|
305 |
+
# should not distinguish these cases because the symbols otherwise
|
306 |
+
# compare equal and are considered equivalent.
|
307 |
+
#
|
308 |
+
# See https://github.com/sympy/sympy/issues/8873
|
309 |
+
#
|
310 |
+
assumptions_orig = assumptions.copy()
|
311 |
+
|
312 |
+
# The only assumption that is assumed by default is comutative=True:
|
313 |
+
assumptions.setdefault('commutative', True)
|
314 |
+
|
315 |
+
assumptions_kb = StdFactKB(assumptions)
|
316 |
+
assumptions0 = dict(assumptions_kb)
|
317 |
+
|
318 |
+
obj = Expr.__new__(cls)
|
319 |
+
obj.name = name
|
320 |
+
|
321 |
+
obj._assumptions = assumptions_kb
|
322 |
+
obj._assumptions_orig = assumptions_orig
|
323 |
+
obj._assumptions0 = assumptions0
|
324 |
+
|
325 |
+
# The three assumptions dicts are all a little different:
|
326 |
+
#
|
327 |
+
# >>> from sympy import Symbol
|
328 |
+
# >>> x = Symbol('x', finite=True)
|
329 |
+
# >>> x.is_positive # query an assumption
|
330 |
+
# >>> x._assumptions
|
331 |
+
# {'finite': True, 'infinite': False, 'commutative': True, 'positive': None}
|
332 |
+
# >>> x._assumptions0
|
333 |
+
# {'finite': True, 'infinite': False, 'commutative': True}
|
334 |
+
# >>> x._assumptions_orig
|
335 |
+
# {'finite': True}
|
336 |
+
#
|
337 |
+
# Two symbols with the same name are equal if their _assumptions0 are
|
338 |
+
# the same. Arguably it should be _assumptions_orig that is being
|
339 |
+
# compared because that is more transparent to the user (it is
|
340 |
+
# what was passed to the constructor modulo changes made by _sanitize).
|
341 |
+
|
342 |
+
return obj
|
343 |
+
|
344 |
+
@staticmethod
|
345 |
+
@cacheit
|
346 |
+
def __xnew_cached_(cls, name, **assumptions): # symbols are always cached
|
347 |
+
return Symbol.__xnew__(cls, name, **assumptions)
|
348 |
+
|
349 |
+
def __getnewargs_ex__(self):
|
350 |
+
return ((self.name,), self._assumptions_orig)
|
351 |
+
|
352 |
+
# NOTE: __setstate__ is not needed for pickles created by __getnewargs_ex__
|
353 |
+
# but was used before Symbol was changed to use __getnewargs_ex__ in v1.9.
|
354 |
+
# Pickles created in previous SymPy versions will still need __setstate__
|
355 |
+
# so that they can be unpickled in SymPy > v1.9.
|
356 |
+
|
357 |
+
def __setstate__(self, state):
|
358 |
+
for name, value in state.items():
|
359 |
+
setattr(self, name, value)
|
360 |
+
|
361 |
+
def _hashable_content(self):
|
362 |
+
# Note: user-specified assumptions not hashed, just derived ones
|
363 |
+
return (self.name,) + tuple(sorted(self.assumptions0.items()))
|
364 |
+
|
365 |
+
def _eval_subs(self, old, new):
|
366 |
+
if old.is_Pow:
|
367 |
+
from sympy.core.power import Pow
|
368 |
+
return Pow(self, S.One, evaluate=False)._eval_subs(old, new)
|
369 |
+
|
370 |
+
def _eval_refine(self, assumptions):
|
371 |
+
return self
|
372 |
+
|
373 |
+
@property
|
374 |
+
def assumptions0(self):
|
375 |
+
return self._assumptions0.copy()
|
376 |
+
|
377 |
+
@cacheit
|
378 |
+
def sort_key(self, order=None):
|
379 |
+
return self.class_key(), (1, (self.name,)), S.One.sort_key(), S.One
|
380 |
+
|
381 |
+
def as_dummy(self):
|
382 |
+
# only put commutativity in explicitly if it is False
|
383 |
+
return Dummy(self.name) if self.is_commutative is not False \
|
384 |
+
else Dummy(self.name, commutative=self.is_commutative)
|
385 |
+
|
386 |
+
def as_real_imag(self, deep=True, **hints):
|
387 |
+
if hints.get('ignore') == self:
|
388 |
+
return None
|
389 |
+
else:
|
390 |
+
from sympy.functions.elementary.complexes import im, re
|
391 |
+
return (re(self), im(self))
|
392 |
+
|
393 |
+
def is_constant(self, *wrt, **flags):
|
394 |
+
if not wrt:
|
395 |
+
return False
|
396 |
+
return self not in wrt
|
397 |
+
|
398 |
+
@property
|
399 |
+
def free_symbols(self):
|
400 |
+
return {self}
|
401 |
+
|
402 |
+
binary_symbols = free_symbols # in this case, not always
|
403 |
+
|
404 |
+
def as_set(self):
|
405 |
+
return S.UniversalSet
|
406 |
+
|
407 |
+
|
408 |
+
class Dummy(Symbol):
|
409 |
+
"""Dummy symbols are each unique, even if they have the same name:
|
410 |
+
|
411 |
+
Examples
|
412 |
+
========
|
413 |
+
|
414 |
+
>>> from sympy import Dummy
|
415 |
+
>>> Dummy("x") == Dummy("x")
|
416 |
+
False
|
417 |
+
|
418 |
+
If a name is not supplied then a string value of an internal count will be
|
419 |
+
used. This is useful when a temporary variable is needed and the name
|
420 |
+
of the variable used in the expression is not important.
|
421 |
+
|
422 |
+
>>> Dummy() #doctest: +SKIP
|
423 |
+
_Dummy_10
|
424 |
+
|
425 |
+
"""
|
426 |
+
|
427 |
+
# In the rare event that a Dummy object needs to be recreated, both the
|
428 |
+
# `name` and `dummy_index` should be passed. This is used by `srepr` for
|
429 |
+
# example:
|
430 |
+
# >>> d1 = Dummy()
|
431 |
+
# >>> d2 = eval(srepr(d1))
|
432 |
+
# >>> d2 == d1
|
433 |
+
# True
|
434 |
+
#
|
435 |
+
# If a new session is started between `srepr` and `eval`, there is a very
|
436 |
+
# small chance that `d2` will be equal to a previously-created Dummy.
|
437 |
+
|
438 |
+
_count = 0
|
439 |
+
_prng = random.Random()
|
440 |
+
_base_dummy_index = _prng.randint(10**6, 9*10**6)
|
441 |
+
|
442 |
+
__slots__ = ('dummy_index',)
|
443 |
+
|
444 |
+
is_Dummy = True
|
445 |
+
|
446 |
+
def __new__(cls, name=None, dummy_index=None, **assumptions):
|
447 |
+
if dummy_index is not None:
|
448 |
+
assert name is not None, "If you specify a dummy_index, you must also provide a name"
|
449 |
+
|
450 |
+
if name is None:
|
451 |
+
name = "Dummy_" + str(Dummy._count)
|
452 |
+
|
453 |
+
if dummy_index is None:
|
454 |
+
dummy_index = Dummy._base_dummy_index + Dummy._count
|
455 |
+
Dummy._count += 1
|
456 |
+
|
457 |
+
cls._sanitize(assumptions, cls)
|
458 |
+
obj = Symbol.__xnew__(cls, name, **assumptions)
|
459 |
+
|
460 |
+
obj.dummy_index = dummy_index
|
461 |
+
|
462 |
+
return obj
|
463 |
+
|
464 |
+
def __getnewargs_ex__(self):
|
465 |
+
return ((self.name, self.dummy_index), self._assumptions_orig)
|
466 |
+
|
467 |
+
@cacheit
|
468 |
+
def sort_key(self, order=None):
|
469 |
+
return self.class_key(), (
|
470 |
+
2, (self.name, self.dummy_index)), S.One.sort_key(), S.One
|
471 |
+
|
472 |
+
def _hashable_content(self):
|
473 |
+
return Symbol._hashable_content(self) + (self.dummy_index,)
|
474 |
+
|
475 |
+
|
476 |
+
class Wild(Symbol):
|
477 |
+
"""
|
478 |
+
A Wild symbol matches anything, or anything
|
479 |
+
without whatever is explicitly excluded.
|
480 |
+
|
481 |
+
Parameters
|
482 |
+
==========
|
483 |
+
|
484 |
+
name : str
|
485 |
+
Name of the Wild instance.
|
486 |
+
|
487 |
+
exclude : iterable, optional
|
488 |
+
Instances in ``exclude`` will not be matched.
|
489 |
+
|
490 |
+
properties : iterable of functions, optional
|
491 |
+
Functions, each taking an expressions as input
|
492 |
+
and returns a ``bool``. All functions in ``properties``
|
493 |
+
need to return ``True`` in order for the Wild instance
|
494 |
+
to match the expression.
|
495 |
+
|
496 |
+
Examples
|
497 |
+
========
|
498 |
+
|
499 |
+
>>> from sympy import Wild, WildFunction, cos, pi
|
500 |
+
>>> from sympy.abc import x, y, z
|
501 |
+
>>> a = Wild('a')
|
502 |
+
>>> x.match(a)
|
503 |
+
{a_: x}
|
504 |
+
>>> pi.match(a)
|
505 |
+
{a_: pi}
|
506 |
+
>>> (3*x**2).match(a*x)
|
507 |
+
{a_: 3*x}
|
508 |
+
>>> cos(x).match(a)
|
509 |
+
{a_: cos(x)}
|
510 |
+
>>> b = Wild('b', exclude=[x])
|
511 |
+
>>> (3*x**2).match(b*x)
|
512 |
+
>>> b.match(a)
|
513 |
+
{a_: b_}
|
514 |
+
>>> A = WildFunction('A')
|
515 |
+
>>> A.match(a)
|
516 |
+
{a_: A_}
|
517 |
+
|
518 |
+
Tips
|
519 |
+
====
|
520 |
+
|
521 |
+
When using Wild, be sure to use the exclude
|
522 |
+
keyword to make the pattern more precise.
|
523 |
+
Without the exclude pattern, you may get matches
|
524 |
+
that are technically correct, but not what you
|
525 |
+
wanted. For example, using the above without
|
526 |
+
exclude:
|
527 |
+
|
528 |
+
>>> from sympy import symbols
|
529 |
+
>>> a, b = symbols('a b', cls=Wild)
|
530 |
+
>>> (2 + 3*y).match(a*x + b*y)
|
531 |
+
{a_: 2/x, b_: 3}
|
532 |
+
|
533 |
+
This is technically correct, because
|
534 |
+
(2/x)*x + 3*y == 2 + 3*y, but you probably
|
535 |
+
wanted it to not match at all. The issue is that
|
536 |
+
you really did not want a and b to include x and y,
|
537 |
+
and the exclude parameter lets you specify exactly
|
538 |
+
this. With the exclude parameter, the pattern will
|
539 |
+
not match.
|
540 |
+
|
541 |
+
>>> a = Wild('a', exclude=[x, y])
|
542 |
+
>>> b = Wild('b', exclude=[x, y])
|
543 |
+
>>> (2 + 3*y).match(a*x + b*y)
|
544 |
+
|
545 |
+
Exclude also helps remove ambiguity from matches.
|
546 |
+
|
547 |
+
>>> E = 2*x**3*y*z
|
548 |
+
>>> a, b = symbols('a b', cls=Wild)
|
549 |
+
>>> E.match(a*b)
|
550 |
+
{a_: 2*y*z, b_: x**3}
|
551 |
+
>>> a = Wild('a', exclude=[x, y])
|
552 |
+
>>> E.match(a*b)
|
553 |
+
{a_: z, b_: 2*x**3*y}
|
554 |
+
>>> a = Wild('a', exclude=[x, y, z])
|
555 |
+
>>> E.match(a*b)
|
556 |
+
{a_: 2, b_: x**3*y*z}
|
557 |
+
|
558 |
+
Wild also accepts a ``properties`` parameter:
|
559 |
+
|
560 |
+
>>> a = Wild('a', properties=[lambda k: k.is_Integer])
|
561 |
+
>>> E.match(a*b)
|
562 |
+
{a_: 2, b_: x**3*y*z}
|
563 |
+
|
564 |
+
"""
|
565 |
+
is_Wild = True
|
566 |
+
|
567 |
+
__slots__ = ('exclude', 'properties')
|
568 |
+
|
569 |
+
def __new__(cls, name, exclude=(), properties=(), **assumptions):
|
570 |
+
exclude = tuple([sympify(x) for x in exclude])
|
571 |
+
properties = tuple(properties)
|
572 |
+
cls._sanitize(assumptions, cls)
|
573 |
+
return Wild.__xnew__(cls, name, exclude, properties, **assumptions)
|
574 |
+
|
575 |
+
def __getnewargs__(self):
|
576 |
+
return (self.name, self.exclude, self.properties)
|
577 |
+
|
578 |
+
@staticmethod
|
579 |
+
@cacheit
|
580 |
+
def __xnew__(cls, name, exclude, properties, **assumptions):
|
581 |
+
obj = Symbol.__xnew__(cls, name, **assumptions)
|
582 |
+
obj.exclude = exclude
|
583 |
+
obj.properties = properties
|
584 |
+
return obj
|
585 |
+
|
586 |
+
def _hashable_content(self):
|
587 |
+
return super()._hashable_content() + (self.exclude, self.properties)
|
588 |
+
|
589 |
+
# TODO add check against another Wild
|
590 |
+
def matches(self, expr, repl_dict=None, old=False):
|
591 |
+
if any(expr.has(x) for x in self.exclude):
|
592 |
+
return None
|
593 |
+
if not all(f(expr) for f in self.properties):
|
594 |
+
return None
|
595 |
+
if repl_dict is None:
|
596 |
+
repl_dict = {}
|
597 |
+
else:
|
598 |
+
repl_dict = repl_dict.copy()
|
599 |
+
repl_dict[self] = expr
|
600 |
+
return repl_dict
|
601 |
+
|
602 |
+
|
603 |
+
_range = _re.compile('([0-9]*:[0-9]+|[a-zA-Z]?:[a-zA-Z])')
|
604 |
+
|
605 |
+
|
606 |
+
def symbols(names, *, cls=Symbol, **args) -> Any:
|
607 |
+
r"""
|
608 |
+
Transform strings into instances of :class:`Symbol` class.
|
609 |
+
|
610 |
+
:func:`symbols` function returns a sequence of symbols with names taken
|
611 |
+
from ``names`` argument, which can be a comma or whitespace delimited
|
612 |
+
string, or a sequence of strings::
|
613 |
+
|
614 |
+
>>> from sympy import symbols, Function
|
615 |
+
|
616 |
+
>>> x, y, z = symbols('x,y,z')
|
617 |
+
>>> a, b, c = symbols('a b c')
|
618 |
+
|
619 |
+
The type of output is dependent on the properties of input arguments::
|
620 |
+
|
621 |
+
>>> symbols('x')
|
622 |
+
x
|
623 |
+
>>> symbols('x,')
|
624 |
+
(x,)
|
625 |
+
>>> symbols('x,y')
|
626 |
+
(x, y)
|
627 |
+
>>> symbols(('a', 'b', 'c'))
|
628 |
+
(a, b, c)
|
629 |
+
>>> symbols(['a', 'b', 'c'])
|
630 |
+
[a, b, c]
|
631 |
+
>>> symbols({'a', 'b', 'c'})
|
632 |
+
{a, b, c}
|
633 |
+
|
634 |
+
If an iterable container is needed for a single symbol, set the ``seq``
|
635 |
+
argument to ``True`` or terminate the symbol name with a comma::
|
636 |
+
|
637 |
+
>>> symbols('x', seq=True)
|
638 |
+
(x,)
|
639 |
+
|
640 |
+
To reduce typing, range syntax is supported to create indexed symbols.
|
641 |
+
Ranges are indicated by a colon and the type of range is determined by
|
642 |
+
the character to the right of the colon. If the character is a digit
|
643 |
+
then all contiguous digits to the left are taken as the nonnegative
|
644 |
+
starting value (or 0 if there is no digit left of the colon) and all
|
645 |
+
contiguous digits to the right are taken as 1 greater than the ending
|
646 |
+
value::
|
647 |
+
|
648 |
+
>>> symbols('x:10')
|
649 |
+
(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9)
|
650 |
+
|
651 |
+
>>> symbols('x5:10')
|
652 |
+
(x5, x6, x7, x8, x9)
|
653 |
+
>>> symbols('x5(:2)')
|
654 |
+
(x50, x51)
|
655 |
+
|
656 |
+
>>> symbols('x5:10,y:5')
|
657 |
+
(x5, x6, x7, x8, x9, y0, y1, y2, y3, y4)
|
658 |
+
|
659 |
+
>>> symbols(('x5:10', 'y:5'))
|
660 |
+
((x5, x6, x7, x8, x9), (y0, y1, y2, y3, y4))
|
661 |
+
|
662 |
+
If the character to the right of the colon is a letter, then the single
|
663 |
+
letter to the left (or 'a' if there is none) is taken as the start
|
664 |
+
and all characters in the lexicographic range *through* the letter to
|
665 |
+
the right are used as the range::
|
666 |
+
|
667 |
+
>>> symbols('x:z')
|
668 |
+
(x, y, z)
|
669 |
+
>>> symbols('x:c') # null range
|
670 |
+
()
|
671 |
+
>>> symbols('x(:c)')
|
672 |
+
(xa, xb, xc)
|
673 |
+
|
674 |
+
>>> symbols(':c')
|
675 |
+
(a, b, c)
|
676 |
+
|
677 |
+
>>> symbols('a:d, x:z')
|
678 |
+
(a, b, c, d, x, y, z)
|
679 |
+
|
680 |
+
>>> symbols(('a:d', 'x:z'))
|
681 |
+
((a, b, c, d), (x, y, z))
|
682 |
+
|
683 |
+
Multiple ranges are supported; contiguous numerical ranges should be
|
684 |
+
separated by parentheses to disambiguate the ending number of one
|
685 |
+
range from the starting number of the next::
|
686 |
+
|
687 |
+
>>> symbols('x:2(1:3)')
|
688 |
+
(x01, x02, x11, x12)
|
689 |
+
>>> symbols(':3:2') # parsing is from left to right
|
690 |
+
(00, 01, 10, 11, 20, 21)
|
691 |
+
|
692 |
+
Only one pair of parentheses surrounding ranges are removed, so to
|
693 |
+
include parentheses around ranges, double them. And to include spaces,
|
694 |
+
commas, or colons, escape them with a backslash::
|
695 |
+
|
696 |
+
>>> symbols('x((a:b))')
|
697 |
+
(x(a), x(b))
|
698 |
+
>>> symbols(r'x(:1\,:2)') # or r'x((:1)\,(:2))'
|
699 |
+
(x(0,0), x(0,1))
|
700 |
+
|
701 |
+
All newly created symbols have assumptions set according to ``args``::
|
702 |
+
|
703 |
+
>>> a = symbols('a', integer=True)
|
704 |
+
>>> a.is_integer
|
705 |
+
True
|
706 |
+
|
707 |
+
>>> x, y, z = symbols('x,y,z', real=True)
|
708 |
+
>>> x.is_real and y.is_real and z.is_real
|
709 |
+
True
|
710 |
+
|
711 |
+
Despite its name, :func:`symbols` can create symbol-like objects like
|
712 |
+
instances of Function or Wild classes. To achieve this, set ``cls``
|
713 |
+
keyword argument to the desired type::
|
714 |
+
|
715 |
+
>>> symbols('f,g,h', cls=Function)
|
716 |
+
(f, g, h)
|
717 |
+
|
718 |
+
>>> type(_[0])
|
719 |
+
<class 'sympy.core.function.UndefinedFunction'>
|
720 |
+
|
721 |
+
"""
|
722 |
+
result = []
|
723 |
+
|
724 |
+
if isinstance(names, str):
|
725 |
+
marker = 0
|
726 |
+
splitters = r'\,', r'\:', r'\ '
|
727 |
+
literals: list[tuple[str, str]] = []
|
728 |
+
for splitter in splitters:
|
729 |
+
if splitter in names:
|
730 |
+
while chr(marker) in names:
|
731 |
+
marker += 1
|
732 |
+
lit_char = chr(marker)
|
733 |
+
marker += 1
|
734 |
+
names = names.replace(splitter, lit_char)
|
735 |
+
literals.append((lit_char, splitter[1:]))
|
736 |
+
def literal(s):
|
737 |
+
if literals:
|
738 |
+
for c, l in literals:
|
739 |
+
s = s.replace(c, l)
|
740 |
+
return s
|
741 |
+
|
742 |
+
names = names.strip()
|
743 |
+
as_seq = names.endswith(',')
|
744 |
+
if as_seq:
|
745 |
+
names = names[:-1].rstrip()
|
746 |
+
if not names:
|
747 |
+
raise ValueError('no symbols given')
|
748 |
+
|
749 |
+
# split on commas
|
750 |
+
names = [n.strip() for n in names.split(',')]
|
751 |
+
if not all(n for n in names):
|
752 |
+
raise ValueError('missing symbol between commas')
|
753 |
+
# split on spaces
|
754 |
+
for i in range(len(names) - 1, -1, -1):
|
755 |
+
names[i: i + 1] = names[i].split()
|
756 |
+
|
757 |
+
seq = args.pop('seq', as_seq)
|
758 |
+
|
759 |
+
for name in names:
|
760 |
+
if not name:
|
761 |
+
raise ValueError('missing symbol')
|
762 |
+
|
763 |
+
if ':' not in name:
|
764 |
+
symbol = cls(literal(name), **args)
|
765 |
+
result.append(symbol)
|
766 |
+
continue
|
767 |
+
|
768 |
+
split: list[str] = _range.split(name)
|
769 |
+
split_list: list[list[str]] = []
|
770 |
+
# remove 1 layer of bounding parentheses around ranges
|
771 |
+
for i in range(len(split) - 1):
|
772 |
+
if i and ':' in split[i] and split[i] != ':' and \
|
773 |
+
split[i - 1].endswith('(') and \
|
774 |
+
split[i + 1].startswith(')'):
|
775 |
+
split[i - 1] = split[i - 1][:-1]
|
776 |
+
split[i + 1] = split[i + 1][1:]
|
777 |
+
for s in split:
|
778 |
+
if ':' in s:
|
779 |
+
if s.endswith(':'):
|
780 |
+
raise ValueError('missing end range')
|
781 |
+
a, b = s.split(':')
|
782 |
+
if b[-1] in string.digits:
|
783 |
+
a_i = 0 if not a else int(a)
|
784 |
+
b_i = int(b)
|
785 |
+
split_list.append([str(c) for c in range(a_i, b_i)])
|
786 |
+
else:
|
787 |
+
a = a or 'a'
|
788 |
+
split_list.append([string.ascii_letters[c] for c in range(
|
789 |
+
string.ascii_letters.index(a),
|
790 |
+
string.ascii_letters.index(b) + 1)]) # inclusive
|
791 |
+
if not split_list[-1]:
|
792 |
+
break
|
793 |
+
else:
|
794 |
+
split_list.append([s])
|
795 |
+
else:
|
796 |
+
seq = True
|
797 |
+
if len(split_list) == 1:
|
798 |
+
names = split_list[0]
|
799 |
+
else:
|
800 |
+
names = [''.join(s) for s in product(*split_list)]
|
801 |
+
if literals:
|
802 |
+
result.extend([cls(literal(s), **args) for s in names])
|
803 |
+
else:
|
804 |
+
result.extend([cls(s, **args) for s in names])
|
805 |
+
|
806 |
+
if not seq and len(result) <= 1:
|
807 |
+
if not result:
|
808 |
+
return ()
|
809 |
+
return result[0]
|
810 |
+
|
811 |
+
return tuple(result)
|
812 |
+
else:
|
813 |
+
for name in names:
|
814 |
+
result.append(symbols(name, cls=cls, **args))
|
815 |
+
|
816 |
+
return type(names)(result)
|
817 |
+
|
818 |
+
|
819 |
+
def var(names, **args):
|
820 |
+
"""
|
821 |
+
Create symbols and inject them into the global namespace.
|
822 |
+
|
823 |
+
Explanation
|
824 |
+
===========
|
825 |
+
|
826 |
+
This calls :func:`symbols` with the same arguments and puts the results
|
827 |
+
into the *global* namespace. It's recommended not to use :func:`var` in
|
828 |
+
library code, where :func:`symbols` has to be used::
|
829 |
+
|
830 |
+
Examples
|
831 |
+
========
|
832 |
+
|
833 |
+
>>> from sympy import var
|
834 |
+
|
835 |
+
>>> var('x')
|
836 |
+
x
|
837 |
+
>>> x # noqa: F821
|
838 |
+
x
|
839 |
+
|
840 |
+
>>> var('a,ab,abc')
|
841 |
+
(a, ab, abc)
|
842 |
+
>>> abc # noqa: F821
|
843 |
+
abc
|
844 |
+
|
845 |
+
>>> var('x,y', real=True)
|
846 |
+
(x, y)
|
847 |
+
>>> x.is_real and y.is_real # noqa: F821
|
848 |
+
True
|
849 |
+
|
850 |
+
See :func:`symbols` documentation for more details on what kinds of
|
851 |
+
arguments can be passed to :func:`var`.
|
852 |
+
|
853 |
+
"""
|
854 |
+
def traverse(symbols, frame):
|
855 |
+
"""Recursively inject symbols to the global namespace. """
|
856 |
+
for symbol in symbols:
|
857 |
+
if isinstance(symbol, Basic):
|
858 |
+
frame.f_globals[symbol.name] = symbol
|
859 |
+
elif isinstance(symbol, FunctionClass):
|
860 |
+
frame.f_globals[symbol.__name__] = symbol
|
861 |
+
else:
|
862 |
+
traverse(symbol, frame)
|
863 |
+
|
864 |
+
from inspect import currentframe
|
865 |
+
frame = currentframe().f_back
|
866 |
+
|
867 |
+
try:
|
868 |
+
syms = symbols(names, **args)
|
869 |
+
|
870 |
+
if syms is not None:
|
871 |
+
if isinstance(syms, Basic):
|
872 |
+
frame.f_globals[syms.name] = syms
|
873 |
+
elif isinstance(syms, FunctionClass):
|
874 |
+
frame.f_globals[syms.__name__] = syms
|
875 |
+
else:
|
876 |
+
traverse(syms, frame)
|
877 |
+
finally:
|
878 |
+
del frame # break cyclic dependencies as stated in inspect docs
|
879 |
+
|
880 |
+
return syms
|
881 |
+
|
882 |
+
def disambiguate(*iter):
|
883 |
+
"""
|
884 |
+
Return a Tuple containing the passed expressions with symbols
|
885 |
+
that appear the same when printed replaced with numerically
|
886 |
+
subscripted symbols, and all Dummy symbols replaced with Symbols.
|
887 |
+
|
888 |
+
Parameters
|
889 |
+
==========
|
890 |
+
|
891 |
+
iter: list of symbols or expressions.
|
892 |
+
|
893 |
+
Examples
|
894 |
+
========
|
895 |
+
|
896 |
+
>>> from sympy.core.symbol import disambiguate
|
897 |
+
>>> from sympy import Dummy, Symbol, Tuple
|
898 |
+
>>> from sympy.abc import y
|
899 |
+
|
900 |
+
>>> tup = Symbol('_x'), Dummy('x'), Dummy('x')
|
901 |
+
>>> disambiguate(*tup)
|
902 |
+
(x_2, x, x_1)
|
903 |
+
|
904 |
+
>>> eqs = Tuple(Symbol('x')/y, Dummy('x')/y)
|
905 |
+
>>> disambiguate(*eqs)
|
906 |
+
(x_1/y, x/y)
|
907 |
+
|
908 |
+
>>> ix = Symbol('x', integer=True)
|
909 |
+
>>> vx = Symbol('x')
|
910 |
+
>>> disambiguate(vx + ix)
|
911 |
+
(x + x_1,)
|
912 |
+
|
913 |
+
To make your own mapping of symbols to use, pass only the free symbols
|
914 |
+
of the expressions and create a dictionary:
|
915 |
+
|
916 |
+
>>> free = eqs.free_symbols
|
917 |
+
>>> mapping = dict(zip(free, disambiguate(*free)))
|
918 |
+
>>> eqs.xreplace(mapping)
|
919 |
+
(x_1/y, x/y)
|
920 |
+
|
921 |
+
"""
|
922 |
+
new_iter = Tuple(*iter)
|
923 |
+
key = lambda x:tuple(sorted(x.assumptions0.items()))
|
924 |
+
syms = ordered(new_iter.free_symbols, keys=key)
|
925 |
+
mapping = {}
|
926 |
+
for s in syms:
|
927 |
+
mapping.setdefault(str(s).lstrip('_'), []).append(s)
|
928 |
+
reps = {}
|
929 |
+
for k in mapping:
|
930 |
+
# the first or only symbol doesn't get subscripted but make
|
931 |
+
# sure that it's a Symbol, not a Dummy
|
932 |
+
mapk0 = Symbol("%s" % (k), **mapping[k][0].assumptions0)
|
933 |
+
if mapping[k][0] != mapk0:
|
934 |
+
reps[mapping[k][0]] = mapk0
|
935 |
+
# the others get subscripts (and are made into Symbols)
|
936 |
+
skip = 0
|
937 |
+
for i in range(1, len(mapping[k])):
|
938 |
+
while True:
|
939 |
+
name = "%s_%i" % (k, i + skip)
|
940 |
+
if name not in mapping:
|
941 |
+
break
|
942 |
+
skip += 1
|
943 |
+
ki = mapping[k][i]
|
944 |
+
reps[ki] = Symbol(name, **ki.assumptions0)
|
945 |
+
return new_iter.xreplace(reps)
|
llmeval-env/lib/python3.10/site-packages/sympy/core/sympify.py
ADDED
@@ -0,0 +1,634 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_args.cpython-310.pyc
ADDED
Binary file (217 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_basic.cpython-310.pyc
ADDED
Binary file (11.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_compatibility.cpython-310.pyc
ADDED
Binary file (478 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_operations.cpython-310.pyc
ADDED
Binary file (4.42 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_symbol.cpython-310.pyc
ADDED
Binary file (14.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_sympify.cpython-310.pyc
ADDED
Binary file (32 kB). View file
|
|
llmeval-env/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
|
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_arit.py
ADDED
@@ -0,0 +1,2463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
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))
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_assumptions.py
ADDED
@@ -0,0 +1,1335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_basic.py
ADDED
@@ -0,0 +1,319 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
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']
|
llmeval-env/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')
|
llmeval-env/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
|
llmeval-env/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
|
llmeval-env/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 |
+
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
llmeval-env/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
|
llmeval-env/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)
|
llmeval-env/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
|
llmeval-env/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)
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_evalf.py
ADDED
@@ -0,0 +1,732 @@
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)"
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_expand.py
ADDED
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.expr import unchanged
|
2 |
+
from sympy.core.mul import Mul
|
3 |
+
from sympy.core.numbers import (I, Rational as R, pi)
|
4 |
+
from sympy.core.power import Pow
|
5 |
+
from sympy.core.singleton import S
|
6 |
+
from sympy.core.symbol import Symbol
|
7 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
8 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
9 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
10 |
+
from sympy.series.order import O
|
11 |
+
from sympy.simplify.radsimp import expand_numer
|
12 |
+
from sympy.core.function import expand, expand_multinomial, expand_power_base
|
13 |
+
|
14 |
+
from sympy.testing.pytest import raises
|
15 |
+
from sympy.core.random import verify_numerically
|
16 |
+
|
17 |
+
from sympy.abc import x, y, z
|
18 |
+
|
19 |
+
|
20 |
+
def test_expand_no_log():
|
21 |
+
assert (
|
22 |
+
(1 + log(x**4))**2).expand(log=False) == 1 + 2*log(x**4) + log(x**4)**2
|
23 |
+
assert ((1 + log(x**4))*(1 + log(x**3))).expand(
|
24 |
+
log=False) == 1 + log(x**4) + log(x**3) + log(x**4)*log(x**3)
|
25 |
+
|
26 |
+
|
27 |
+
def test_expand_no_multinomial():
|
28 |
+
assert ((1 + x)*(1 + (1 + x)**4)).expand(multinomial=False) == \
|
29 |
+
1 + x + (1 + x)**4 + x*(1 + x)**4
|
30 |
+
|
31 |
+
|
32 |
+
def test_expand_negative_integer_powers():
|
33 |
+
expr = (x + y)**(-2)
|
34 |
+
assert expr.expand() == 1 / (2*x*y + x**2 + y**2)
|
35 |
+
assert expr.expand(multinomial=False) == (x + y)**(-2)
|
36 |
+
expr = (x + y)**(-3)
|
37 |
+
assert expr.expand() == 1 / (3*x*x*y + 3*x*y*y + x**3 + y**3)
|
38 |
+
assert expr.expand(multinomial=False) == (x + y)**(-3)
|
39 |
+
expr = (x + y)**(2) * (x + y)**(-4)
|
40 |
+
assert expr.expand() == 1 / (2*x*y + x**2 + y**2)
|
41 |
+
assert expr.expand(multinomial=False) == (x + y)**(-2)
|
42 |
+
|
43 |
+
|
44 |
+
def test_expand_non_commutative():
|
45 |
+
A = Symbol('A', commutative=False)
|
46 |
+
B = Symbol('B', commutative=False)
|
47 |
+
C = Symbol('C', commutative=False)
|
48 |
+
a = Symbol('a')
|
49 |
+
b = Symbol('b')
|
50 |
+
i = Symbol('i', integer=True)
|
51 |
+
n = Symbol('n', negative=True)
|
52 |
+
m = Symbol('m', negative=True)
|
53 |
+
p = Symbol('p', polar=True)
|
54 |
+
np = Symbol('p', polar=False)
|
55 |
+
|
56 |
+
assert (C*(A + B)).expand() == C*A + C*B
|
57 |
+
assert (C*(A + B)).expand() != A*C + B*C
|
58 |
+
assert ((A + B)**2).expand() == A**2 + A*B + B*A + B**2
|
59 |
+
assert ((A + B)**3).expand() == (A**2*B + B**2*A + A*B**2 + B*A**2 +
|
60 |
+
A**3 + B**3 + A*B*A + B*A*B)
|
61 |
+
# issue 6219
|
62 |
+
assert ((a*A*B*A**-1)**2).expand() == a**2*A*B**2/A
|
63 |
+
# Note that (a*A*B*A**-1)**2 is automatically converted to a**2*(A*B*A**-1)**2
|
64 |
+
assert ((a*A*B*A**-1)**2).expand(deep=False) == a**2*(A*B*A**-1)**2
|
65 |
+
assert ((a*A*B*A**-1)**2).expand() == a**2*(A*B**2*A**-1)
|
66 |
+
assert ((a*A*B*A**-1)**2).expand(force=True) == a**2*A*B**2*A**(-1)
|
67 |
+
assert ((a*A*B)**2).expand() == a**2*A*B*A*B
|
68 |
+
assert ((a*A)**2).expand() == a**2*A**2
|
69 |
+
assert ((a*A*B)**i).expand() == a**i*(A*B)**i
|
70 |
+
assert ((a*A*(B*(A*B/A)**2))**i).expand() == a**i*(A*B*A*B**2/A)**i
|
71 |
+
# issue 6558
|
72 |
+
assert (A*B*(A*B)**-1).expand() == 1
|
73 |
+
assert ((a*A)**i).expand() == a**i*A**i
|
74 |
+
assert ((a*A*B*A**-1)**3).expand() == a**3*A*B**3/A
|
75 |
+
assert ((a*A*B*A*B/A)**3).expand() == \
|
76 |
+
a**3*A*B*(A*B**2)*(A*B**2)*A*B*A**(-1)
|
77 |
+
assert ((a*A*B*A*B/A)**-2).expand() == \
|
78 |
+
A*B**-1*A**-1*B**-2*A**-1*B**-1*A**-1/a**2
|
79 |
+
assert ((a*b*A*B*A**-1)**i).expand() == a**i*b**i*(A*B/A)**i
|
80 |
+
assert ((a*(a*b)**i)**i).expand() == a**i*a**(i**2)*b**(i**2)
|
81 |
+
e = Pow(Mul(a, 1/a, A, B, evaluate=False), S(2), evaluate=False)
|
82 |
+
assert e.expand() == A*B*A*B
|
83 |
+
assert sqrt(a*(A*b)**i).expand() == sqrt(a*b**i*A**i)
|
84 |
+
assert (sqrt(-a)**a).expand() == sqrt(-a)**a
|
85 |
+
assert expand((-2*n)**(i/3)) == 2**(i/3)*(-n)**(i/3)
|
86 |
+
assert expand((-2*n*m)**(i/a)) == (-2)**(i/a)*(-n)**(i/a)*(-m)**(i/a)
|
87 |
+
assert expand((-2*a*p)**b) == 2**b*p**b*(-a)**b
|
88 |
+
assert expand((-2*a*np)**b) == 2**b*(-a*np)**b
|
89 |
+
assert expand(sqrt(A*B)) == sqrt(A*B)
|
90 |
+
assert expand(sqrt(-2*a*b)) == sqrt(2)*sqrt(-a*b)
|
91 |
+
|
92 |
+
|
93 |
+
def test_expand_radicals():
|
94 |
+
a = (x + y)**R(1, 2)
|
95 |
+
|
96 |
+
assert (a**1).expand() == a
|
97 |
+
assert (a**3).expand() == x*a + y*a
|
98 |
+
assert (a**5).expand() == x**2*a + 2*x*y*a + y**2*a
|
99 |
+
|
100 |
+
assert (1/a**1).expand() == 1/a
|
101 |
+
assert (1/a**3).expand() == 1/(x*a + y*a)
|
102 |
+
assert (1/a**5).expand() == 1/(x**2*a + 2*x*y*a + y**2*a)
|
103 |
+
|
104 |
+
a = (x + y)**R(1, 3)
|
105 |
+
|
106 |
+
assert (a**1).expand() == a
|
107 |
+
assert (a**2).expand() == a**2
|
108 |
+
assert (a**4).expand() == x*a + y*a
|
109 |
+
assert (a**5).expand() == x*a**2 + y*a**2
|
110 |
+
assert (a**7).expand() == x**2*a + 2*x*y*a + y**2*a
|
111 |
+
|
112 |
+
|
113 |
+
def test_expand_modulus():
|
114 |
+
assert ((x + y)**11).expand(modulus=11) == x**11 + y**11
|
115 |
+
assert ((x + sqrt(2)*y)**11).expand(modulus=11) == x**11 + 10*sqrt(2)*y**11
|
116 |
+
assert (x + y/2).expand(modulus=1) == y/2
|
117 |
+
|
118 |
+
raises(ValueError, lambda: ((x + y)**11).expand(modulus=0))
|
119 |
+
raises(ValueError, lambda: ((x + y)**11).expand(modulus=x))
|
120 |
+
|
121 |
+
|
122 |
+
def test_issue_5743():
|
123 |
+
assert (x*sqrt(
|
124 |
+
x + y)*(1 + sqrt(x + y))).expand() == x**2 + x*y + x*sqrt(x + y)
|
125 |
+
assert (x*sqrt(
|
126 |
+
x + y)*(1 + x*sqrt(x + y))).expand() == x**3 + x**2*y + x*sqrt(x + y)
|
127 |
+
|
128 |
+
|
129 |
+
def test_expand_frac():
|
130 |
+
assert expand((x + y)*y/x/(x + 1), frac=True) == \
|
131 |
+
(x*y + y**2)/(x**2 + x)
|
132 |
+
assert expand((x + y)*y/x/(x + 1), numer=True) == \
|
133 |
+
(x*y + y**2)/(x*(x + 1))
|
134 |
+
assert expand((x + y)*y/x/(x + 1), denom=True) == \
|
135 |
+
y*(x + y)/(x**2 + x)
|
136 |
+
eq = (x + 1)**2/y
|
137 |
+
assert expand_numer(eq, multinomial=False) == eq
|
138 |
+
|
139 |
+
|
140 |
+
def test_issue_6121():
|
141 |
+
eq = -I*exp(-3*I*pi/4)/(4*pi**(S(3)/2)*sqrt(x))
|
142 |
+
assert eq.expand(complex=True) # does not give oo recursion
|
143 |
+
eq = -I*exp(-3*I*pi/4)/(4*pi**(R(3, 2))*sqrt(x))
|
144 |
+
assert eq.expand(complex=True) # does not give oo recursion
|
145 |
+
|
146 |
+
|
147 |
+
def test_expand_power_base():
|
148 |
+
assert expand_power_base((x*y*z)**4) == x**4*y**4*z**4
|
149 |
+
assert expand_power_base((x*y*z)**x).is_Pow
|
150 |
+
assert expand_power_base((x*y*z)**x, force=True) == x**x*y**x*z**x
|
151 |
+
assert expand_power_base((x*(y*z)**2)**3) == x**3*y**6*z**6
|
152 |
+
|
153 |
+
assert expand_power_base((sin((x*y)**2)*y)**z).is_Pow
|
154 |
+
assert expand_power_base(
|
155 |
+
(sin((x*y)**2)*y)**z, force=True) == sin((x*y)**2)**z*y**z
|
156 |
+
assert expand_power_base(
|
157 |
+
(sin((x*y)**2)*y)**z, deep=True) == (sin(x**2*y**2)*y)**z
|
158 |
+
|
159 |
+
assert expand_power_base(exp(x)**2) == exp(2*x)
|
160 |
+
assert expand_power_base((exp(x)*exp(y))**2) == exp(2*x)*exp(2*y)
|
161 |
+
|
162 |
+
assert expand_power_base(
|
163 |
+
(exp((x*y)**z)*exp(y))**2) == exp(2*(x*y)**z)*exp(2*y)
|
164 |
+
assert expand_power_base((exp((x*y)**z)*exp(
|
165 |
+
y))**2, deep=True, force=True) == exp(2*x**z*y**z)*exp(2*y)
|
166 |
+
|
167 |
+
assert expand_power_base((exp(x)*exp(y))**z).is_Pow
|
168 |
+
assert expand_power_base(
|
169 |
+
(exp(x)*exp(y))**z, force=True) == exp(x)**z*exp(y)**z
|
170 |
+
|
171 |
+
|
172 |
+
def test_expand_arit():
|
173 |
+
a = Symbol("a")
|
174 |
+
b = Symbol("b", positive=True)
|
175 |
+
c = Symbol("c")
|
176 |
+
|
177 |
+
p = R(5)
|
178 |
+
e = (a + b)*c
|
179 |
+
assert e == c*(a + b)
|
180 |
+
assert (e.expand() - a*c - b*c) == R(0)
|
181 |
+
e = (a + b)*(a + b)
|
182 |
+
assert e == (a + b)**2
|
183 |
+
assert e.expand() == 2*a*b + a**2 + b**2
|
184 |
+
e = (a + b)*(a + b)**R(2)
|
185 |
+
assert e == (a + b)**3
|
186 |
+
assert e.expand() == 3*b*a**2 + 3*a*b**2 + a**3 + b**3
|
187 |
+
assert e.expand() == 3*b*a**2 + 3*a*b**2 + a**3 + b**3
|
188 |
+
e = (a + b)*(a + c)*(b + c)
|
189 |
+
assert e == (a + c)*(a + b)*(b + c)
|
190 |
+
assert e.expand() == 2*a*b*c + b*a**2 + c*a**2 + b*c**2 + a*c**2 + c*b**2 + a*b**2
|
191 |
+
e = (a + R(1))**p
|
192 |
+
assert e == (1 + a)**5
|
193 |
+
assert e.expand() == 1 + 5*a + 10*a**2 + 10*a**3 + 5*a**4 + a**5
|
194 |
+
e = (a + b + c)*(a + c + p)
|
195 |
+
assert e == (5 + a + c)*(a + b + c)
|
196 |
+
assert e.expand() == 5*a + 5*b + 5*c + 2*a*c + b*c + a*b + a**2 + c**2
|
197 |
+
x = Symbol("x")
|
198 |
+
s = exp(x*x) - 1
|
199 |
+
e = s.nseries(x, 0, 6)/x**2
|
200 |
+
assert e.expand() == 1 + x**2/2 + O(x**4)
|
201 |
+
|
202 |
+
e = (x*(y + z))**(x*(y + z))*(x + y)
|
203 |
+
assert e.expand(power_exp=False, power_base=False) == x*(x*y + x*
|
204 |
+
z)**(x*y + x*z) + y*(x*y + x*z)**(x*y + x*z)
|
205 |
+
assert e.expand(power_exp=False, power_base=False, deep=False) == x* \
|
206 |
+
(x*(y + z))**(x*(y + z)) + y*(x*(y + z))**(x*(y + z))
|
207 |
+
e = x * (x + (y + 1)**2)
|
208 |
+
assert e.expand(deep=False) == x**2 + x*(y + 1)**2
|
209 |
+
e = (x*(y + z))**z
|
210 |
+
assert e.expand(power_base=True, mul=True, deep=True) in [x**z*(y +
|
211 |
+
z)**z, (x*y + x*z)**z]
|
212 |
+
assert ((2*y)**z).expand() == 2**z*y**z
|
213 |
+
p = Symbol('p', positive=True)
|
214 |
+
assert sqrt(-x).expand().is_Pow
|
215 |
+
assert sqrt(-x).expand(force=True) == I*sqrt(x)
|
216 |
+
assert ((2*y*p)**z).expand() == 2**z*p**z*y**z
|
217 |
+
assert ((2*y*p*x)**z).expand() == 2**z*p**z*(x*y)**z
|
218 |
+
assert ((2*y*p*x)**z).expand(force=True) == 2**z*p**z*x**z*y**z
|
219 |
+
assert ((2*y*p*-pi)**z).expand() == 2**z*pi**z*p**z*(-y)**z
|
220 |
+
assert ((2*y*p*-pi*x)**z).expand() == 2**z*pi**z*p**z*(-x*y)**z
|
221 |
+
n = Symbol('n', negative=True)
|
222 |
+
m = Symbol('m', negative=True)
|
223 |
+
assert ((-2*x*y*n)**z).expand() == 2**z*(-n)**z*(x*y)**z
|
224 |
+
assert ((-2*x*y*n*m)**z).expand() == 2**z*(-m)**z*(-n)**z*(-x*y)**z
|
225 |
+
# issue 5482
|
226 |
+
assert sqrt(-2*x*n) == sqrt(2)*sqrt(-n)*sqrt(x)
|
227 |
+
# issue 5605 (2)
|
228 |
+
assert (cos(x + y)**2).expand(trig=True) in [
|
229 |
+
(-sin(x)*sin(y) + cos(x)*cos(y))**2,
|
230 |
+
sin(x)**2*sin(y)**2 - 2*sin(x)*sin(y)*cos(x)*cos(y) + cos(x)**2*cos(y)**2
|
231 |
+
]
|
232 |
+
|
233 |
+
# Check that this isn't too slow
|
234 |
+
x = Symbol('x')
|
235 |
+
W = 1
|
236 |
+
for i in range(1, 21):
|
237 |
+
W = W * (x - i)
|
238 |
+
W = W.expand()
|
239 |
+
assert W.has(-1672280820*x**15)
|
240 |
+
|
241 |
+
def test_expand_mul():
|
242 |
+
# part of issue 20597
|
243 |
+
e = Mul(2, 3, evaluate=False)
|
244 |
+
assert e.expand() == 6
|
245 |
+
|
246 |
+
e = Mul(2, 3, 1/x, evaluate = False)
|
247 |
+
assert e.expand() == 6/x
|
248 |
+
e = Mul(2, R(1, 3), evaluate=False)
|
249 |
+
assert e.expand() == R(2, 3)
|
250 |
+
|
251 |
+
def test_power_expand():
|
252 |
+
"""Test for Pow.expand()"""
|
253 |
+
a = Symbol('a')
|
254 |
+
b = Symbol('b')
|
255 |
+
p = (a + b)**2
|
256 |
+
assert p.expand() == a**2 + b**2 + 2*a*b
|
257 |
+
|
258 |
+
p = (1 + 2*(1 + a))**2
|
259 |
+
assert p.expand() == 9 + 4*(a**2) + 12*a
|
260 |
+
|
261 |
+
p = 2**(a + b)
|
262 |
+
assert p.expand() == 2**a*2**b
|
263 |
+
|
264 |
+
A = Symbol('A', commutative=False)
|
265 |
+
B = Symbol('B', commutative=False)
|
266 |
+
assert (2**(A + B)).expand() == 2**(A + B)
|
267 |
+
assert (A**(a + b)).expand() != A**(a + b)
|
268 |
+
|
269 |
+
|
270 |
+
def test_issues_5919_6830():
|
271 |
+
# issue 5919
|
272 |
+
n = -1 + 1/x
|
273 |
+
z = n/x/(-n)**2 - 1/n/x
|
274 |
+
assert expand(z) == 1/(x**2 - 2*x + 1) - 1/(x - 2 + 1/x) - 1/(-x + 1)
|
275 |
+
|
276 |
+
# issue 6830
|
277 |
+
p = (1 + x)**2
|
278 |
+
assert expand_multinomial((1 + x*p)**2) == (
|
279 |
+
x**2*(x**4 + 4*x**3 + 6*x**2 + 4*x + 1) + 2*x*(x**2 + 2*x + 1) + 1)
|
280 |
+
assert expand_multinomial((1 + (y + x)*p)**2) == (
|
281 |
+
2*((x + y)*(x**2 + 2*x + 1)) + (x**2 + 2*x*y + y**2)*
|
282 |
+
(x**4 + 4*x**3 + 6*x**2 + 4*x + 1) + 1)
|
283 |
+
A = Symbol('A', commutative=False)
|
284 |
+
p = (1 + A)**2
|
285 |
+
assert expand_multinomial((1 + x*p)**2) == (
|
286 |
+
x**2*(1 + 4*A + 6*A**2 + 4*A**3 + A**4) + 2*x*(1 + 2*A + A**2) + 1)
|
287 |
+
assert expand_multinomial((1 + (y + x)*p)**2) == (
|
288 |
+
(x + y)*(1 + 2*A + A**2)*2 + (x**2 + 2*x*y + y**2)*
|
289 |
+
(1 + 4*A + 6*A**2 + 4*A**3 + A**4) + 1)
|
290 |
+
assert expand_multinomial((1 + (y + x)*p)**3) == (
|
291 |
+
(x + y)*(1 + 2*A + A**2)*3 + (x**2 + 2*x*y + y**2)*(1 + 4*A +
|
292 |
+
6*A**2 + 4*A**3 + A**4)*3 + (x**3 + 3*x**2*y + 3*x*y**2 + y**3)*(1 + 6*A
|
293 |
+
+ 15*A**2 + 20*A**3 + 15*A**4 + 6*A**5 + A**6) + 1)
|
294 |
+
# unevaluate powers
|
295 |
+
eq = (Pow((x + 1)*((A + 1)**2), 2, evaluate=False))
|
296 |
+
# - in this case the base is not an Add so no further
|
297 |
+
# expansion is done
|
298 |
+
assert expand_multinomial(eq) == \
|
299 |
+
(x**2 + 2*x + 1)*(1 + 4*A + 6*A**2 + 4*A**3 + A**4)
|
300 |
+
# - but here, the expanded base *is* an Add so it gets expanded
|
301 |
+
eq = (Pow(((A + 1)**2), 2, evaluate=False))
|
302 |
+
assert expand_multinomial(eq) == 1 + 4*A + 6*A**2 + 4*A**3 + A**4
|
303 |
+
|
304 |
+
# coverage
|
305 |
+
def ok(a, b, n):
|
306 |
+
e = (a + I*b)**n
|
307 |
+
return verify_numerically(e, expand_multinomial(e))
|
308 |
+
|
309 |
+
for a in [2, S.Half]:
|
310 |
+
for b in [3, R(1, 3)]:
|
311 |
+
for n in range(2, 6):
|
312 |
+
assert ok(a, b, n)
|
313 |
+
|
314 |
+
assert expand_multinomial((x + 1 + O(z))**2) == \
|
315 |
+
1 + 2*x + x**2 + O(z)
|
316 |
+
assert expand_multinomial((x + 1 + O(z))**3) == \
|
317 |
+
1 + 3*x + 3*x**2 + x**3 + O(z)
|
318 |
+
|
319 |
+
assert expand_multinomial(3**(x + y + 3)) == 27*3**(x + y)
|
320 |
+
|
321 |
+
def test_expand_log():
|
322 |
+
t = Symbol('t', positive=True)
|
323 |
+
# after first expansion, -2*log(2) + log(4); then 0 after second
|
324 |
+
assert expand(log(t**2) - log(t**2/4) - 2*log(2)) == 0
|
325 |
+
|
326 |
+
|
327 |
+
def test_issue_23952():
|
328 |
+
assert (x**(y + z)).expand(force=True) == x**y*x**z
|
329 |
+
one = Symbol('1', integer=True, prime=True, odd=True, positive=True)
|
330 |
+
two = Symbol('2', integer=True, prime=True, even=True)
|
331 |
+
e = two - one
|
332 |
+
for b in (0, x):
|
333 |
+
# 0**e = 0, 0**-e = zoo; but if expanded then nan
|
334 |
+
assert unchanged(Pow, b, e) # power_exp
|
335 |
+
assert unchanged(Pow, b, -e) # power_exp
|
336 |
+
assert unchanged(Pow, b, y - x) # power_exp
|
337 |
+
assert unchanged(Pow, b, 3 - x) # multinomial
|
338 |
+
assert (b**e).expand().is_Pow # power_exp
|
339 |
+
assert (b**-e).expand().is_Pow # power_exp
|
340 |
+
assert (b**(y - x)).expand().is_Pow # power_exp
|
341 |
+
assert (b**(3 - x)).expand().is_Pow # multinomial
|
342 |
+
nn1 = Symbol('nn1', nonnegative=True)
|
343 |
+
nn2 = Symbol('nn2', nonnegative=True)
|
344 |
+
nn3 = Symbol('nn3', nonnegative=True)
|
345 |
+
assert (x**(nn1 + nn2)).expand() == x**nn1*x**nn2
|
346 |
+
assert (x**(-nn1 - nn2)).expand() == x**-nn1*x**-nn2
|
347 |
+
assert unchanged(Pow, x, nn1 + nn2 - nn3)
|
348 |
+
assert unchanged(Pow, x, 1 + nn2 - nn3)
|
349 |
+
assert unchanged(Pow, x, nn1 - nn2)
|
350 |
+
assert unchanged(Pow, x, 1 - nn2)
|
351 |
+
assert unchanged(Pow, x, -1 + nn2)
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_expr.py
ADDED
@@ -0,0 +1,2261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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'
|
llmeval-env/lib/python3.10/site-packages/sympy/core/tests/test_exprtools.py
ADDED
@@ -0,0 +1,493 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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]
|