Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step80/zero/19.mlp.dense_h_to_4h.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/19.mlp.dense_h_to_4h.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/19.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/20.attention.query_key_value.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/20.attention.query_key_value.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/sympy/functions/__init__.py +111 -0
- venv/lib/python3.10/site-packages/sympy/functions/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/combinatorial/__init__.py +1 -0
- venv/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/factorials.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/numbers.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/combinatorial/factorials.py +1102 -0
- venv/lib/python3.10/site-packages/sympy/functions/combinatorial/numbers.py +2563 -0
- venv/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_factorials.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_numbers.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/test_comb_factorials.py +650 -0
- venv/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/test_comb_numbers.py +852 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/__init__.py +1 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/_trigonometric_special.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/complexes.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/exponential.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/hyperbolic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/integers.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/miscellaneous.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/piecewise.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/trigonometric.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/_trigonometric_special.py +260 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__init__.py +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__pycache__/bench_exp.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/bench_exp.py +11 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/complexes.py +1465 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/exponential.py +1291 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/hyperbolic.py +2203 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/integers.py +625 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/miscellaneous.py +915 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/piecewise.py +1506 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_complexes.py +1018 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_exponential.py +806 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_interface.py +72 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_miscellaneous.py +504 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_piecewise.py +1606 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_trigonometric.py +2162 -0
- venv/lib/python3.10/site-packages/sympy/functions/elementary/trigonometric.py +0 -0
- venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/autowrap.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/codegen.cpython-310.pyc +0 -0
ckpts/universal/global_step80/zero/19.mlp.dense_h_to_4h.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:65325841ace746095a42cb0973ae0886fbdf232b11b0430dcaf6f4253e024b75
|
3 |
+
size 33555612
|
ckpts/universal/global_step80/zero/19.mlp.dense_h_to_4h.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b47a1ddf85d80386dfa5be84824e9cdfd04a71431ff8e9e92648b269590005dd
|
3 |
+
size 33555627
|
ckpts/universal/global_step80/zero/19.mlp.dense_h_to_4h.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:723945f54943cf3bfdaa9d28eac61b9d93d852a8ada701cba480b944a03edf0c
|
3 |
+
size 33555533
|
ckpts/universal/global_step80/zero/20.attention.query_key_value.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c271831d89c4e9a0919352e8eebc2f9a08f79494c64bc5270ebb78afaf6d2e8c
|
3 |
+
size 50332843
|
ckpts/universal/global_step80/zero/20.attention.query_key_value.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3738898faac1afab19d8c6bbe4ef7585910bd9cf1bf8dce7d925d7e26e7ac25f
|
3 |
+
size 50332749
|
venv/lib/python3.10/site-packages/sympy/functions/__init__.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""A functions module, includes all the standard functions.
|
2 |
+
|
3 |
+
Combinatorial - factorial, fibonacci, harmonic, bernoulli...
|
4 |
+
Elementary - hyperbolic, trigonometric, exponential, floor and ceiling, sqrt...
|
5 |
+
Special - gamma, zeta,spherical harmonics...
|
6 |
+
"""
|
7 |
+
|
8 |
+
from sympy.functions.combinatorial.factorials import (factorial, factorial2,
|
9 |
+
rf, ff, binomial, RisingFactorial, FallingFactorial, subfactorial)
|
10 |
+
from sympy.functions.combinatorial.numbers import (carmichael, fibonacci, lucas, tribonacci,
|
11 |
+
harmonic, bernoulli, bell, euler, catalan, genocchi, andre, partition, motzkin)
|
12 |
+
from sympy.functions.elementary.miscellaneous import (sqrt, root, Min, Max,
|
13 |
+
Id, real_root, cbrt, Rem)
|
14 |
+
from sympy.functions.elementary.complexes import (re, im, sign, Abs,
|
15 |
+
conjugate, arg, polar_lift, periodic_argument, unbranched_argument,
|
16 |
+
principal_branch, transpose, adjoint, polarify, unpolarify)
|
17 |
+
from sympy.functions.elementary.trigonometric import (sin, cos, tan,
|
18 |
+
sec, csc, cot, sinc, asin, acos, atan, asec, acsc, acot, atan2)
|
19 |
+
from sympy.functions.elementary.exponential import (exp_polar, exp, log,
|
20 |
+
LambertW)
|
21 |
+
from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth,
|
22 |
+
sech, csch, asinh, acosh, atanh, acoth, asech, acsch)
|
23 |
+
from sympy.functions.elementary.integers import floor, ceiling, frac
|
24 |
+
from sympy.functions.elementary.piecewise import (Piecewise, piecewise_fold,
|
25 |
+
piecewise_exclusive)
|
26 |
+
from sympy.functions.special.error_functions import (erf, erfc, erfi, erf2,
|
27 |
+
erfinv, erfcinv, erf2inv, Ei, expint, E1, li, Li, Si, Ci, Shi, Chi,
|
28 |
+
fresnels, fresnelc)
|
29 |
+
from sympy.functions.special.gamma_functions import (gamma, lowergamma,
|
30 |
+
uppergamma, polygamma, loggamma, digamma, trigamma, multigamma)
|
31 |
+
from sympy.functions.special.zeta_functions import (dirichlet_eta, zeta,
|
32 |
+
lerchphi, polylog, stieltjes, riemann_xi)
|
33 |
+
from sympy.functions.special.tensor_functions import (Eijk, LeviCivita,
|
34 |
+
KroneckerDelta)
|
35 |
+
from sympy.functions.special.singularity_functions import SingularityFunction
|
36 |
+
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
|
37 |
+
from sympy.functions.special.bsplines import bspline_basis, bspline_basis_set, interpolating_spline
|
38 |
+
from sympy.functions.special.bessel import (besselj, bessely, besseli, besselk,
|
39 |
+
hankel1, hankel2, jn, yn, jn_zeros, hn1, hn2, airyai, airybi, airyaiprime, airybiprime, marcumq)
|
40 |
+
from sympy.functions.special.hyper import hyper, meijerg, appellf1
|
41 |
+
from sympy.functions.special.polynomials import (legendre, assoc_legendre,
|
42 |
+
hermite, hermite_prob, chebyshevt, chebyshevu, chebyshevu_root,
|
43 |
+
chebyshevt_root, laguerre, assoc_laguerre, gegenbauer, jacobi, jacobi_normalized)
|
44 |
+
from sympy.functions.special.spherical_harmonics import Ynm, Ynm_c, Znm
|
45 |
+
from sympy.functions.special.elliptic_integrals import (elliptic_k,
|
46 |
+
elliptic_f, elliptic_e, elliptic_pi)
|
47 |
+
from sympy.functions.special.beta_functions import beta, betainc, betainc_regularized
|
48 |
+
from sympy.functions.special.mathieu_functions import (mathieus, mathieuc,
|
49 |
+
mathieusprime, mathieucprime)
|
50 |
+
ln = log
|
51 |
+
|
52 |
+
__all__ = [
|
53 |
+
'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial',
|
54 |
+
'FallingFactorial', 'subfactorial',
|
55 |
+
|
56 |
+
'carmichael', 'fibonacci', 'lucas', 'motzkin', 'tribonacci', 'harmonic',
|
57 |
+
'bernoulli', 'bell', 'euler', 'catalan', 'genocchi', 'andre', 'partition',
|
58 |
+
|
59 |
+
'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root', 'cbrt', 'Rem',
|
60 |
+
|
61 |
+
're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift',
|
62 |
+
'periodic_argument', 'unbranched_argument', 'principal_branch',
|
63 |
+
'transpose', 'adjoint', 'polarify', 'unpolarify',
|
64 |
+
|
65 |
+
'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan',
|
66 |
+
'asec', 'acsc', 'acot', 'atan2',
|
67 |
+
|
68 |
+
'exp_polar', 'exp', 'ln', 'log', 'LambertW',
|
69 |
+
|
70 |
+
'sinh', 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh',
|
71 |
+
'acoth', 'asech', 'acsch',
|
72 |
+
|
73 |
+
'floor', 'ceiling', 'frac',
|
74 |
+
|
75 |
+
'Piecewise', 'piecewise_fold', 'piecewise_exclusive',
|
76 |
+
|
77 |
+
'erf', 'erfc', 'erfi', 'erf2', 'erfinv', 'erfcinv', 'erf2inv', 'Ei',
|
78 |
+
'expint', 'E1', 'li', 'Li', 'Si', 'Ci', 'Shi', 'Chi', 'fresnels',
|
79 |
+
'fresnelc',
|
80 |
+
|
81 |
+
'gamma', 'lowergamma', 'uppergamma', 'polygamma', 'loggamma', 'digamma',
|
82 |
+
'trigamma', 'multigamma',
|
83 |
+
|
84 |
+
'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'riemann_xi',
|
85 |
+
|
86 |
+
'Eijk', 'LeviCivita', 'KroneckerDelta',
|
87 |
+
|
88 |
+
'SingularityFunction',
|
89 |
+
|
90 |
+
'DiracDelta', 'Heaviside',
|
91 |
+
|
92 |
+
'bspline_basis', 'bspline_basis_set', 'interpolating_spline',
|
93 |
+
|
94 |
+
'besselj', 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn',
|
95 |
+
'yn', 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime',
|
96 |
+
'airybiprime', 'marcumq',
|
97 |
+
|
98 |
+
'hyper', 'meijerg', 'appellf1',
|
99 |
+
|
100 |
+
'legendre', 'assoc_legendre', 'hermite', 'hermite_prob', 'chebyshevt',
|
101 |
+
'chebyshevu', 'chebyshevu_root', 'chebyshevt_root', 'laguerre',
|
102 |
+
'assoc_laguerre', 'gegenbauer', 'jacobi', 'jacobi_normalized',
|
103 |
+
|
104 |
+
'Ynm', 'Ynm_c', 'Znm',
|
105 |
+
|
106 |
+
'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi',
|
107 |
+
|
108 |
+
'beta', 'betainc', 'betainc_regularized',
|
109 |
+
|
110 |
+
'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime',
|
111 |
+
]
|
venv/lib/python3.10/site-packages/sympy/functions/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (5.53 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/combinatorial/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
# Stub __init__.py for sympy.functions.combinatorial
|
venv/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (197 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/factorials.cpython-310.pyc
ADDED
Binary file (30.5 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/numbers.cpython-310.pyc
ADDED
Binary file (77 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/combinatorial/factorials.py
ADDED
@@ -0,0 +1,1102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
from functools import reduce
|
3 |
+
|
4 |
+
from sympy.core import S, sympify, Dummy, Mod
|
5 |
+
from sympy.core.cache import cacheit
|
6 |
+
from sympy.core.function import Function, ArgumentIndexError, PoleError
|
7 |
+
from sympy.core.logic import fuzzy_and
|
8 |
+
from sympy.core.numbers import Integer, pi, I
|
9 |
+
from sympy.core.relational import Eq
|
10 |
+
from sympy.external.gmpy import HAS_GMPY, gmpy
|
11 |
+
from sympy.ntheory import sieve
|
12 |
+
from sympy.polys.polytools import Poly
|
13 |
+
|
14 |
+
from math import factorial as _factorial, prod, sqrt as _sqrt
|
15 |
+
|
16 |
+
class CombinatorialFunction(Function):
|
17 |
+
"""Base class for combinatorial functions. """
|
18 |
+
|
19 |
+
def _eval_simplify(self, **kwargs):
|
20 |
+
from sympy.simplify.combsimp import combsimp
|
21 |
+
# combinatorial function with non-integer arguments is
|
22 |
+
# automatically passed to gammasimp
|
23 |
+
expr = combsimp(self)
|
24 |
+
measure = kwargs['measure']
|
25 |
+
if measure(expr) <= kwargs['ratio']*measure(self):
|
26 |
+
return expr
|
27 |
+
return self
|
28 |
+
|
29 |
+
|
30 |
+
###############################################################################
|
31 |
+
######################## FACTORIAL and MULTI-FACTORIAL ########################
|
32 |
+
###############################################################################
|
33 |
+
|
34 |
+
|
35 |
+
class factorial(CombinatorialFunction):
|
36 |
+
r"""Implementation of factorial function over nonnegative integers.
|
37 |
+
By convention (consistent with the gamma function and the binomial
|
38 |
+
coefficients), factorial of a negative integer is complex infinity.
|
39 |
+
|
40 |
+
The factorial is very important in combinatorics where it gives
|
41 |
+
the number of ways in which `n` objects can be permuted. It also
|
42 |
+
arises in calculus, probability, number theory, etc.
|
43 |
+
|
44 |
+
There is strict relation of factorial with gamma function. In
|
45 |
+
fact `n! = gamma(n+1)` for nonnegative integers. Rewrite of this
|
46 |
+
kind is very useful in case of combinatorial simplification.
|
47 |
+
|
48 |
+
Computation of the factorial is done using two algorithms. For
|
49 |
+
small arguments a precomputed look up table is used. However for bigger
|
50 |
+
input algorithm Prime-Swing is used. It is the fastest algorithm
|
51 |
+
known and computes `n!` via prime factorization of special class
|
52 |
+
of numbers, called here the 'Swing Numbers'.
|
53 |
+
|
54 |
+
Examples
|
55 |
+
========
|
56 |
+
|
57 |
+
>>> from sympy import Symbol, factorial, S
|
58 |
+
>>> n = Symbol('n', integer=True)
|
59 |
+
|
60 |
+
>>> factorial(0)
|
61 |
+
1
|
62 |
+
|
63 |
+
>>> factorial(7)
|
64 |
+
5040
|
65 |
+
|
66 |
+
>>> factorial(-2)
|
67 |
+
zoo
|
68 |
+
|
69 |
+
>>> factorial(n)
|
70 |
+
factorial(n)
|
71 |
+
|
72 |
+
>>> factorial(2*n)
|
73 |
+
factorial(2*n)
|
74 |
+
|
75 |
+
>>> factorial(S(1)/2)
|
76 |
+
factorial(1/2)
|
77 |
+
|
78 |
+
See Also
|
79 |
+
========
|
80 |
+
|
81 |
+
factorial2, RisingFactorial, FallingFactorial
|
82 |
+
"""
|
83 |
+
|
84 |
+
def fdiff(self, argindex=1):
|
85 |
+
from sympy.functions.special.gamma_functions import (gamma, polygamma)
|
86 |
+
if argindex == 1:
|
87 |
+
return gamma(self.args[0] + 1)*polygamma(0, self.args[0] + 1)
|
88 |
+
else:
|
89 |
+
raise ArgumentIndexError(self, argindex)
|
90 |
+
|
91 |
+
_small_swing = [
|
92 |
+
1, 1, 1, 3, 3, 15, 5, 35, 35, 315, 63, 693, 231, 3003, 429, 6435, 6435, 109395,
|
93 |
+
12155, 230945, 46189, 969969, 88179, 2028117, 676039, 16900975, 1300075,
|
94 |
+
35102025, 5014575, 145422675, 9694845, 300540195, 300540195
|
95 |
+
]
|
96 |
+
|
97 |
+
_small_factorials: list[int] = []
|
98 |
+
|
99 |
+
@classmethod
|
100 |
+
def _swing(cls, n):
|
101 |
+
if n < 33:
|
102 |
+
return cls._small_swing[n]
|
103 |
+
else:
|
104 |
+
N, primes = int(_sqrt(n)), []
|
105 |
+
|
106 |
+
for prime in sieve.primerange(3, N + 1):
|
107 |
+
p, q = 1, n
|
108 |
+
|
109 |
+
while True:
|
110 |
+
q //= prime
|
111 |
+
|
112 |
+
if q > 0:
|
113 |
+
if q & 1 == 1:
|
114 |
+
p *= prime
|
115 |
+
else:
|
116 |
+
break
|
117 |
+
|
118 |
+
if p > 1:
|
119 |
+
primes.append(p)
|
120 |
+
|
121 |
+
for prime in sieve.primerange(N + 1, n//3 + 1):
|
122 |
+
if (n // prime) & 1 == 1:
|
123 |
+
primes.append(prime)
|
124 |
+
|
125 |
+
L_product = prod(sieve.primerange(n//2 + 1, n + 1))
|
126 |
+
R_product = prod(primes)
|
127 |
+
|
128 |
+
return L_product*R_product
|
129 |
+
|
130 |
+
@classmethod
|
131 |
+
def _recursive(cls, n):
|
132 |
+
if n < 2:
|
133 |
+
return 1
|
134 |
+
else:
|
135 |
+
return (cls._recursive(n//2)**2)*cls._swing(n)
|
136 |
+
|
137 |
+
@classmethod
|
138 |
+
def eval(cls, n):
|
139 |
+
n = sympify(n)
|
140 |
+
|
141 |
+
if n.is_Number:
|
142 |
+
if n.is_zero:
|
143 |
+
return S.One
|
144 |
+
elif n is S.Infinity:
|
145 |
+
return S.Infinity
|
146 |
+
elif n.is_Integer:
|
147 |
+
if n.is_negative:
|
148 |
+
return S.ComplexInfinity
|
149 |
+
else:
|
150 |
+
n = n.p
|
151 |
+
|
152 |
+
if n < 20:
|
153 |
+
if not cls._small_factorials:
|
154 |
+
result = 1
|
155 |
+
for i in range(1, 20):
|
156 |
+
result *= i
|
157 |
+
cls._small_factorials.append(result)
|
158 |
+
result = cls._small_factorials[n-1]
|
159 |
+
|
160 |
+
# GMPY factorial is faster, use it when available
|
161 |
+
elif HAS_GMPY:
|
162 |
+
result = gmpy.fac(n)
|
163 |
+
|
164 |
+
else:
|
165 |
+
bits = bin(n).count('1')
|
166 |
+
result = cls._recursive(n)*2**(n - bits)
|
167 |
+
|
168 |
+
return Integer(result)
|
169 |
+
|
170 |
+
def _facmod(self, n, q):
|
171 |
+
res, N = 1, int(_sqrt(n))
|
172 |
+
|
173 |
+
# Exponent of prime p in n! is e_p(n) = [n/p] + [n/p**2] + ...
|
174 |
+
# for p > sqrt(n), e_p(n) < sqrt(n), the primes with [n/p] = m,
|
175 |
+
# occur consecutively and are grouped together in pw[m] for
|
176 |
+
# simultaneous exponentiation at a later stage
|
177 |
+
pw = [1]*N
|
178 |
+
|
179 |
+
m = 2 # to initialize the if condition below
|
180 |
+
for prime in sieve.primerange(2, n + 1):
|
181 |
+
if m > 1:
|
182 |
+
m, y = 0, n // prime
|
183 |
+
while y:
|
184 |
+
m += y
|
185 |
+
y //= prime
|
186 |
+
if m < N:
|
187 |
+
pw[m] = pw[m]*prime % q
|
188 |
+
else:
|
189 |
+
res = res*pow(prime, m, q) % q
|
190 |
+
|
191 |
+
for ex, bs in enumerate(pw):
|
192 |
+
if ex == 0 or bs == 1:
|
193 |
+
continue
|
194 |
+
if bs == 0:
|
195 |
+
return 0
|
196 |
+
res = res*pow(bs, ex, q) % q
|
197 |
+
|
198 |
+
return res
|
199 |
+
|
200 |
+
def _eval_Mod(self, q):
|
201 |
+
n = self.args[0]
|
202 |
+
if n.is_integer and n.is_nonnegative and q.is_integer:
|
203 |
+
aq = abs(q)
|
204 |
+
d = aq - n
|
205 |
+
if d.is_nonpositive:
|
206 |
+
return S.Zero
|
207 |
+
else:
|
208 |
+
isprime = aq.is_prime
|
209 |
+
if d == 1:
|
210 |
+
# Apply Wilson's theorem (if a natural number n > 1
|
211 |
+
# is a prime number, then (n-1)! = -1 mod n) and
|
212 |
+
# its inverse (if n > 4 is a composite number, then
|
213 |
+
# (n-1)! = 0 mod n)
|
214 |
+
if isprime:
|
215 |
+
return -1 % q
|
216 |
+
elif isprime is False and (aq - 6).is_nonnegative:
|
217 |
+
return S.Zero
|
218 |
+
elif n.is_Integer and q.is_Integer:
|
219 |
+
n, d, aq = map(int, (n, d, aq))
|
220 |
+
if isprime and (d - 1 < n):
|
221 |
+
fc = self._facmod(d - 1, aq)
|
222 |
+
fc = pow(fc, aq - 2, aq)
|
223 |
+
if d%2:
|
224 |
+
fc = -fc
|
225 |
+
else:
|
226 |
+
fc = self._facmod(n, aq)
|
227 |
+
|
228 |
+
return fc % q
|
229 |
+
|
230 |
+
def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
|
231 |
+
from sympy.functions.special.gamma_functions import gamma
|
232 |
+
return gamma(n + 1)
|
233 |
+
|
234 |
+
def _eval_rewrite_as_Product(self, n, **kwargs):
|
235 |
+
from sympy.concrete.products import Product
|
236 |
+
if n.is_nonnegative and n.is_integer:
|
237 |
+
i = Dummy('i', integer=True)
|
238 |
+
return Product(i, (i, 1, n))
|
239 |
+
|
240 |
+
def _eval_is_integer(self):
|
241 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
242 |
+
return True
|
243 |
+
|
244 |
+
def _eval_is_positive(self):
|
245 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
246 |
+
return True
|
247 |
+
|
248 |
+
def _eval_is_even(self):
|
249 |
+
x = self.args[0]
|
250 |
+
if x.is_integer and x.is_nonnegative:
|
251 |
+
return (x - 2).is_nonnegative
|
252 |
+
|
253 |
+
def _eval_is_composite(self):
|
254 |
+
x = self.args[0]
|
255 |
+
if x.is_integer and x.is_nonnegative:
|
256 |
+
return (x - 3).is_nonnegative
|
257 |
+
|
258 |
+
def _eval_is_real(self):
|
259 |
+
x = self.args[0]
|
260 |
+
if x.is_nonnegative or x.is_noninteger:
|
261 |
+
return True
|
262 |
+
|
263 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
264 |
+
arg = self.args[0].as_leading_term(x)
|
265 |
+
arg0 = arg.subs(x, 0)
|
266 |
+
if arg0.is_zero:
|
267 |
+
return S.One
|
268 |
+
elif not arg0.is_infinite:
|
269 |
+
return self.func(arg)
|
270 |
+
raise PoleError("Cannot expand %s around 0" % (self))
|
271 |
+
|
272 |
+
class MultiFactorial(CombinatorialFunction):
|
273 |
+
pass
|
274 |
+
|
275 |
+
|
276 |
+
class subfactorial(CombinatorialFunction):
|
277 |
+
r"""The subfactorial counts the derangements of $n$ items and is
|
278 |
+
defined for non-negative integers as:
|
279 |
+
|
280 |
+
.. math:: !n = \begin{cases} 1 & n = 0 \\ 0 & n = 1 \\
|
281 |
+
(n-1)(!(n-1) + !(n-2)) & n > 1 \end{cases}
|
282 |
+
|
283 |
+
It can also be written as ``int(round(n!/exp(1)))`` but the
|
284 |
+
recursive definition with caching is implemented for this function.
|
285 |
+
|
286 |
+
An interesting analytic expression is the following [2]_
|
287 |
+
|
288 |
+
.. math:: !x = \Gamma(x + 1, -1)/e
|
289 |
+
|
290 |
+
which is valid for non-negative integers `x`. The above formula
|
291 |
+
is not very useful in case of non-integers. `\Gamma(x + 1, -1)` is
|
292 |
+
single-valued only for integral arguments `x`, elsewhere on the positive
|
293 |
+
real axis it has an infinite number of branches none of which are real.
|
294 |
+
|
295 |
+
References
|
296 |
+
==========
|
297 |
+
|
298 |
+
.. [1] https://en.wikipedia.org/wiki/Subfactorial
|
299 |
+
.. [2] https://mathworld.wolfram.com/Subfactorial.html
|
300 |
+
|
301 |
+
Examples
|
302 |
+
========
|
303 |
+
|
304 |
+
>>> from sympy import subfactorial
|
305 |
+
>>> from sympy.abc import n
|
306 |
+
>>> subfactorial(n + 1)
|
307 |
+
subfactorial(n + 1)
|
308 |
+
>>> subfactorial(5)
|
309 |
+
44
|
310 |
+
|
311 |
+
See Also
|
312 |
+
========
|
313 |
+
|
314 |
+
factorial, uppergamma,
|
315 |
+
sympy.utilities.iterables.generate_derangements
|
316 |
+
"""
|
317 |
+
|
318 |
+
@classmethod
|
319 |
+
@cacheit
|
320 |
+
def _eval(self, n):
|
321 |
+
if not n:
|
322 |
+
return S.One
|
323 |
+
elif n == 1:
|
324 |
+
return S.Zero
|
325 |
+
else:
|
326 |
+
z1, z2 = 1, 0
|
327 |
+
for i in range(2, n + 1):
|
328 |
+
z1, z2 = z2, (i - 1)*(z2 + z1)
|
329 |
+
return z2
|
330 |
+
|
331 |
+
@classmethod
|
332 |
+
def eval(cls, arg):
|
333 |
+
if arg.is_Number:
|
334 |
+
if arg.is_Integer and arg.is_nonnegative:
|
335 |
+
return cls._eval(arg)
|
336 |
+
elif arg is S.NaN:
|
337 |
+
return S.NaN
|
338 |
+
elif arg is S.Infinity:
|
339 |
+
return S.Infinity
|
340 |
+
|
341 |
+
def _eval_is_even(self):
|
342 |
+
if self.args[0].is_odd and self.args[0].is_nonnegative:
|
343 |
+
return True
|
344 |
+
|
345 |
+
def _eval_is_integer(self):
|
346 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
347 |
+
return True
|
348 |
+
|
349 |
+
def _eval_rewrite_as_factorial(self, arg, **kwargs):
|
350 |
+
from sympy.concrete.summations import summation
|
351 |
+
i = Dummy('i')
|
352 |
+
f = S.NegativeOne**i / factorial(i)
|
353 |
+
return factorial(arg) * summation(f, (i, 0, arg))
|
354 |
+
|
355 |
+
def _eval_rewrite_as_gamma(self, arg, piecewise=True, **kwargs):
|
356 |
+
from sympy.functions.elementary.exponential import exp
|
357 |
+
from sympy.functions.special.gamma_functions import (gamma, lowergamma)
|
358 |
+
return (S.NegativeOne**(arg + 1)*exp(-I*pi*arg)*lowergamma(arg + 1, -1)
|
359 |
+
+ gamma(arg + 1))*exp(-1)
|
360 |
+
|
361 |
+
def _eval_rewrite_as_uppergamma(self, arg, **kwargs):
|
362 |
+
from sympy.functions.special.gamma_functions import uppergamma
|
363 |
+
return uppergamma(arg + 1, -1)/S.Exp1
|
364 |
+
|
365 |
+
def _eval_is_nonnegative(self):
|
366 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
367 |
+
return True
|
368 |
+
|
369 |
+
def _eval_is_odd(self):
|
370 |
+
if self.args[0].is_even and self.args[0].is_nonnegative:
|
371 |
+
return True
|
372 |
+
|
373 |
+
|
374 |
+
class factorial2(CombinatorialFunction):
|
375 |
+
r"""The double factorial `n!!`, not to be confused with `(n!)!`
|
376 |
+
|
377 |
+
The double factorial is defined for nonnegative integers and for odd
|
378 |
+
negative integers as:
|
379 |
+
|
380 |
+
.. math:: n!! = \begin{cases} 1 & n = 0 \\
|
381 |
+
n(n-2)(n-4) \cdots 1 & n\ \text{positive odd} \\
|
382 |
+
n(n-2)(n-4) \cdots 2 & n\ \text{positive even} \\
|
383 |
+
(n+2)!!/(n+2) & n\ \text{negative odd} \end{cases}
|
384 |
+
|
385 |
+
References
|
386 |
+
==========
|
387 |
+
|
388 |
+
.. [1] https://en.wikipedia.org/wiki/Double_factorial
|
389 |
+
|
390 |
+
Examples
|
391 |
+
========
|
392 |
+
|
393 |
+
>>> from sympy import factorial2, var
|
394 |
+
>>> n = var('n')
|
395 |
+
>>> n
|
396 |
+
n
|
397 |
+
>>> factorial2(n + 1)
|
398 |
+
factorial2(n + 1)
|
399 |
+
>>> factorial2(5)
|
400 |
+
15
|
401 |
+
>>> factorial2(-1)
|
402 |
+
1
|
403 |
+
>>> factorial2(-5)
|
404 |
+
1/3
|
405 |
+
|
406 |
+
See Also
|
407 |
+
========
|
408 |
+
|
409 |
+
factorial, RisingFactorial, FallingFactorial
|
410 |
+
"""
|
411 |
+
|
412 |
+
@classmethod
|
413 |
+
def eval(cls, arg):
|
414 |
+
# TODO: extend this to complex numbers?
|
415 |
+
|
416 |
+
if arg.is_Number:
|
417 |
+
if not arg.is_Integer:
|
418 |
+
raise ValueError("argument must be nonnegative integer "
|
419 |
+
"or negative odd integer")
|
420 |
+
|
421 |
+
# This implementation is faster than the recursive one
|
422 |
+
# It also avoids "maximum recursion depth exceeded" runtime error
|
423 |
+
if arg.is_nonnegative:
|
424 |
+
if arg.is_even:
|
425 |
+
k = arg / 2
|
426 |
+
return 2**k * factorial(k)
|
427 |
+
return factorial(arg) / factorial2(arg - 1)
|
428 |
+
|
429 |
+
|
430 |
+
if arg.is_odd:
|
431 |
+
return arg*(S.NegativeOne)**((1 - arg)/2) / factorial2(-arg)
|
432 |
+
raise ValueError("argument must be nonnegative integer "
|
433 |
+
"or negative odd integer")
|
434 |
+
|
435 |
+
|
436 |
+
def _eval_is_even(self):
|
437 |
+
# Double factorial is even for every positive even input
|
438 |
+
n = self.args[0]
|
439 |
+
if n.is_integer:
|
440 |
+
if n.is_odd:
|
441 |
+
return False
|
442 |
+
if n.is_even:
|
443 |
+
if n.is_positive:
|
444 |
+
return True
|
445 |
+
if n.is_zero:
|
446 |
+
return False
|
447 |
+
|
448 |
+
def _eval_is_integer(self):
|
449 |
+
# Double factorial is an integer for every nonnegative input, and for
|
450 |
+
# -1 and -3
|
451 |
+
n = self.args[0]
|
452 |
+
if n.is_integer:
|
453 |
+
if (n + 1).is_nonnegative:
|
454 |
+
return True
|
455 |
+
if n.is_odd:
|
456 |
+
return (n + 3).is_nonnegative
|
457 |
+
|
458 |
+
def _eval_is_odd(self):
|
459 |
+
# Double factorial is odd for every odd input not smaller than -3, and
|
460 |
+
# for 0
|
461 |
+
n = self.args[0]
|
462 |
+
if n.is_odd:
|
463 |
+
return (n + 3).is_nonnegative
|
464 |
+
if n.is_even:
|
465 |
+
if n.is_positive:
|
466 |
+
return False
|
467 |
+
if n.is_zero:
|
468 |
+
return True
|
469 |
+
|
470 |
+
def _eval_is_positive(self):
|
471 |
+
# Double factorial is positive for every nonnegative input, and for
|
472 |
+
# every odd negative input which is of the form -1-4k for an
|
473 |
+
# nonnegative integer k
|
474 |
+
n = self.args[0]
|
475 |
+
if n.is_integer:
|
476 |
+
if (n + 1).is_nonnegative:
|
477 |
+
return True
|
478 |
+
if n.is_odd:
|
479 |
+
return ((n + 1) / 2).is_even
|
480 |
+
|
481 |
+
def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
|
482 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
483 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
484 |
+
from sympy.functions.special.gamma_functions import gamma
|
485 |
+
return 2**(n/2)*gamma(n/2 + 1) * Piecewise((1, Eq(Mod(n, 2), 0)),
|
486 |
+
(sqrt(2/pi), Eq(Mod(n, 2), 1)))
|
487 |
+
|
488 |
+
|
489 |
+
###############################################################################
|
490 |
+
######################## RISING and FALLING FACTORIALS ########################
|
491 |
+
###############################################################################
|
492 |
+
|
493 |
+
|
494 |
+
class RisingFactorial(CombinatorialFunction):
|
495 |
+
r"""
|
496 |
+
Rising factorial (also called Pochhammer symbol [1]_) is a double valued
|
497 |
+
function arising in concrete mathematics, hypergeometric functions
|
498 |
+
and series expansions. It is defined by:
|
499 |
+
|
500 |
+
.. math:: \texttt{rf(y, k)} = (x)^k = x \cdot (x+1) \cdots (x+k-1)
|
501 |
+
|
502 |
+
where `x` can be arbitrary expression and `k` is an integer. For
|
503 |
+
more information check "Concrete mathematics" by Graham, pp. 66
|
504 |
+
or visit https://mathworld.wolfram.com/RisingFactorial.html page.
|
505 |
+
|
506 |
+
When `x` is a `~.Poly` instance of degree $\ge 1$ with a single variable,
|
507 |
+
`(x)^k = x(y) \cdot x(y+1) \cdots x(y+k-1)`, where `y` is the
|
508 |
+
variable of `x`. This is as described in [2]_.
|
509 |
+
|
510 |
+
Examples
|
511 |
+
========
|
512 |
+
|
513 |
+
>>> from sympy import rf, Poly
|
514 |
+
>>> from sympy.abc import x
|
515 |
+
>>> rf(x, 0)
|
516 |
+
1
|
517 |
+
>>> rf(1, 5)
|
518 |
+
120
|
519 |
+
>>> rf(x, 5) == x*(1 + x)*(2 + x)*(3 + x)*(4 + x)
|
520 |
+
True
|
521 |
+
>>> rf(Poly(x**3, x), 2)
|
522 |
+
Poly(x**6 + 3*x**5 + 3*x**4 + x**3, x, domain='ZZ')
|
523 |
+
|
524 |
+
Rewriting is complicated unless the relationship between
|
525 |
+
the arguments is known, but rising factorial can
|
526 |
+
be rewritten in terms of gamma, factorial, binomial,
|
527 |
+
and falling factorial.
|
528 |
+
|
529 |
+
>>> from sympy import Symbol, factorial, ff, binomial, gamma
|
530 |
+
>>> n = Symbol('n', integer=True, positive=True)
|
531 |
+
>>> R = rf(n, n + 2)
|
532 |
+
>>> for i in (rf, ff, factorial, binomial, gamma):
|
533 |
+
... R.rewrite(i)
|
534 |
+
...
|
535 |
+
RisingFactorial(n, n + 2)
|
536 |
+
FallingFactorial(2*n + 1, n + 2)
|
537 |
+
factorial(2*n + 1)/factorial(n - 1)
|
538 |
+
binomial(2*n + 1, n + 2)*factorial(n + 2)
|
539 |
+
gamma(2*n + 2)/gamma(n)
|
540 |
+
|
541 |
+
See Also
|
542 |
+
========
|
543 |
+
|
544 |
+
factorial, factorial2, FallingFactorial
|
545 |
+
|
546 |
+
References
|
547 |
+
==========
|
548 |
+
|
549 |
+
.. [1] https://en.wikipedia.org/wiki/Pochhammer_symbol
|
550 |
+
.. [2] Peter Paule, "Greatest Factorial Factorization and Symbolic
|
551 |
+
Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268,
|
552 |
+
1995.
|
553 |
+
|
554 |
+
"""
|
555 |
+
|
556 |
+
@classmethod
|
557 |
+
def eval(cls, x, k):
|
558 |
+
x = sympify(x)
|
559 |
+
k = sympify(k)
|
560 |
+
|
561 |
+
if x is S.NaN or k is S.NaN:
|
562 |
+
return S.NaN
|
563 |
+
elif x is S.One:
|
564 |
+
return factorial(k)
|
565 |
+
elif k.is_Integer:
|
566 |
+
if k.is_zero:
|
567 |
+
return S.One
|
568 |
+
else:
|
569 |
+
if k.is_positive:
|
570 |
+
if x is S.Infinity:
|
571 |
+
return S.Infinity
|
572 |
+
elif x is S.NegativeInfinity:
|
573 |
+
if k.is_odd:
|
574 |
+
return S.NegativeInfinity
|
575 |
+
else:
|
576 |
+
return S.Infinity
|
577 |
+
else:
|
578 |
+
if isinstance(x, Poly):
|
579 |
+
gens = x.gens
|
580 |
+
if len(gens)!= 1:
|
581 |
+
raise ValueError("rf only defined for "
|
582 |
+
"polynomials on one generator")
|
583 |
+
else:
|
584 |
+
return reduce(lambda r, i:
|
585 |
+
r*(x.shift(i)),
|
586 |
+
range(int(k)), 1)
|
587 |
+
else:
|
588 |
+
return reduce(lambda r, i: r*(x + i),
|
589 |
+
range(int(k)), 1)
|
590 |
+
|
591 |
+
else:
|
592 |
+
if x is S.Infinity:
|
593 |
+
return S.Infinity
|
594 |
+
elif x is S.NegativeInfinity:
|
595 |
+
return S.Infinity
|
596 |
+
else:
|
597 |
+
if isinstance(x, Poly):
|
598 |
+
gens = x.gens
|
599 |
+
if len(gens)!= 1:
|
600 |
+
raise ValueError("rf only defined for "
|
601 |
+
"polynomials on one generator")
|
602 |
+
else:
|
603 |
+
return 1/reduce(lambda r, i:
|
604 |
+
r*(x.shift(-i)),
|
605 |
+
range(1, abs(int(k)) + 1), 1)
|
606 |
+
else:
|
607 |
+
return 1/reduce(lambda r, i:
|
608 |
+
r*(x - i),
|
609 |
+
range(1, abs(int(k)) + 1), 1)
|
610 |
+
|
611 |
+
if k.is_integer == False:
|
612 |
+
if x.is_integer and x.is_negative:
|
613 |
+
return S.Zero
|
614 |
+
|
615 |
+
def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs):
|
616 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
617 |
+
from sympy.functions.special.gamma_functions import gamma
|
618 |
+
if not piecewise:
|
619 |
+
if (x <= 0) == True:
|
620 |
+
return S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1)
|
621 |
+
return gamma(x + k) / gamma(x)
|
622 |
+
return Piecewise(
|
623 |
+
(gamma(x + k) / gamma(x), x > 0),
|
624 |
+
(S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1), True))
|
625 |
+
|
626 |
+
def _eval_rewrite_as_FallingFactorial(self, x, k, **kwargs):
|
627 |
+
return FallingFactorial(x + k - 1, k)
|
628 |
+
|
629 |
+
def _eval_rewrite_as_factorial(self, x, k, **kwargs):
|
630 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
631 |
+
if x.is_integer and k.is_integer:
|
632 |
+
return Piecewise(
|
633 |
+
(factorial(k + x - 1)/factorial(x - 1), x > 0),
|
634 |
+
(S.NegativeOne**k*factorial(-x)/factorial(-k - x), True))
|
635 |
+
|
636 |
+
def _eval_rewrite_as_binomial(self, x, k, **kwargs):
|
637 |
+
if k.is_integer:
|
638 |
+
return factorial(k) * binomial(x + k - 1, k)
|
639 |
+
|
640 |
+
def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs):
|
641 |
+
from sympy.functions.special.gamma_functions import gamma
|
642 |
+
if limitvar:
|
643 |
+
k_lim = k.subs(limitvar, S.Infinity)
|
644 |
+
if k_lim is S.Infinity:
|
645 |
+
return (gamma(x + k).rewrite('tractable', deep=True) / gamma(x))
|
646 |
+
elif k_lim is S.NegativeInfinity:
|
647 |
+
return (S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1).rewrite('tractable', deep=True))
|
648 |
+
return self.rewrite(gamma).rewrite('tractable', deep=True)
|
649 |
+
|
650 |
+
def _eval_is_integer(self):
|
651 |
+
return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer,
|
652 |
+
self.args[1].is_nonnegative))
|
653 |
+
|
654 |
+
|
655 |
+
class FallingFactorial(CombinatorialFunction):
|
656 |
+
r"""
|
657 |
+
Falling factorial (related to rising factorial) is a double valued
|
658 |
+
function arising in concrete mathematics, hypergeometric functions
|
659 |
+
and series expansions. It is defined by
|
660 |
+
|
661 |
+
.. math:: \texttt{ff(x, k)} = (x)_k = x \cdot (x-1) \cdots (x-k+1)
|
662 |
+
|
663 |
+
where `x` can be arbitrary expression and `k` is an integer. For
|
664 |
+
more information check "Concrete mathematics" by Graham, pp. 66
|
665 |
+
or [1]_.
|
666 |
+
|
667 |
+
When `x` is a `~.Poly` instance of degree $\ge 1$ with single variable,
|
668 |
+
`(x)_k = x(y) \cdot x(y-1) \cdots x(y-k+1)`, where `y` is the
|
669 |
+
variable of `x`. This is as described in
|
670 |
+
|
671 |
+
>>> from sympy import ff, Poly, Symbol
|
672 |
+
>>> from sympy.abc import x
|
673 |
+
>>> n = Symbol('n', integer=True)
|
674 |
+
|
675 |
+
>>> ff(x, 0)
|
676 |
+
1
|
677 |
+
>>> ff(5, 5)
|
678 |
+
120
|
679 |
+
>>> ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4)
|
680 |
+
True
|
681 |
+
>>> ff(Poly(x**2, x), 2)
|
682 |
+
Poly(x**4 - 2*x**3 + x**2, x, domain='ZZ')
|
683 |
+
>>> ff(n, n)
|
684 |
+
factorial(n)
|
685 |
+
|
686 |
+
Rewriting is complicated unless the relationship between
|
687 |
+
the arguments is known, but falling factorial can
|
688 |
+
be rewritten in terms of gamma, factorial and binomial
|
689 |
+
and rising factorial.
|
690 |
+
|
691 |
+
>>> from sympy import factorial, rf, gamma, binomial, Symbol
|
692 |
+
>>> n = Symbol('n', integer=True, positive=True)
|
693 |
+
>>> F = ff(n, n - 2)
|
694 |
+
>>> for i in (rf, ff, factorial, binomial, gamma):
|
695 |
+
... F.rewrite(i)
|
696 |
+
...
|
697 |
+
RisingFactorial(3, n - 2)
|
698 |
+
FallingFactorial(n, n - 2)
|
699 |
+
factorial(n)/2
|
700 |
+
binomial(n, n - 2)*factorial(n - 2)
|
701 |
+
gamma(n + 1)/2
|
702 |
+
|
703 |
+
See Also
|
704 |
+
========
|
705 |
+
|
706 |
+
factorial, factorial2, RisingFactorial
|
707 |
+
|
708 |
+
References
|
709 |
+
==========
|
710 |
+
|
711 |
+
.. [1] https://mathworld.wolfram.com/FallingFactorial.html
|
712 |
+
.. [2] Peter Paule, "Greatest Factorial Factorization and Symbolic
|
713 |
+
Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268,
|
714 |
+
1995.
|
715 |
+
|
716 |
+
"""
|
717 |
+
|
718 |
+
@classmethod
|
719 |
+
def eval(cls, x, k):
|
720 |
+
x = sympify(x)
|
721 |
+
k = sympify(k)
|
722 |
+
|
723 |
+
if x is S.NaN or k is S.NaN:
|
724 |
+
return S.NaN
|
725 |
+
elif k.is_integer and x == k:
|
726 |
+
return factorial(x)
|
727 |
+
elif k.is_Integer:
|
728 |
+
if k.is_zero:
|
729 |
+
return S.One
|
730 |
+
else:
|
731 |
+
if k.is_positive:
|
732 |
+
if x is S.Infinity:
|
733 |
+
return S.Infinity
|
734 |
+
elif x is S.NegativeInfinity:
|
735 |
+
if k.is_odd:
|
736 |
+
return S.NegativeInfinity
|
737 |
+
else:
|
738 |
+
return S.Infinity
|
739 |
+
else:
|
740 |
+
if isinstance(x, Poly):
|
741 |
+
gens = x.gens
|
742 |
+
if len(gens)!= 1:
|
743 |
+
raise ValueError("ff only defined for "
|
744 |
+
"polynomials on one generator")
|
745 |
+
else:
|
746 |
+
return reduce(lambda r, i:
|
747 |
+
r*(x.shift(-i)),
|
748 |
+
range(int(k)), 1)
|
749 |
+
else:
|
750 |
+
return reduce(lambda r, i: r*(x - i),
|
751 |
+
range(int(k)), 1)
|
752 |
+
else:
|
753 |
+
if x is S.Infinity:
|
754 |
+
return S.Infinity
|
755 |
+
elif x is S.NegativeInfinity:
|
756 |
+
return S.Infinity
|
757 |
+
else:
|
758 |
+
if isinstance(x, Poly):
|
759 |
+
gens = x.gens
|
760 |
+
if len(gens)!= 1:
|
761 |
+
raise ValueError("rf only defined for "
|
762 |
+
"polynomials on one generator")
|
763 |
+
else:
|
764 |
+
return 1/reduce(lambda r, i:
|
765 |
+
r*(x.shift(i)),
|
766 |
+
range(1, abs(int(k)) + 1), 1)
|
767 |
+
else:
|
768 |
+
return 1/reduce(lambda r, i: r*(x + i),
|
769 |
+
range(1, abs(int(k)) + 1), 1)
|
770 |
+
|
771 |
+
def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs):
|
772 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
773 |
+
from sympy.functions.special.gamma_functions import gamma
|
774 |
+
if not piecewise:
|
775 |
+
if (x < 0) == True:
|
776 |
+
return S.NegativeOne**k*gamma(k - x) / gamma(-x)
|
777 |
+
return gamma(x + 1) / gamma(x - k + 1)
|
778 |
+
return Piecewise(
|
779 |
+
(gamma(x + 1) / gamma(x - k + 1), x >= 0),
|
780 |
+
(S.NegativeOne**k*gamma(k - x) / gamma(-x), True))
|
781 |
+
|
782 |
+
def _eval_rewrite_as_RisingFactorial(self, x, k, **kwargs):
|
783 |
+
return rf(x - k + 1, k)
|
784 |
+
|
785 |
+
def _eval_rewrite_as_binomial(self, x, k, **kwargs):
|
786 |
+
if k.is_integer:
|
787 |
+
return factorial(k) * binomial(x, k)
|
788 |
+
|
789 |
+
def _eval_rewrite_as_factorial(self, x, k, **kwargs):
|
790 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
791 |
+
if x.is_integer and k.is_integer:
|
792 |
+
return Piecewise(
|
793 |
+
(factorial(x)/factorial(-k + x), x >= 0),
|
794 |
+
(S.NegativeOne**k*factorial(k - x - 1)/factorial(-x - 1), True))
|
795 |
+
|
796 |
+
def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs):
|
797 |
+
from sympy.functions.special.gamma_functions import gamma
|
798 |
+
if limitvar:
|
799 |
+
k_lim = k.subs(limitvar, S.Infinity)
|
800 |
+
if k_lim is S.Infinity:
|
801 |
+
return (S.NegativeOne**k*gamma(k - x).rewrite('tractable', deep=True) / gamma(-x))
|
802 |
+
elif k_lim is S.NegativeInfinity:
|
803 |
+
return (gamma(x + 1) / gamma(x - k + 1).rewrite('tractable', deep=True))
|
804 |
+
return self.rewrite(gamma).rewrite('tractable', deep=True)
|
805 |
+
|
806 |
+
def _eval_is_integer(self):
|
807 |
+
return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer,
|
808 |
+
self.args[1].is_nonnegative))
|
809 |
+
|
810 |
+
|
811 |
+
rf = RisingFactorial
|
812 |
+
ff = FallingFactorial
|
813 |
+
|
814 |
+
###############################################################################
|
815 |
+
########################### BINOMIAL COEFFICIENTS #############################
|
816 |
+
###############################################################################
|
817 |
+
|
818 |
+
|
819 |
+
class binomial(CombinatorialFunction):
|
820 |
+
r"""Implementation of the binomial coefficient. It can be defined
|
821 |
+
in two ways depending on its desired interpretation:
|
822 |
+
|
823 |
+
.. math:: \binom{n}{k} = \frac{n!}{k!(n-k)!}\ \text{or}\
|
824 |
+
\binom{n}{k} = \frac{(n)_k}{k!}
|
825 |
+
|
826 |
+
First, in a strict combinatorial sense it defines the
|
827 |
+
number of ways we can choose `k` elements from a set of
|
828 |
+
`n` elements. In this case both arguments are nonnegative
|
829 |
+
integers and binomial is computed using an efficient
|
830 |
+
algorithm based on prime factorization.
|
831 |
+
|
832 |
+
The other definition is generalization for arbitrary `n`,
|
833 |
+
however `k` must also be nonnegative. This case is very
|
834 |
+
useful when evaluating summations.
|
835 |
+
|
836 |
+
For the sake of convenience, for negative integer `k` this function
|
837 |
+
will return zero no matter the other argument.
|
838 |
+
|
839 |
+
To expand the binomial when `n` is a symbol, use either
|
840 |
+
``expand_func()`` or ``expand(func=True)``. The former will keep
|
841 |
+
the polynomial in factored form while the latter will expand the
|
842 |
+
polynomial itself. See examples for details.
|
843 |
+
|
844 |
+
Examples
|
845 |
+
========
|
846 |
+
|
847 |
+
>>> from sympy import Symbol, Rational, binomial, expand_func
|
848 |
+
>>> n = Symbol('n', integer=True, positive=True)
|
849 |
+
|
850 |
+
>>> binomial(15, 8)
|
851 |
+
6435
|
852 |
+
|
853 |
+
>>> binomial(n, -1)
|
854 |
+
0
|
855 |
+
|
856 |
+
Rows of Pascal's triangle can be generated with the binomial function:
|
857 |
+
|
858 |
+
>>> for N in range(8):
|
859 |
+
... print([binomial(N, i) for i in range(N + 1)])
|
860 |
+
...
|
861 |
+
[1]
|
862 |
+
[1, 1]
|
863 |
+
[1, 2, 1]
|
864 |
+
[1, 3, 3, 1]
|
865 |
+
[1, 4, 6, 4, 1]
|
866 |
+
[1, 5, 10, 10, 5, 1]
|
867 |
+
[1, 6, 15, 20, 15, 6, 1]
|
868 |
+
[1, 7, 21, 35, 35, 21, 7, 1]
|
869 |
+
|
870 |
+
As can a given diagonal, e.g. the 4th diagonal:
|
871 |
+
|
872 |
+
>>> N = -4
|
873 |
+
>>> [binomial(N, i) for i in range(1 - N)]
|
874 |
+
[1, -4, 10, -20, 35]
|
875 |
+
|
876 |
+
>>> binomial(Rational(5, 4), 3)
|
877 |
+
-5/128
|
878 |
+
>>> binomial(Rational(-5, 4), 3)
|
879 |
+
-195/128
|
880 |
+
|
881 |
+
>>> binomial(n, 3)
|
882 |
+
binomial(n, 3)
|
883 |
+
|
884 |
+
>>> binomial(n, 3).expand(func=True)
|
885 |
+
n**3/6 - n**2/2 + n/3
|
886 |
+
|
887 |
+
>>> expand_func(binomial(n, 3))
|
888 |
+
n*(n - 2)*(n - 1)/6
|
889 |
+
|
890 |
+
References
|
891 |
+
==========
|
892 |
+
|
893 |
+
.. [1] https://www.johndcook.com/blog/binomial_coefficients/
|
894 |
+
|
895 |
+
"""
|
896 |
+
|
897 |
+
def fdiff(self, argindex=1):
|
898 |
+
from sympy.functions.special.gamma_functions import polygamma
|
899 |
+
if argindex == 1:
|
900 |
+
# https://functions.wolfram.com/GammaBetaErf/Binomial/20/01/01/
|
901 |
+
n, k = self.args
|
902 |
+
return binomial(n, k)*(polygamma(0, n + 1) - \
|
903 |
+
polygamma(0, n - k + 1))
|
904 |
+
elif argindex == 2:
|
905 |
+
# https://functions.wolfram.com/GammaBetaErf/Binomial/20/01/02/
|
906 |
+
n, k = self.args
|
907 |
+
return binomial(n, k)*(polygamma(0, n - k + 1) - \
|
908 |
+
polygamma(0, k + 1))
|
909 |
+
else:
|
910 |
+
raise ArgumentIndexError(self, argindex)
|
911 |
+
|
912 |
+
@classmethod
|
913 |
+
def _eval(self, n, k):
|
914 |
+
# n.is_Number and k.is_Integer and k != 1 and n != k
|
915 |
+
|
916 |
+
if k.is_Integer:
|
917 |
+
if n.is_Integer and n >= 0:
|
918 |
+
n, k = int(n), int(k)
|
919 |
+
|
920 |
+
if k > n:
|
921 |
+
return S.Zero
|
922 |
+
elif k > n // 2:
|
923 |
+
k = n - k
|
924 |
+
|
925 |
+
if HAS_GMPY:
|
926 |
+
return Integer(gmpy.bincoef(n, k))
|
927 |
+
|
928 |
+
d, result = n - k, 1
|
929 |
+
for i in range(1, k + 1):
|
930 |
+
d += 1
|
931 |
+
result = result * d // i
|
932 |
+
return Integer(result)
|
933 |
+
else:
|
934 |
+
d, result = n - k, 1
|
935 |
+
for i in range(1, k + 1):
|
936 |
+
d += 1
|
937 |
+
result *= d
|
938 |
+
return result / _factorial(k)
|
939 |
+
|
940 |
+
@classmethod
|
941 |
+
def eval(cls, n, k):
|
942 |
+
n, k = map(sympify, (n, k))
|
943 |
+
d = n - k
|
944 |
+
n_nonneg, n_isint = n.is_nonnegative, n.is_integer
|
945 |
+
if k.is_zero or ((n_nonneg or n_isint is False)
|
946 |
+
and d.is_zero):
|
947 |
+
return S.One
|
948 |
+
if (k - 1).is_zero or ((n_nonneg or n_isint is False)
|
949 |
+
and (d - 1).is_zero):
|
950 |
+
return n
|
951 |
+
if k.is_integer:
|
952 |
+
if k.is_negative or (n_nonneg and n_isint and d.is_negative):
|
953 |
+
return S.Zero
|
954 |
+
elif n.is_number:
|
955 |
+
res = cls._eval(n, k)
|
956 |
+
return res.expand(basic=True) if res else res
|
957 |
+
elif n_nonneg is False and n_isint:
|
958 |
+
# a special case when binomial evaluates to complex infinity
|
959 |
+
return S.ComplexInfinity
|
960 |
+
elif k.is_number:
|
961 |
+
from sympy.functions.special.gamma_functions import gamma
|
962 |
+
return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
|
963 |
+
|
964 |
+
def _eval_Mod(self, q):
|
965 |
+
n, k = self.args
|
966 |
+
|
967 |
+
if any(x.is_integer is False for x in (n, k, q)):
|
968 |
+
raise ValueError("Integers expected for binomial Mod")
|
969 |
+
|
970 |
+
if all(x.is_Integer for x in (n, k, q)):
|
971 |
+
n, k = map(int, (n, k))
|
972 |
+
aq, res = abs(q), 1
|
973 |
+
|
974 |
+
# handle negative integers k or n
|
975 |
+
if k < 0:
|
976 |
+
return S.Zero
|
977 |
+
if n < 0:
|
978 |
+
n = -n + k - 1
|
979 |
+
res = -1 if k%2 else 1
|
980 |
+
|
981 |
+
# non negative integers k and n
|
982 |
+
if k > n:
|
983 |
+
return S.Zero
|
984 |
+
|
985 |
+
isprime = aq.is_prime
|
986 |
+
aq = int(aq)
|
987 |
+
if isprime:
|
988 |
+
if aq < n:
|
989 |
+
# use Lucas Theorem
|
990 |
+
N, K = n, k
|
991 |
+
while N or K:
|
992 |
+
res = res*binomial(N % aq, K % aq) % aq
|
993 |
+
N, K = N // aq, K // aq
|
994 |
+
|
995 |
+
else:
|
996 |
+
# use Factorial Modulo
|
997 |
+
d = n - k
|
998 |
+
if k > d:
|
999 |
+
k, d = d, k
|
1000 |
+
kf = 1
|
1001 |
+
for i in range(2, k + 1):
|
1002 |
+
kf = kf*i % aq
|
1003 |
+
df = kf
|
1004 |
+
for i in range(k + 1, d + 1):
|
1005 |
+
df = df*i % aq
|
1006 |
+
res *= df
|
1007 |
+
for i in range(d + 1, n + 1):
|
1008 |
+
res = res*i % aq
|
1009 |
+
|
1010 |
+
res *= pow(kf*df % aq, aq - 2, aq)
|
1011 |
+
res %= aq
|
1012 |
+
|
1013 |
+
else:
|
1014 |
+
# Binomial Factorization is performed by calculating the
|
1015 |
+
# exponents of primes <= n in `n! /(k! (n - k)!)`,
|
1016 |
+
# for non-negative integers n and k. As the exponent of
|
1017 |
+
# prime in n! is e_p(n) = [n/p] + [n/p**2] + ...
|
1018 |
+
# the exponent of prime in binomial(n, k) would be
|
1019 |
+
# e_p(n) - e_p(k) - e_p(n - k)
|
1020 |
+
M = int(_sqrt(n))
|
1021 |
+
for prime in sieve.primerange(2, n + 1):
|
1022 |
+
if prime > n - k:
|
1023 |
+
res = res*prime % aq
|
1024 |
+
elif prime > n // 2:
|
1025 |
+
continue
|
1026 |
+
elif prime > M:
|
1027 |
+
if n % prime < k % prime:
|
1028 |
+
res = res*prime % aq
|
1029 |
+
else:
|
1030 |
+
N, K = n, k
|
1031 |
+
exp = a = 0
|
1032 |
+
|
1033 |
+
while N > 0:
|
1034 |
+
a = int((N % prime) < (K % prime + a))
|
1035 |
+
N, K = N // prime, K // prime
|
1036 |
+
exp += a
|
1037 |
+
|
1038 |
+
if exp > 0:
|
1039 |
+
res *= pow(prime, exp, aq)
|
1040 |
+
res %= aq
|
1041 |
+
|
1042 |
+
return S(res % q)
|
1043 |
+
|
1044 |
+
def _eval_expand_func(self, **hints):
|
1045 |
+
"""
|
1046 |
+
Function to expand binomial(n, k) when m is positive integer
|
1047 |
+
Also,
|
1048 |
+
n is self.args[0] and k is self.args[1] while using binomial(n, k)
|
1049 |
+
"""
|
1050 |
+
n = self.args[0]
|
1051 |
+
if n.is_Number:
|
1052 |
+
return binomial(*self.args)
|
1053 |
+
|
1054 |
+
k = self.args[1]
|
1055 |
+
if (n-k).is_Integer:
|
1056 |
+
k = n - k
|
1057 |
+
|
1058 |
+
if k.is_Integer:
|
1059 |
+
if k.is_zero:
|
1060 |
+
return S.One
|
1061 |
+
elif k.is_negative:
|
1062 |
+
return S.Zero
|
1063 |
+
else:
|
1064 |
+
n, result = self.args[0], 1
|
1065 |
+
for i in range(1, k + 1):
|
1066 |
+
result *= n - k + i
|
1067 |
+
return result / _factorial(k)
|
1068 |
+
else:
|
1069 |
+
return binomial(*self.args)
|
1070 |
+
|
1071 |
+
def _eval_rewrite_as_factorial(self, n, k, **kwargs):
|
1072 |
+
return factorial(n)/(factorial(k)*factorial(n - k))
|
1073 |
+
|
1074 |
+
def _eval_rewrite_as_gamma(self, n, k, piecewise=True, **kwargs):
|
1075 |
+
from sympy.functions.special.gamma_functions import gamma
|
1076 |
+
return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
|
1077 |
+
|
1078 |
+
def _eval_rewrite_as_tractable(self, n, k, limitvar=None, **kwargs):
|
1079 |
+
return self._eval_rewrite_as_gamma(n, k).rewrite('tractable')
|
1080 |
+
|
1081 |
+
def _eval_rewrite_as_FallingFactorial(self, n, k, **kwargs):
|
1082 |
+
if k.is_integer:
|
1083 |
+
return ff(n, k) / factorial(k)
|
1084 |
+
|
1085 |
+
def _eval_is_integer(self):
|
1086 |
+
n, k = self.args
|
1087 |
+
if n.is_integer and k.is_integer:
|
1088 |
+
return True
|
1089 |
+
elif k.is_integer is False:
|
1090 |
+
return False
|
1091 |
+
|
1092 |
+
def _eval_is_nonnegative(self):
|
1093 |
+
n, k = self.args
|
1094 |
+
if n.is_integer and k.is_integer:
|
1095 |
+
if n.is_nonnegative or k.is_negative or k.is_even:
|
1096 |
+
return True
|
1097 |
+
elif k.is_even is False:
|
1098 |
+
return False
|
1099 |
+
|
1100 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
1101 |
+
from sympy.functions.special.gamma_functions import gamma
|
1102 |
+
return self.rewrite(gamma)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
venv/lib/python3.10/site-packages/sympy/functions/combinatorial/numbers.py
ADDED
@@ -0,0 +1,2563 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module implements some special functions that commonly appear in
|
3 |
+
combinatorial contexts (e.g. in power series); in particular,
|
4 |
+
sequences of rational numbers such as Bernoulli and Fibonacci numbers.
|
5 |
+
|
6 |
+
Factorials, binomial coefficients and related functions are located in
|
7 |
+
the separate 'factorials' module.
|
8 |
+
"""
|
9 |
+
from math import prod
|
10 |
+
from collections import defaultdict
|
11 |
+
from typing import Tuple as tTuple
|
12 |
+
|
13 |
+
from sympy.core import S, Symbol, Add, Dummy
|
14 |
+
from sympy.core.cache import cacheit
|
15 |
+
from sympy.core.expr import Expr
|
16 |
+
from sympy.core.function import ArgumentIndexError, Function, expand_mul
|
17 |
+
from sympy.core.logic import fuzzy_not
|
18 |
+
from sympy.core.mul import Mul
|
19 |
+
from sympy.core.numbers import E, I, pi, oo, Rational, Integer
|
20 |
+
from sympy.core.relational import Eq, is_le, is_gt
|
21 |
+
from sympy.external.gmpy import SYMPY_INTS
|
22 |
+
from sympy.functions.combinatorial.factorials import (binomial,
|
23 |
+
factorial, subfactorial)
|
24 |
+
from sympy.functions.elementary.exponential import log
|
25 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
26 |
+
from sympy.ntheory.primetest import isprime, is_square
|
27 |
+
from sympy.polys.appellseqs import bernoulli_poly, euler_poly, genocchi_poly
|
28 |
+
from sympy.utilities.enumerative import MultisetPartitionTraverser
|
29 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
30 |
+
from sympy.utilities.iterables import multiset, multiset_derangements, iterable
|
31 |
+
from sympy.utilities.memoization import recurrence_memo
|
32 |
+
from sympy.utilities.misc import as_int
|
33 |
+
|
34 |
+
from mpmath import mp, workprec
|
35 |
+
from mpmath.libmp import ifib as _ifib
|
36 |
+
|
37 |
+
|
38 |
+
def _product(a, b):
|
39 |
+
return prod(range(a, b + 1))
|
40 |
+
|
41 |
+
|
42 |
+
# Dummy symbol used for computing polynomial sequences
|
43 |
+
_sym = Symbol('x')
|
44 |
+
|
45 |
+
|
46 |
+
#----------------------------------------------------------------------------#
|
47 |
+
# #
|
48 |
+
# Carmichael numbers #
|
49 |
+
# #
|
50 |
+
#----------------------------------------------------------------------------#
|
51 |
+
|
52 |
+
def _divides(p, n):
|
53 |
+
return n % p == 0
|
54 |
+
|
55 |
+
class carmichael(Function):
|
56 |
+
r"""
|
57 |
+
Carmichael Numbers:
|
58 |
+
|
59 |
+
Certain cryptographic algorithms make use of big prime numbers.
|
60 |
+
However, checking whether a big number is prime is not so easy.
|
61 |
+
Randomized prime number checking tests exist that offer a high degree of
|
62 |
+
confidence of accurate determination at low cost, such as the Fermat test.
|
63 |
+
|
64 |
+
Let 'a' be a random number between $2$ and $n - 1$, where $n$ is the
|
65 |
+
number whose primality we are testing. Then, $n$ is probably prime if it
|
66 |
+
satisfies the modular arithmetic congruence relation:
|
67 |
+
|
68 |
+
.. math :: a^{n-1} = 1 \pmod{n}
|
69 |
+
|
70 |
+
(where mod refers to the modulo operation)
|
71 |
+
|
72 |
+
If a number passes the Fermat test several times, then it is prime with a
|
73 |
+
high probability.
|
74 |
+
|
75 |
+
Unfortunately, certain composite numbers (non-primes) still pass the Fermat
|
76 |
+
test with every number smaller than themselves.
|
77 |
+
These numbers are called Carmichael numbers.
|
78 |
+
|
79 |
+
A Carmichael number will pass a Fermat primality test to every base $b$
|
80 |
+
relatively prime to the number, even though it is not actually prime.
|
81 |
+
This makes tests based on Fermat's Little Theorem less effective than
|
82 |
+
strong probable prime tests such as the Baillie-PSW primality test and
|
83 |
+
the Miller-Rabin primality test.
|
84 |
+
|
85 |
+
Examples
|
86 |
+
========
|
87 |
+
|
88 |
+
>>> from sympy import carmichael
|
89 |
+
>>> carmichael.find_first_n_carmichaels(5)
|
90 |
+
[561, 1105, 1729, 2465, 2821]
|
91 |
+
>>> carmichael.find_carmichael_numbers_in_range(0, 562)
|
92 |
+
[561]
|
93 |
+
>>> carmichael.find_carmichael_numbers_in_range(0,1000)
|
94 |
+
[561]
|
95 |
+
>>> carmichael.find_carmichael_numbers_in_range(0,2000)
|
96 |
+
[561, 1105, 1729]
|
97 |
+
|
98 |
+
References
|
99 |
+
==========
|
100 |
+
|
101 |
+
.. [1] https://en.wikipedia.org/wiki/Carmichael_number
|
102 |
+
.. [2] https://en.wikipedia.org/wiki/Fermat_primality_test
|
103 |
+
.. [3] https://www.jstor.org/stable/23248683?seq=1#metadata_info_tab_contents
|
104 |
+
"""
|
105 |
+
|
106 |
+
@staticmethod
|
107 |
+
def is_perfect_square(n):
|
108 |
+
sympy_deprecation_warning(
|
109 |
+
"""
|
110 |
+
is_perfect_square is just a wrapper around sympy.ntheory.primetest.is_square
|
111 |
+
so use that directly instead.
|
112 |
+
""",
|
113 |
+
deprecated_since_version="1.11",
|
114 |
+
active_deprecations_target='deprecated-carmichael-static-methods',
|
115 |
+
)
|
116 |
+
return is_square(n)
|
117 |
+
|
118 |
+
@staticmethod
|
119 |
+
def divides(p, n):
|
120 |
+
sympy_deprecation_warning(
|
121 |
+
"""
|
122 |
+
divides can be replaced by directly testing n % p == 0.
|
123 |
+
""",
|
124 |
+
deprecated_since_version="1.11",
|
125 |
+
active_deprecations_target='deprecated-carmichael-static-methods',
|
126 |
+
)
|
127 |
+
return n % p == 0
|
128 |
+
|
129 |
+
@staticmethod
|
130 |
+
def is_prime(n):
|
131 |
+
sympy_deprecation_warning(
|
132 |
+
"""
|
133 |
+
is_prime is just a wrapper around sympy.ntheory.primetest.isprime so use that
|
134 |
+
directly instead.
|
135 |
+
""",
|
136 |
+
deprecated_since_version="1.11",
|
137 |
+
active_deprecations_target='deprecated-carmichael-static-methods',
|
138 |
+
)
|
139 |
+
return isprime(n)
|
140 |
+
|
141 |
+
@staticmethod
|
142 |
+
def is_carmichael(n):
|
143 |
+
if n >= 0:
|
144 |
+
if (n == 1) or isprime(n) or (n % 2 == 0):
|
145 |
+
return False
|
146 |
+
|
147 |
+
divisors = [1, n]
|
148 |
+
|
149 |
+
# get divisors
|
150 |
+
divisors.extend([i for i in range(3, n // 2 + 1, 2) if n % i == 0])
|
151 |
+
|
152 |
+
for i in divisors:
|
153 |
+
if is_square(i) and i != 1:
|
154 |
+
return False
|
155 |
+
if isprime(i):
|
156 |
+
if not _divides(i - 1, n - 1):
|
157 |
+
return False
|
158 |
+
|
159 |
+
return True
|
160 |
+
|
161 |
+
else:
|
162 |
+
raise ValueError('The provided number must be greater than or equal to 0')
|
163 |
+
|
164 |
+
@staticmethod
|
165 |
+
def find_carmichael_numbers_in_range(x, y):
|
166 |
+
if 0 <= x <= y:
|
167 |
+
if x % 2 == 0:
|
168 |
+
return [i for i in range(x + 1, y, 2) if carmichael.is_carmichael(i)]
|
169 |
+
else:
|
170 |
+
return [i for i in range(x, y, 2) if carmichael.is_carmichael(i)]
|
171 |
+
|
172 |
+
else:
|
173 |
+
raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y')
|
174 |
+
|
175 |
+
@staticmethod
|
176 |
+
def find_first_n_carmichaels(n):
|
177 |
+
i = 1
|
178 |
+
carmichaels = []
|
179 |
+
|
180 |
+
while len(carmichaels) < n:
|
181 |
+
if carmichael.is_carmichael(i):
|
182 |
+
carmichaels.append(i)
|
183 |
+
i += 2
|
184 |
+
|
185 |
+
return carmichaels
|
186 |
+
|
187 |
+
|
188 |
+
#----------------------------------------------------------------------------#
|
189 |
+
# #
|
190 |
+
# Fibonacci numbers #
|
191 |
+
# #
|
192 |
+
#----------------------------------------------------------------------------#
|
193 |
+
|
194 |
+
|
195 |
+
class fibonacci(Function):
|
196 |
+
r"""
|
197 |
+
Fibonacci numbers / Fibonacci polynomials
|
198 |
+
|
199 |
+
The Fibonacci numbers are the integer sequence defined by the
|
200 |
+
initial terms `F_0 = 0`, `F_1 = 1` and the two-term recurrence
|
201 |
+
relation `F_n = F_{n-1} + F_{n-2}`. This definition
|
202 |
+
extended to arbitrary real and complex arguments using
|
203 |
+
the formula
|
204 |
+
|
205 |
+
.. math :: F_z = \frac{\phi^z - \cos(\pi z) \phi^{-z}}{\sqrt 5}
|
206 |
+
|
207 |
+
The Fibonacci polynomials are defined by `F_1(x) = 1`,
|
208 |
+
`F_2(x) = x`, and `F_n(x) = x*F_{n-1}(x) + F_{n-2}(x)` for `n > 2`.
|
209 |
+
For all positive integers `n`, `F_n(1) = F_n`.
|
210 |
+
|
211 |
+
* ``fibonacci(n)`` gives the `n^{th}` Fibonacci number, `F_n`
|
212 |
+
* ``fibonacci(n, x)`` gives the `n^{th}` Fibonacci polynomial in `x`, `F_n(x)`
|
213 |
+
|
214 |
+
Examples
|
215 |
+
========
|
216 |
+
|
217 |
+
>>> from sympy import fibonacci, Symbol
|
218 |
+
|
219 |
+
>>> [fibonacci(x) for x in range(11)]
|
220 |
+
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
|
221 |
+
>>> fibonacci(5, Symbol('t'))
|
222 |
+
t**4 + 3*t**2 + 1
|
223 |
+
|
224 |
+
See Also
|
225 |
+
========
|
226 |
+
|
227 |
+
bell, bernoulli, catalan, euler, harmonic, lucas, genocchi, partition, tribonacci
|
228 |
+
|
229 |
+
References
|
230 |
+
==========
|
231 |
+
|
232 |
+
.. [1] https://en.wikipedia.org/wiki/Fibonacci_number
|
233 |
+
.. [2] https://mathworld.wolfram.com/FibonacciNumber.html
|
234 |
+
|
235 |
+
"""
|
236 |
+
|
237 |
+
@staticmethod
|
238 |
+
def _fib(n):
|
239 |
+
return _ifib(n)
|
240 |
+
|
241 |
+
@staticmethod
|
242 |
+
@recurrence_memo([None, S.One, _sym])
|
243 |
+
def _fibpoly(n, prev):
|
244 |
+
return (prev[-2] + _sym*prev[-1]).expand()
|
245 |
+
|
246 |
+
@classmethod
|
247 |
+
def eval(cls, n, sym=None):
|
248 |
+
if n is S.Infinity:
|
249 |
+
return S.Infinity
|
250 |
+
|
251 |
+
if n.is_Integer:
|
252 |
+
if sym is None:
|
253 |
+
n = int(n)
|
254 |
+
if n < 0:
|
255 |
+
return S.NegativeOne**(n + 1) * fibonacci(-n)
|
256 |
+
else:
|
257 |
+
return Integer(cls._fib(n))
|
258 |
+
else:
|
259 |
+
if n < 1:
|
260 |
+
raise ValueError("Fibonacci polynomials are defined "
|
261 |
+
"only for positive integer indices.")
|
262 |
+
return cls._fibpoly(n).subs(_sym, sym)
|
263 |
+
|
264 |
+
def _eval_rewrite_as_sqrt(self, n, **kwargs):
|
265 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
266 |
+
return 2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5
|
267 |
+
|
268 |
+
def _eval_rewrite_as_GoldenRatio(self,n, **kwargs):
|
269 |
+
return (S.GoldenRatio**n - 1/(-S.GoldenRatio)**n)/(2*S.GoldenRatio-1)
|
270 |
+
|
271 |
+
|
272 |
+
#----------------------------------------------------------------------------#
|
273 |
+
# #
|
274 |
+
# Lucas numbers #
|
275 |
+
# #
|
276 |
+
#----------------------------------------------------------------------------#
|
277 |
+
|
278 |
+
|
279 |
+
class lucas(Function):
|
280 |
+
"""
|
281 |
+
Lucas numbers
|
282 |
+
|
283 |
+
Lucas numbers satisfy a recurrence relation similar to that of
|
284 |
+
the Fibonacci sequence, in which each term is the sum of the
|
285 |
+
preceding two. They are generated by choosing the initial
|
286 |
+
values `L_0 = 2` and `L_1 = 1`.
|
287 |
+
|
288 |
+
* ``lucas(n)`` gives the `n^{th}` Lucas number
|
289 |
+
|
290 |
+
Examples
|
291 |
+
========
|
292 |
+
|
293 |
+
>>> from sympy import lucas
|
294 |
+
|
295 |
+
>>> [lucas(x) for x in range(11)]
|
296 |
+
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123]
|
297 |
+
|
298 |
+
See Also
|
299 |
+
========
|
300 |
+
|
301 |
+
bell, bernoulli, catalan, euler, fibonacci, harmonic, genocchi, partition, tribonacci
|
302 |
+
|
303 |
+
References
|
304 |
+
==========
|
305 |
+
|
306 |
+
.. [1] https://en.wikipedia.org/wiki/Lucas_number
|
307 |
+
.. [2] https://mathworld.wolfram.com/LucasNumber.html
|
308 |
+
|
309 |
+
"""
|
310 |
+
|
311 |
+
@classmethod
|
312 |
+
def eval(cls, n):
|
313 |
+
if n is S.Infinity:
|
314 |
+
return S.Infinity
|
315 |
+
|
316 |
+
if n.is_Integer:
|
317 |
+
return fibonacci(n + 1) + fibonacci(n - 1)
|
318 |
+
|
319 |
+
def _eval_rewrite_as_sqrt(self, n, **kwargs):
|
320 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
321 |
+
return 2**(-n)*((1 + sqrt(5))**n + (-sqrt(5) + 1)**n)
|
322 |
+
|
323 |
+
|
324 |
+
#----------------------------------------------------------------------------#
|
325 |
+
# #
|
326 |
+
# Tribonacci numbers #
|
327 |
+
# #
|
328 |
+
#----------------------------------------------------------------------------#
|
329 |
+
|
330 |
+
|
331 |
+
class tribonacci(Function):
|
332 |
+
r"""
|
333 |
+
Tribonacci numbers / Tribonacci polynomials
|
334 |
+
|
335 |
+
The Tribonacci numbers are the integer sequence defined by the
|
336 |
+
initial terms `T_0 = 0`, `T_1 = 1`, `T_2 = 1` and the three-term
|
337 |
+
recurrence relation `T_n = T_{n-1} + T_{n-2} + T_{n-3}`.
|
338 |
+
|
339 |
+
The Tribonacci polynomials are defined by `T_0(x) = 0`, `T_1(x) = 1`,
|
340 |
+
`T_2(x) = x^2`, and `T_n(x) = x^2 T_{n-1}(x) + x T_{n-2}(x) + T_{n-3}(x)`
|
341 |
+
for `n > 2`. For all positive integers `n`, `T_n(1) = T_n`.
|
342 |
+
|
343 |
+
* ``tribonacci(n)`` gives the `n^{th}` Tribonacci number, `T_n`
|
344 |
+
* ``tribonacci(n, x)`` gives the `n^{th}` Tribonacci polynomial in `x`, `T_n(x)`
|
345 |
+
|
346 |
+
Examples
|
347 |
+
========
|
348 |
+
|
349 |
+
>>> from sympy import tribonacci, Symbol
|
350 |
+
|
351 |
+
>>> [tribonacci(x) for x in range(11)]
|
352 |
+
[0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149]
|
353 |
+
>>> tribonacci(5, Symbol('t'))
|
354 |
+
t**8 + 3*t**5 + 3*t**2
|
355 |
+
|
356 |
+
See Also
|
357 |
+
========
|
358 |
+
|
359 |
+
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition
|
360 |
+
|
361 |
+
References
|
362 |
+
==========
|
363 |
+
|
364 |
+
.. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers
|
365 |
+
.. [2] https://mathworld.wolfram.com/TribonacciNumber.html
|
366 |
+
.. [3] https://oeis.org/A000073
|
367 |
+
|
368 |
+
"""
|
369 |
+
|
370 |
+
@staticmethod
|
371 |
+
@recurrence_memo([S.Zero, S.One, S.One])
|
372 |
+
def _trib(n, prev):
|
373 |
+
return (prev[-3] + prev[-2] + prev[-1])
|
374 |
+
|
375 |
+
@staticmethod
|
376 |
+
@recurrence_memo([S.Zero, S.One, _sym**2])
|
377 |
+
def _tribpoly(n, prev):
|
378 |
+
return (prev[-3] + _sym*prev[-2] + _sym**2*prev[-1]).expand()
|
379 |
+
|
380 |
+
@classmethod
|
381 |
+
def eval(cls, n, sym=None):
|
382 |
+
if n is S.Infinity:
|
383 |
+
return S.Infinity
|
384 |
+
|
385 |
+
if n.is_Integer:
|
386 |
+
n = int(n)
|
387 |
+
if n < 0:
|
388 |
+
raise ValueError("Tribonacci polynomials are defined "
|
389 |
+
"only for non-negative integer indices.")
|
390 |
+
if sym is None:
|
391 |
+
return Integer(cls._trib(n))
|
392 |
+
else:
|
393 |
+
return cls._tribpoly(n).subs(_sym, sym)
|
394 |
+
|
395 |
+
def _eval_rewrite_as_sqrt(self, n, **kwargs):
|
396 |
+
from sympy.functions.elementary.miscellaneous import cbrt, sqrt
|
397 |
+
w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2
|
398 |
+
a = (1 + cbrt(19 + 3*sqrt(33)) + cbrt(19 - 3*sqrt(33))) / 3
|
399 |
+
b = (1 + w*cbrt(19 + 3*sqrt(33)) + w**2*cbrt(19 - 3*sqrt(33))) / 3
|
400 |
+
c = (1 + w**2*cbrt(19 + 3*sqrt(33)) + w*cbrt(19 - 3*sqrt(33))) / 3
|
401 |
+
Tn = (a**(n + 1)/((a - b)*(a - c))
|
402 |
+
+ b**(n + 1)/((b - a)*(b - c))
|
403 |
+
+ c**(n + 1)/((c - a)*(c - b)))
|
404 |
+
return Tn
|
405 |
+
|
406 |
+
def _eval_rewrite_as_TribonacciConstant(self, n, **kwargs):
|
407 |
+
from sympy.functions.elementary.integers import floor
|
408 |
+
from sympy.functions.elementary.miscellaneous import cbrt, sqrt
|
409 |
+
b = cbrt(586 + 102*sqrt(33))
|
410 |
+
Tn = 3 * b * S.TribonacciConstant**n / (b**2 - 2*b + 4)
|
411 |
+
return floor(Tn + S.Half)
|
412 |
+
|
413 |
+
|
414 |
+
#----------------------------------------------------------------------------#
|
415 |
+
# #
|
416 |
+
# Bernoulli numbers #
|
417 |
+
# #
|
418 |
+
#----------------------------------------------------------------------------#
|
419 |
+
|
420 |
+
|
421 |
+
class bernoulli(Function):
|
422 |
+
r"""
|
423 |
+
Bernoulli numbers / Bernoulli polynomials / Bernoulli function
|
424 |
+
|
425 |
+
The Bernoulli numbers are a sequence of rational numbers
|
426 |
+
defined by `B_0 = 1` and the recursive relation (`n > 0`):
|
427 |
+
|
428 |
+
.. math :: n+1 = \sum_{k=0}^n \binom{n+1}{k} B_k
|
429 |
+
|
430 |
+
They are also commonly defined by their exponential generating
|
431 |
+
function, which is `\frac{x}{1 - e^{-x}}`. For odd indices > 1,
|
432 |
+
the Bernoulli numbers are zero.
|
433 |
+
|
434 |
+
The Bernoulli polynomials satisfy the analogous formula:
|
435 |
+
|
436 |
+
.. math :: B_n(x) = \sum_{k=0}^n (-1)^k \binom{n}{k} B_k x^{n-k}
|
437 |
+
|
438 |
+
Bernoulli numbers and Bernoulli polynomials are related as
|
439 |
+
`B_n(1) = B_n`.
|
440 |
+
|
441 |
+
The generalized Bernoulli function `\operatorname{B}(s, a)`
|
442 |
+
is defined for any complex `s` and `a`, except where `a` is a
|
443 |
+
nonpositive integer and `s` is not a nonnegative integer. It is
|
444 |
+
an entire function of `s` for fixed `a`, related to the Hurwitz
|
445 |
+
zeta function by
|
446 |
+
|
447 |
+
.. math:: \operatorname{B}(s, a) = \begin{cases}
|
448 |
+
-s \zeta(1-s, a) & s \ne 0 \\ 1 & s = 0 \end{cases}
|
449 |
+
|
450 |
+
When `s` is a nonnegative integer this function reduces to the
|
451 |
+
Bernoulli polynomials: `\operatorname{B}(n, x) = B_n(x)`. When
|
452 |
+
`a` is omitted it is assumed to be 1, yielding the (ordinary)
|
453 |
+
Bernoulli function which interpolates the Bernoulli numbers and is
|
454 |
+
related to the Riemann zeta function.
|
455 |
+
|
456 |
+
We compute Bernoulli numbers using Ramanujan's formula:
|
457 |
+
|
458 |
+
.. math :: B_n = \frac{A(n) - S(n)}{\binom{n+3}{n}}
|
459 |
+
|
460 |
+
where:
|
461 |
+
|
462 |
+
.. math :: A(n) = \begin{cases} \frac{n+3}{3} &
|
463 |
+
n \equiv 0\ \text{or}\ 2 \pmod{6} \\
|
464 |
+
-\frac{n+3}{6} & n \equiv 4 \pmod{6} \end{cases}
|
465 |
+
|
466 |
+
and:
|
467 |
+
|
468 |
+
.. math :: S(n) = \sum_{k=1}^{[n/6]} \binom{n+3}{n-6k} B_{n-6k}
|
469 |
+
|
470 |
+
This formula is similar to the sum given in the definition, but
|
471 |
+
cuts `\frac{2}{3}` of the terms. For Bernoulli polynomials, we use
|
472 |
+
Appell sequences.
|
473 |
+
|
474 |
+
For `n` a nonnegative integer and `s`, `a`, `x` arbitrary complex numbers,
|
475 |
+
|
476 |
+
* ``bernoulli(n)`` gives the nth Bernoulli number, `B_n`
|
477 |
+
* ``bernoulli(s)`` gives the Bernoulli function `\operatorname{B}(s)`
|
478 |
+
* ``bernoulli(n, x)`` gives the nth Bernoulli polynomial in `x`, `B_n(x)`
|
479 |
+
* ``bernoulli(s, a)`` gives the generalized Bernoulli function
|
480 |
+
`\operatorname{B}(s, a)`
|
481 |
+
|
482 |
+
.. versionchanged:: 1.12
|
483 |
+
``bernoulli(1)`` gives `+\frac{1}{2}` instead of `-\frac{1}{2}`.
|
484 |
+
This choice of value confers several theoretical advantages [5]_,
|
485 |
+
including the extension to complex parameters described above
|
486 |
+
which this function now implements. The previous behavior, defined
|
487 |
+
only for nonnegative integers `n`, can be obtained with
|
488 |
+
``(-1)**n*bernoulli(n)``.
|
489 |
+
|
490 |
+
Examples
|
491 |
+
========
|
492 |
+
|
493 |
+
>>> from sympy import bernoulli
|
494 |
+
>>> from sympy.abc import x
|
495 |
+
>>> [bernoulli(n) for n in range(11)]
|
496 |
+
[1, 1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
|
497 |
+
>>> bernoulli(1000001)
|
498 |
+
0
|
499 |
+
>>> bernoulli(3, x)
|
500 |
+
x**3 - 3*x**2/2 + x/2
|
501 |
+
|
502 |
+
See Also
|
503 |
+
========
|
504 |
+
|
505 |
+
andre, bell, catalan, euler, fibonacci, harmonic, lucas, genocchi,
|
506 |
+
partition, tribonacci, sympy.polys.appellseqs.bernoulli_poly
|
507 |
+
|
508 |
+
References
|
509 |
+
==========
|
510 |
+
|
511 |
+
.. [1] https://en.wikipedia.org/wiki/Bernoulli_number
|
512 |
+
.. [2] https://en.wikipedia.org/wiki/Bernoulli_polynomial
|
513 |
+
.. [3] https://mathworld.wolfram.com/BernoulliNumber.html
|
514 |
+
.. [4] https://mathworld.wolfram.com/BernoulliPolynomial.html
|
515 |
+
.. [5] Peter Luschny, "The Bernoulli Manifesto",
|
516 |
+
https://luschny.de/math/zeta/The-Bernoulli-Manifesto.html
|
517 |
+
.. [6] Peter Luschny, "An introduction to the Bernoulli function",
|
518 |
+
https://arxiv.org/abs/2009.06743
|
519 |
+
|
520 |
+
"""
|
521 |
+
|
522 |
+
args: tTuple[Integer]
|
523 |
+
|
524 |
+
# Calculates B_n for positive even n
|
525 |
+
@staticmethod
|
526 |
+
def _calc_bernoulli(n):
|
527 |
+
s = 0
|
528 |
+
a = int(binomial(n + 3, n - 6))
|
529 |
+
for j in range(1, n//6 + 1):
|
530 |
+
s += a * bernoulli(n - 6*j)
|
531 |
+
# Avoid computing each binomial coefficient from scratch
|
532 |
+
a *= _product(n - 6 - 6*j + 1, n - 6*j)
|
533 |
+
a //= _product(6*j + 4, 6*j + 9)
|
534 |
+
if n % 6 == 4:
|
535 |
+
s = -Rational(n + 3, 6) - s
|
536 |
+
else:
|
537 |
+
s = Rational(n + 3, 3) - s
|
538 |
+
return s / binomial(n + 3, n)
|
539 |
+
|
540 |
+
# We implement a specialized memoization scheme to handle each
|
541 |
+
# case modulo 6 separately
|
542 |
+
_cache = {0: S.One, 2: Rational(1, 6), 4: Rational(-1, 30)}
|
543 |
+
_highest = {0: 0, 2: 2, 4: 4}
|
544 |
+
|
545 |
+
@classmethod
|
546 |
+
def eval(cls, n, x=None):
|
547 |
+
if x is S.One:
|
548 |
+
return cls(n)
|
549 |
+
elif n.is_zero:
|
550 |
+
return S.One
|
551 |
+
elif n.is_integer is False or n.is_nonnegative is False:
|
552 |
+
if x is not None and x.is_Integer and x.is_nonpositive:
|
553 |
+
return S.NaN
|
554 |
+
return
|
555 |
+
# Bernoulli numbers
|
556 |
+
elif x is None:
|
557 |
+
if n is S.One:
|
558 |
+
return S.Half
|
559 |
+
elif n.is_odd and (n-1).is_positive:
|
560 |
+
return S.Zero
|
561 |
+
elif n.is_Number:
|
562 |
+
n = int(n)
|
563 |
+
# Use mpmath for enormous Bernoulli numbers
|
564 |
+
if n > 500:
|
565 |
+
p, q = mp.bernfrac(n)
|
566 |
+
return Rational(int(p), int(q))
|
567 |
+
case = n % 6
|
568 |
+
highest_cached = cls._highest[case]
|
569 |
+
if n <= highest_cached:
|
570 |
+
return cls._cache[n]
|
571 |
+
# To avoid excessive recursion when, say, bernoulli(1000) is
|
572 |
+
# requested, calculate and cache the entire sequence ... B_988,
|
573 |
+
# B_994, B_1000 in increasing order
|
574 |
+
for i in range(highest_cached + 6, n + 6, 6):
|
575 |
+
b = cls._calc_bernoulli(i)
|
576 |
+
cls._cache[i] = b
|
577 |
+
cls._highest[case] = i
|
578 |
+
return b
|
579 |
+
# Bernoulli polynomials
|
580 |
+
elif n.is_Number:
|
581 |
+
return bernoulli_poly(n, x)
|
582 |
+
|
583 |
+
def _eval_rewrite_as_zeta(self, n, x=1, **kwargs):
|
584 |
+
from sympy.functions.special.zeta_functions import zeta
|
585 |
+
return Piecewise((1, Eq(n, 0)), (-n * zeta(1-n, x), True))
|
586 |
+
|
587 |
+
def _eval_evalf(self, prec):
|
588 |
+
if not all(x.is_number for x in self.args):
|
589 |
+
return
|
590 |
+
n = self.args[0]._to_mpmath(prec)
|
591 |
+
x = (self.args[1] if len(self.args) > 1 else S.One)._to_mpmath(prec)
|
592 |
+
with workprec(prec):
|
593 |
+
if n == 0:
|
594 |
+
res = mp.mpf(1)
|
595 |
+
elif n == 1:
|
596 |
+
res = x - mp.mpf(0.5)
|
597 |
+
elif mp.isint(n) and n >= 0:
|
598 |
+
res = mp.bernoulli(n) if x == 1 else mp.bernpoly(n, x)
|
599 |
+
else:
|
600 |
+
res = -n * mp.zeta(1-n, x)
|
601 |
+
return Expr._from_mpmath(res, prec)
|
602 |
+
|
603 |
+
|
604 |
+
#----------------------------------------------------------------------------#
|
605 |
+
# #
|
606 |
+
# Bell numbers #
|
607 |
+
# #
|
608 |
+
#----------------------------------------------------------------------------#
|
609 |
+
|
610 |
+
|
611 |
+
class bell(Function):
|
612 |
+
r"""
|
613 |
+
Bell numbers / Bell polynomials
|
614 |
+
|
615 |
+
The Bell numbers satisfy `B_0 = 1` and
|
616 |
+
|
617 |
+
.. math:: B_n = \sum_{k=0}^{n-1} \binom{n-1}{k} B_k.
|
618 |
+
|
619 |
+
They are also given by:
|
620 |
+
|
621 |
+
.. math:: B_n = \frac{1}{e} \sum_{k=0}^{\infty} \frac{k^n}{k!}.
|
622 |
+
|
623 |
+
The Bell polynomials are given by `B_0(x) = 1` and
|
624 |
+
|
625 |
+
.. math:: B_n(x) = x \sum_{k=1}^{n-1} \binom{n-1}{k-1} B_{k-1}(x).
|
626 |
+
|
627 |
+
The second kind of Bell polynomials (are sometimes called "partial" Bell
|
628 |
+
polynomials or incomplete Bell polynomials) are defined as
|
629 |
+
|
630 |
+
.. math:: B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) =
|
631 |
+
\sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n}
|
632 |
+
\frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!}
|
633 |
+
\left(\frac{x_1}{1!} \right)^{j_1}
|
634 |
+
\left(\frac{x_2}{2!} \right)^{j_2} \dotsb
|
635 |
+
\left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}.
|
636 |
+
|
637 |
+
* ``bell(n)`` gives the `n^{th}` Bell number, `B_n`.
|
638 |
+
* ``bell(n, x)`` gives the `n^{th}` Bell polynomial, `B_n(x)`.
|
639 |
+
* ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind,
|
640 |
+
`B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`.
|
641 |
+
|
642 |
+
Notes
|
643 |
+
=====
|
644 |
+
|
645 |
+
Not to be confused with Bernoulli numbers and Bernoulli polynomials,
|
646 |
+
which use the same notation.
|
647 |
+
|
648 |
+
Examples
|
649 |
+
========
|
650 |
+
|
651 |
+
>>> from sympy import bell, Symbol, symbols
|
652 |
+
|
653 |
+
>>> [bell(n) for n in range(11)]
|
654 |
+
[1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975]
|
655 |
+
>>> bell(30)
|
656 |
+
846749014511809332450147
|
657 |
+
>>> bell(4, Symbol('t'))
|
658 |
+
t**4 + 6*t**3 + 7*t**2 + t
|
659 |
+
>>> bell(6, 2, symbols('x:6')[1:])
|
660 |
+
6*x1*x5 + 15*x2*x4 + 10*x3**2
|
661 |
+
|
662 |
+
See Also
|
663 |
+
========
|
664 |
+
|
665 |
+
bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci
|
666 |
+
|
667 |
+
References
|
668 |
+
==========
|
669 |
+
|
670 |
+
.. [1] https://en.wikipedia.org/wiki/Bell_number
|
671 |
+
.. [2] https://mathworld.wolfram.com/BellNumber.html
|
672 |
+
.. [3] https://mathworld.wolfram.com/BellPolynomial.html
|
673 |
+
|
674 |
+
"""
|
675 |
+
|
676 |
+
@staticmethod
|
677 |
+
@recurrence_memo([1, 1])
|
678 |
+
def _bell(n, prev):
|
679 |
+
s = 1
|
680 |
+
a = 1
|
681 |
+
for k in range(1, n):
|
682 |
+
a = a * (n - k) // k
|
683 |
+
s += a * prev[k]
|
684 |
+
return s
|
685 |
+
|
686 |
+
@staticmethod
|
687 |
+
@recurrence_memo([S.One, _sym])
|
688 |
+
def _bell_poly(n, prev):
|
689 |
+
s = 1
|
690 |
+
a = 1
|
691 |
+
for k in range(2, n + 1):
|
692 |
+
a = a * (n - k + 1) // (k - 1)
|
693 |
+
s += a * prev[k - 1]
|
694 |
+
return expand_mul(_sym * s)
|
695 |
+
|
696 |
+
@staticmethod
|
697 |
+
def _bell_incomplete_poly(n, k, symbols):
|
698 |
+
r"""
|
699 |
+
The second kind of Bell polynomials (incomplete Bell polynomials).
|
700 |
+
|
701 |
+
Calculated by recurrence formula:
|
702 |
+
|
703 |
+
.. math:: B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1}) =
|
704 |
+
\sum_{m=1}^{n-k+1}
|
705 |
+
\x_m \binom{n-1}{m-1} B_{n-m,k-1}(x_1, x_2, \dotsc, x_{n-m-k})
|
706 |
+
|
707 |
+
where
|
708 |
+
`B_{0,0} = 1;`
|
709 |
+
`B_{n,0} = 0; for n \ge 1`
|
710 |
+
`B_{0,k} = 0; for k \ge 1`
|
711 |
+
|
712 |
+
"""
|
713 |
+
if (n == 0) and (k == 0):
|
714 |
+
return S.One
|
715 |
+
elif (n == 0) or (k == 0):
|
716 |
+
return S.Zero
|
717 |
+
s = S.Zero
|
718 |
+
a = S.One
|
719 |
+
for m in range(1, n - k + 2):
|
720 |
+
s += a * bell._bell_incomplete_poly(
|
721 |
+
n - m, k - 1, symbols) * symbols[m - 1]
|
722 |
+
a = a * (n - m) / m
|
723 |
+
return expand_mul(s)
|
724 |
+
|
725 |
+
@classmethod
|
726 |
+
def eval(cls, n, k_sym=None, symbols=None):
|
727 |
+
if n is S.Infinity:
|
728 |
+
if k_sym is None:
|
729 |
+
return S.Infinity
|
730 |
+
else:
|
731 |
+
raise ValueError("Bell polynomial is not defined")
|
732 |
+
|
733 |
+
if n.is_negative or n.is_integer is False:
|
734 |
+
raise ValueError("a non-negative integer expected")
|
735 |
+
|
736 |
+
if n.is_Integer and n.is_nonnegative:
|
737 |
+
if k_sym is None:
|
738 |
+
return Integer(cls._bell(int(n)))
|
739 |
+
elif symbols is None:
|
740 |
+
return cls._bell_poly(int(n)).subs(_sym, k_sym)
|
741 |
+
else:
|
742 |
+
r = cls._bell_incomplete_poly(int(n), int(k_sym), symbols)
|
743 |
+
return r
|
744 |
+
|
745 |
+
def _eval_rewrite_as_Sum(self, n, k_sym=None, symbols=None, **kwargs):
|
746 |
+
from sympy.concrete.summations import Sum
|
747 |
+
if (k_sym is not None) or (symbols is not None):
|
748 |
+
return self
|
749 |
+
|
750 |
+
# Dobinski's formula
|
751 |
+
if not n.is_nonnegative:
|
752 |
+
return self
|
753 |
+
k = Dummy('k', integer=True, nonnegative=True)
|
754 |
+
return 1 / E * Sum(k**n / factorial(k), (k, 0, S.Infinity))
|
755 |
+
|
756 |
+
|
757 |
+
#----------------------------------------------------------------------------#
|
758 |
+
# #
|
759 |
+
# Harmonic numbers #
|
760 |
+
# #
|
761 |
+
#----------------------------------------------------------------------------#
|
762 |
+
|
763 |
+
|
764 |
+
class harmonic(Function):
|
765 |
+
r"""
|
766 |
+
Harmonic numbers
|
767 |
+
|
768 |
+
The nth harmonic number is given by `\operatorname{H}_{n} =
|
769 |
+
1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}`.
|
770 |
+
|
771 |
+
More generally:
|
772 |
+
|
773 |
+
.. math:: \operatorname{H}_{n,m} = \sum_{k=1}^{n} \frac{1}{k^m}
|
774 |
+
|
775 |
+
As `n \rightarrow \infty`, `\operatorname{H}_{n,m} \rightarrow \zeta(m)`,
|
776 |
+
the Riemann zeta function.
|
777 |
+
|
778 |
+
* ``harmonic(n)`` gives the nth harmonic number, `\operatorname{H}_n`
|
779 |
+
|
780 |
+
* ``harmonic(n, m)`` gives the nth generalized harmonic number
|
781 |
+
of order `m`, `\operatorname{H}_{n,m}`, where
|
782 |
+
``harmonic(n) == harmonic(n, 1)``
|
783 |
+
|
784 |
+
This function can be extended to complex `n` and `m` where `n` is not a
|
785 |
+
negative integer or `m` is a nonpositive integer as
|
786 |
+
|
787 |
+
.. math:: \operatorname{H}_{n,m} = \begin{cases} \zeta(m) - \zeta(m, n+1)
|
788 |
+
& m \ne 1 \\ \psi(n+1) + \gamma & m = 1 \end{cases}
|
789 |
+
|
790 |
+
Examples
|
791 |
+
========
|
792 |
+
|
793 |
+
>>> from sympy import harmonic, oo
|
794 |
+
|
795 |
+
>>> [harmonic(n) for n in range(6)]
|
796 |
+
[0, 1, 3/2, 11/6, 25/12, 137/60]
|
797 |
+
>>> [harmonic(n, 2) for n in range(6)]
|
798 |
+
[0, 1, 5/4, 49/36, 205/144, 5269/3600]
|
799 |
+
>>> harmonic(oo, 2)
|
800 |
+
pi**2/6
|
801 |
+
|
802 |
+
>>> from sympy import Symbol, Sum
|
803 |
+
>>> n = Symbol("n")
|
804 |
+
|
805 |
+
>>> harmonic(n).rewrite(Sum)
|
806 |
+
Sum(1/_k, (_k, 1, n))
|
807 |
+
|
808 |
+
We can evaluate harmonic numbers for all integral and positive
|
809 |
+
rational arguments:
|
810 |
+
|
811 |
+
>>> from sympy import S, expand_func, simplify
|
812 |
+
>>> harmonic(8)
|
813 |
+
761/280
|
814 |
+
>>> harmonic(11)
|
815 |
+
83711/27720
|
816 |
+
|
817 |
+
>>> H = harmonic(1/S(3))
|
818 |
+
>>> H
|
819 |
+
harmonic(1/3)
|
820 |
+
>>> He = expand_func(H)
|
821 |
+
>>> He
|
822 |
+
-log(6) - sqrt(3)*pi/6 + 2*Sum(log(sin(_k*pi/3))*cos(2*_k*pi/3), (_k, 1, 1))
|
823 |
+
+ 3*Sum(1/(3*_k + 1), (_k, 0, 0))
|
824 |
+
>>> He.doit()
|
825 |
+
-log(6) - sqrt(3)*pi/6 - log(sqrt(3)/2) + 3
|
826 |
+
>>> H = harmonic(25/S(7))
|
827 |
+
>>> He = simplify(expand_func(H).doit())
|
828 |
+
>>> He
|
829 |
+
log(sin(2*pi/7)**(2*cos(16*pi/7))/(14*sin(pi/7)**(2*cos(pi/7))*cos(pi/14)**(2*sin(pi/14)))) + pi*tan(pi/14)/2 + 30247/9900
|
830 |
+
>>> He.n(40)
|
831 |
+
1.983697455232980674869851942390639915940
|
832 |
+
>>> harmonic(25/S(7)).n(40)
|
833 |
+
1.983697455232980674869851942390639915940
|
834 |
+
|
835 |
+
We can rewrite harmonic numbers in terms of polygamma functions:
|
836 |
+
|
837 |
+
>>> from sympy import digamma, polygamma
|
838 |
+
>>> m = Symbol("m", integer=True, positive=True)
|
839 |
+
|
840 |
+
>>> harmonic(n).rewrite(digamma)
|
841 |
+
polygamma(0, n + 1) + EulerGamma
|
842 |
+
|
843 |
+
>>> harmonic(n).rewrite(polygamma)
|
844 |
+
polygamma(0, n + 1) + EulerGamma
|
845 |
+
|
846 |
+
>>> harmonic(n,3).rewrite(polygamma)
|
847 |
+
polygamma(2, n + 1)/2 + zeta(3)
|
848 |
+
|
849 |
+
>>> simplify(harmonic(n,m).rewrite(polygamma))
|
850 |
+
Piecewise((polygamma(0, n + 1) + EulerGamma, Eq(m, 1)),
|
851 |
+
(-(-1)**m*polygamma(m - 1, n + 1)/factorial(m - 1) + zeta(m), True))
|
852 |
+
|
853 |
+
Integer offsets in the argument can be pulled out:
|
854 |
+
|
855 |
+
>>> from sympy import expand_func
|
856 |
+
|
857 |
+
>>> expand_func(harmonic(n+4))
|
858 |
+
harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)
|
859 |
+
|
860 |
+
>>> expand_func(harmonic(n-4))
|
861 |
+
harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n
|
862 |
+
|
863 |
+
Some limits can be computed as well:
|
864 |
+
|
865 |
+
>>> from sympy import limit, oo
|
866 |
+
|
867 |
+
>>> limit(harmonic(n), n, oo)
|
868 |
+
oo
|
869 |
+
|
870 |
+
>>> limit(harmonic(n, 2), n, oo)
|
871 |
+
pi**2/6
|
872 |
+
|
873 |
+
>>> limit(harmonic(n, 3), n, oo)
|
874 |
+
zeta(3)
|
875 |
+
|
876 |
+
For `m > 1`, `H_{n,m}` tends to `\zeta(m)` in the limit of infinite `n`:
|
877 |
+
|
878 |
+
>>> m = Symbol("m", positive=True)
|
879 |
+
>>> limit(harmonic(n, m+1), n, oo)
|
880 |
+
zeta(m + 1)
|
881 |
+
|
882 |
+
See Also
|
883 |
+
========
|
884 |
+
|
885 |
+
bell, bernoulli, catalan, euler, fibonacci, lucas, genocchi, partition, tribonacci
|
886 |
+
|
887 |
+
References
|
888 |
+
==========
|
889 |
+
|
890 |
+
.. [1] https://en.wikipedia.org/wiki/Harmonic_number
|
891 |
+
.. [2] https://functions.wolfram.com/GammaBetaErf/HarmonicNumber/
|
892 |
+
.. [3] https://functions.wolfram.com/GammaBetaErf/HarmonicNumber2/
|
893 |
+
|
894 |
+
"""
|
895 |
+
|
896 |
+
@classmethod
|
897 |
+
def eval(cls, n, m=None):
|
898 |
+
from sympy.functions.special.zeta_functions import zeta
|
899 |
+
if m is S.One:
|
900 |
+
return cls(n)
|
901 |
+
if m is None:
|
902 |
+
m = S.One
|
903 |
+
if n.is_zero:
|
904 |
+
return S.Zero
|
905 |
+
elif m.is_zero:
|
906 |
+
return n
|
907 |
+
elif n is S.Infinity:
|
908 |
+
if m.is_negative:
|
909 |
+
return S.NaN
|
910 |
+
elif is_le(m, S.One):
|
911 |
+
return S.Infinity
|
912 |
+
elif is_gt(m, S.One):
|
913 |
+
return zeta(m)
|
914 |
+
elif m.is_Integer and m.is_nonpositive:
|
915 |
+
return (bernoulli(1-m, n+1) - bernoulli(1-m)) / (1-m)
|
916 |
+
elif n.is_Integer:
|
917 |
+
if n.is_negative and (m.is_integer is False or m.is_nonpositive is False):
|
918 |
+
return S.ComplexInfinity if m is S.One else S.NaN
|
919 |
+
if n.is_nonnegative:
|
920 |
+
return Add(*(k**(-m) for k in range(1, int(n)+1)))
|
921 |
+
|
922 |
+
def _eval_rewrite_as_polygamma(self, n, m=S.One, **kwargs):
|
923 |
+
from sympy.functions.special.gamma_functions import gamma, polygamma
|
924 |
+
if m.is_integer and m.is_positive:
|
925 |
+
return Piecewise((polygamma(0, n+1) + S.EulerGamma, Eq(m, 1)),
|
926 |
+
(S.NegativeOne**m * (polygamma(m-1, 1) - polygamma(m-1, n+1)) /
|
927 |
+
gamma(m), True))
|
928 |
+
|
929 |
+
def _eval_rewrite_as_digamma(self, n, m=1, **kwargs):
|
930 |
+
from sympy.functions.special.gamma_functions import polygamma
|
931 |
+
return self.rewrite(polygamma)
|
932 |
+
|
933 |
+
def _eval_rewrite_as_trigamma(self, n, m=1, **kwargs):
|
934 |
+
from sympy.functions.special.gamma_functions import polygamma
|
935 |
+
return self.rewrite(polygamma)
|
936 |
+
|
937 |
+
def _eval_rewrite_as_Sum(self, n, m=None, **kwargs):
|
938 |
+
from sympy.concrete.summations import Sum
|
939 |
+
k = Dummy("k", integer=True)
|
940 |
+
if m is None:
|
941 |
+
m = S.One
|
942 |
+
return Sum(k**(-m), (k, 1, n))
|
943 |
+
|
944 |
+
def _eval_rewrite_as_zeta(self, n, m=S.One, **kwargs):
|
945 |
+
from sympy.functions.special.zeta_functions import zeta
|
946 |
+
from sympy.functions.special.gamma_functions import digamma
|
947 |
+
return Piecewise((digamma(n + 1) + S.EulerGamma, Eq(m, 1)),
|
948 |
+
(zeta(m) - zeta(m, n+1), True))
|
949 |
+
|
950 |
+
def _eval_expand_func(self, **hints):
|
951 |
+
from sympy.concrete.summations import Sum
|
952 |
+
n = self.args[0]
|
953 |
+
m = self.args[1] if len(self.args) == 2 else 1
|
954 |
+
|
955 |
+
if m == S.One:
|
956 |
+
if n.is_Add:
|
957 |
+
off = n.args[0]
|
958 |
+
nnew = n - off
|
959 |
+
if off.is_Integer and off.is_positive:
|
960 |
+
result = [S.One/(nnew + i) for i in range(off, 0, -1)] + [harmonic(nnew)]
|
961 |
+
return Add(*result)
|
962 |
+
elif off.is_Integer and off.is_negative:
|
963 |
+
result = [-S.One/(nnew + i) for i in range(0, off, -1)] + [harmonic(nnew)]
|
964 |
+
return Add(*result)
|
965 |
+
|
966 |
+
if n.is_Rational:
|
967 |
+
# Expansions for harmonic numbers at general rational arguments (u + p/q)
|
968 |
+
# Split n as u + p/q with p < q
|
969 |
+
p, q = n.as_numer_denom()
|
970 |
+
u = p // q
|
971 |
+
p = p - u * q
|
972 |
+
if u.is_nonnegative and p.is_positive and q.is_positive and p < q:
|
973 |
+
from sympy.functions.elementary.exponential import log
|
974 |
+
from sympy.functions.elementary.integers import floor
|
975 |
+
from sympy.functions.elementary.trigonometric import sin, cos, cot
|
976 |
+
k = Dummy("k")
|
977 |
+
t1 = q * Sum(1 / (q * k + p), (k, 0, u))
|
978 |
+
t2 = 2 * Sum(cos((2 * pi * p * k) / S(q)) *
|
979 |
+
log(sin((pi * k) / S(q))),
|
980 |
+
(k, 1, floor((q - 1) / S(2))))
|
981 |
+
t3 = (pi / 2) * cot((pi * p) / q) + log(2 * q)
|
982 |
+
return t1 + t2 - t3
|
983 |
+
|
984 |
+
return self
|
985 |
+
|
986 |
+
def _eval_rewrite_as_tractable(self, n, m=1, limitvar=None, **kwargs):
|
987 |
+
from sympy.functions.special.zeta_functions import zeta
|
988 |
+
from sympy.functions.special.gamma_functions import polygamma
|
989 |
+
pg = self.rewrite(polygamma)
|
990 |
+
if not isinstance(pg, harmonic):
|
991 |
+
return pg.rewrite("tractable", deep=True)
|
992 |
+
arg = m - S.One
|
993 |
+
if arg.is_nonzero:
|
994 |
+
return (zeta(m) - zeta(m, n+1)).rewrite("tractable", deep=True)
|
995 |
+
|
996 |
+
def _eval_evalf(self, prec):
|
997 |
+
if not all(x.is_number for x in self.args):
|
998 |
+
return
|
999 |
+
n = self.args[0]._to_mpmath(prec)
|
1000 |
+
m = (self.args[1] if len(self.args) > 1 else S.One)._to_mpmath(prec)
|
1001 |
+
if mp.isint(n) and n < 0:
|
1002 |
+
return S.NaN
|
1003 |
+
with workprec(prec):
|
1004 |
+
if m == 1:
|
1005 |
+
res = mp.harmonic(n)
|
1006 |
+
else:
|
1007 |
+
res = mp.zeta(m) - mp.zeta(m, n+1)
|
1008 |
+
return Expr._from_mpmath(res, prec)
|
1009 |
+
|
1010 |
+
def fdiff(self, argindex=1):
|
1011 |
+
from sympy.functions.special.zeta_functions import zeta
|
1012 |
+
if len(self.args) == 2:
|
1013 |
+
n, m = self.args
|
1014 |
+
else:
|
1015 |
+
n, m = self.args + (1,)
|
1016 |
+
if argindex == 1:
|
1017 |
+
return m * zeta(m+1, n+1)
|
1018 |
+
else:
|
1019 |
+
raise ArgumentIndexError
|
1020 |
+
|
1021 |
+
|
1022 |
+
#----------------------------------------------------------------------------#
|
1023 |
+
# #
|
1024 |
+
# Euler numbers #
|
1025 |
+
# #
|
1026 |
+
#----------------------------------------------------------------------------#
|
1027 |
+
|
1028 |
+
|
1029 |
+
class euler(Function):
|
1030 |
+
r"""
|
1031 |
+
Euler numbers / Euler polynomials / Euler function
|
1032 |
+
|
1033 |
+
The Euler numbers are given by:
|
1034 |
+
|
1035 |
+
.. math:: E_{2n} = I \sum_{k=1}^{2n+1} \sum_{j=0}^k \binom{k}{j}
|
1036 |
+
\frac{(-1)^j (k-2j)^{2n+1}}{2^k I^k k}
|
1037 |
+
|
1038 |
+
.. math:: E_{2n+1} = 0
|
1039 |
+
|
1040 |
+
Euler numbers and Euler polynomials are related by
|
1041 |
+
|
1042 |
+
.. math:: E_n = 2^n E_n\left(\frac{1}{2}\right).
|
1043 |
+
|
1044 |
+
We compute symbolic Euler polynomials using Appell sequences,
|
1045 |
+
but numerical evaluation of the Euler polynomial is computed
|
1046 |
+
more efficiently (and more accurately) using the mpmath library.
|
1047 |
+
|
1048 |
+
The Euler polynomials are special cases of the generalized Euler function,
|
1049 |
+
related to the Genocchi function as
|
1050 |
+
|
1051 |
+
.. math:: \operatorname{E}(s, a) = -\frac{\operatorname{G}(s+1, a)}{s+1}
|
1052 |
+
|
1053 |
+
with the limit of `\psi\left(\frac{a+1}{2}\right) - \psi\left(\frac{a}{2}\right)`
|
1054 |
+
being taken when `s = -1`. The (ordinary) Euler function interpolating
|
1055 |
+
the Euler numbers is then obtained as
|
1056 |
+
`\operatorname{E}(s) = 2^s \operatorname{E}\left(s, \frac{1}{2}\right)`.
|
1057 |
+
|
1058 |
+
* ``euler(n)`` gives the nth Euler number `E_n`.
|
1059 |
+
* ``euler(s)`` gives the Euler function `\operatorname{E}(s)`.
|
1060 |
+
* ``euler(n, x)`` gives the nth Euler polynomial `E_n(x)`.
|
1061 |
+
* ``euler(s, a)`` gives the generalized Euler function `\operatorname{E}(s, a)`.
|
1062 |
+
|
1063 |
+
Examples
|
1064 |
+
========
|
1065 |
+
|
1066 |
+
>>> from sympy import euler, Symbol, S
|
1067 |
+
>>> [euler(n) for n in range(10)]
|
1068 |
+
[1, 0, -1, 0, 5, 0, -61, 0, 1385, 0]
|
1069 |
+
>>> [2**n*euler(n,1) for n in range(10)]
|
1070 |
+
[1, 1, 0, -2, 0, 16, 0, -272, 0, 7936]
|
1071 |
+
>>> n = Symbol("n")
|
1072 |
+
>>> euler(n + 2*n)
|
1073 |
+
euler(3*n)
|
1074 |
+
|
1075 |
+
>>> x = Symbol("x")
|
1076 |
+
>>> euler(n, x)
|
1077 |
+
euler(n, x)
|
1078 |
+
|
1079 |
+
>>> euler(0, x)
|
1080 |
+
1
|
1081 |
+
>>> euler(1, x)
|
1082 |
+
x - 1/2
|
1083 |
+
>>> euler(2, x)
|
1084 |
+
x**2 - x
|
1085 |
+
>>> euler(3, x)
|
1086 |
+
x**3 - 3*x**2/2 + 1/4
|
1087 |
+
>>> euler(4, x)
|
1088 |
+
x**4 - 2*x**3 + x
|
1089 |
+
|
1090 |
+
>>> euler(12, S.Half)
|
1091 |
+
2702765/4096
|
1092 |
+
>>> euler(12)
|
1093 |
+
2702765
|
1094 |
+
|
1095 |
+
See Also
|
1096 |
+
========
|
1097 |
+
|
1098 |
+
andre, bell, bernoulli, catalan, fibonacci, harmonic, lucas, genocchi,
|
1099 |
+
partition, tribonacci, sympy.polys.appellseqs.euler_poly
|
1100 |
+
|
1101 |
+
References
|
1102 |
+
==========
|
1103 |
+
|
1104 |
+
.. [1] https://en.wikipedia.org/wiki/Euler_numbers
|
1105 |
+
.. [2] https://mathworld.wolfram.com/EulerNumber.html
|
1106 |
+
.. [3] https://en.wikipedia.org/wiki/Alternating_permutation
|
1107 |
+
.. [4] https://mathworld.wolfram.com/AlternatingPermutation.html
|
1108 |
+
|
1109 |
+
"""
|
1110 |
+
|
1111 |
+
@classmethod
|
1112 |
+
def eval(cls, n, x=None):
|
1113 |
+
if n.is_zero:
|
1114 |
+
return S.One
|
1115 |
+
elif n is S.NegativeOne:
|
1116 |
+
if x is None:
|
1117 |
+
return S.Pi/2
|
1118 |
+
from sympy.functions.special.gamma_functions import digamma
|
1119 |
+
return digamma((x+1)/2) - digamma(x/2)
|
1120 |
+
elif n.is_integer is False or n.is_nonnegative is False:
|
1121 |
+
return
|
1122 |
+
# Euler numbers
|
1123 |
+
elif x is None:
|
1124 |
+
if n.is_odd and n.is_positive:
|
1125 |
+
return S.Zero
|
1126 |
+
elif n.is_Number:
|
1127 |
+
from mpmath import mp
|
1128 |
+
n = n._to_mpmath(mp.prec)
|
1129 |
+
res = mp.eulernum(n, exact=True)
|
1130 |
+
return Integer(res)
|
1131 |
+
# Euler polynomials
|
1132 |
+
elif n.is_Number:
|
1133 |
+
return euler_poly(n, x)
|
1134 |
+
|
1135 |
+
def _eval_rewrite_as_Sum(self, n, x=None, **kwargs):
|
1136 |
+
from sympy.concrete.summations import Sum
|
1137 |
+
if x is None and n.is_even:
|
1138 |
+
k = Dummy("k", integer=True)
|
1139 |
+
j = Dummy("j", integer=True)
|
1140 |
+
n = n / 2
|
1141 |
+
Em = (S.ImaginaryUnit * Sum(Sum(binomial(k, j) * (S.NegativeOne**j *
|
1142 |
+
(k - 2*j)**(2*n + 1)) /
|
1143 |
+
(2**k*S.ImaginaryUnit**k * k), (j, 0, k)), (k, 1, 2*n + 1)))
|
1144 |
+
return Em
|
1145 |
+
if x:
|
1146 |
+
k = Dummy("k", integer=True)
|
1147 |
+
return Sum(binomial(n, k)*euler(k)/2**k*(x - S.Half)**(n - k), (k, 0, n))
|
1148 |
+
|
1149 |
+
def _eval_rewrite_as_genocchi(self, n, x=None, **kwargs):
|
1150 |
+
if x is None:
|
1151 |
+
return Piecewise((S.Pi/2, Eq(n, -1)),
|
1152 |
+
(-2**n * genocchi(n+1, S.Half) / (n+1), True))
|
1153 |
+
from sympy.functions.special.gamma_functions import digamma
|
1154 |
+
return Piecewise((digamma((x+1)/2) - digamma(x/2), Eq(n, -1)),
|
1155 |
+
(-genocchi(n+1, x) / (n+1), True))
|
1156 |
+
|
1157 |
+
def _eval_evalf(self, prec):
|
1158 |
+
if not all(i.is_number for i in self.args):
|
1159 |
+
return
|
1160 |
+
from mpmath import mp
|
1161 |
+
m, x = (self.args[0], None) if len(self.args) == 1 else self.args
|
1162 |
+
m = m._to_mpmath(prec)
|
1163 |
+
if x is not None:
|
1164 |
+
x = x._to_mpmath(prec)
|
1165 |
+
with workprec(prec):
|
1166 |
+
if mp.isint(m) and m >= 0:
|
1167 |
+
res = mp.eulernum(m) if x is None else mp.eulerpoly(m, x)
|
1168 |
+
else:
|
1169 |
+
if m == -1:
|
1170 |
+
res = mp.pi if x is None else mp.digamma((x+1)/2) - mp.digamma(x/2)
|
1171 |
+
else:
|
1172 |
+
y = 0.5 if x is None else x
|
1173 |
+
res = 2 * (mp.zeta(-m, y) - 2**(m+1) * mp.zeta(-m, (y+1)/2))
|
1174 |
+
if x is None:
|
1175 |
+
res *= 2**m
|
1176 |
+
return Expr._from_mpmath(res, prec)
|
1177 |
+
|
1178 |
+
|
1179 |
+
#----------------------------------------------------------------------------#
|
1180 |
+
# #
|
1181 |
+
# Catalan numbers #
|
1182 |
+
# #
|
1183 |
+
#----------------------------------------------------------------------------#
|
1184 |
+
|
1185 |
+
|
1186 |
+
class catalan(Function):
|
1187 |
+
r"""
|
1188 |
+
Catalan numbers
|
1189 |
+
|
1190 |
+
The `n^{th}` catalan number is given by:
|
1191 |
+
|
1192 |
+
.. math :: C_n = \frac{1}{n+1} \binom{2n}{n}
|
1193 |
+
|
1194 |
+
* ``catalan(n)`` gives the `n^{th}` Catalan number, `C_n`
|
1195 |
+
|
1196 |
+
Examples
|
1197 |
+
========
|
1198 |
+
|
1199 |
+
>>> from sympy import (Symbol, binomial, gamma, hyper,
|
1200 |
+
... catalan, diff, combsimp, Rational, I)
|
1201 |
+
|
1202 |
+
>>> [catalan(i) for i in range(1,10)]
|
1203 |
+
[1, 2, 5, 14, 42, 132, 429, 1430, 4862]
|
1204 |
+
|
1205 |
+
>>> n = Symbol("n", integer=True)
|
1206 |
+
|
1207 |
+
>>> catalan(n)
|
1208 |
+
catalan(n)
|
1209 |
+
|
1210 |
+
Catalan numbers can be transformed into several other, identical
|
1211 |
+
expressions involving other mathematical functions
|
1212 |
+
|
1213 |
+
>>> catalan(n).rewrite(binomial)
|
1214 |
+
binomial(2*n, n)/(n + 1)
|
1215 |
+
|
1216 |
+
>>> catalan(n).rewrite(gamma)
|
1217 |
+
4**n*gamma(n + 1/2)/(sqrt(pi)*gamma(n + 2))
|
1218 |
+
|
1219 |
+
>>> catalan(n).rewrite(hyper)
|
1220 |
+
hyper((1 - n, -n), (2,), 1)
|
1221 |
+
|
1222 |
+
For some non-integer values of n we can get closed form
|
1223 |
+
expressions by rewriting in terms of gamma functions:
|
1224 |
+
|
1225 |
+
>>> catalan(Rational(1, 2)).rewrite(gamma)
|
1226 |
+
8/(3*pi)
|
1227 |
+
|
1228 |
+
We can differentiate the Catalan numbers C(n) interpreted as a
|
1229 |
+
continuous real function in n:
|
1230 |
+
|
1231 |
+
>>> diff(catalan(n), n)
|
1232 |
+
(polygamma(0, n + 1/2) - polygamma(0, n + 2) + log(4))*catalan(n)
|
1233 |
+
|
1234 |
+
As a more advanced example consider the following ratio
|
1235 |
+
between consecutive numbers:
|
1236 |
+
|
1237 |
+
>>> combsimp((catalan(n + 1)/catalan(n)).rewrite(binomial))
|
1238 |
+
2*(2*n + 1)/(n + 2)
|
1239 |
+
|
1240 |
+
The Catalan numbers can be generalized to complex numbers:
|
1241 |
+
|
1242 |
+
>>> catalan(I).rewrite(gamma)
|
1243 |
+
4**I*gamma(1/2 + I)/(sqrt(pi)*gamma(2 + I))
|
1244 |
+
|
1245 |
+
and evaluated with arbitrary precision:
|
1246 |
+
|
1247 |
+
>>> catalan(I).evalf(20)
|
1248 |
+
0.39764993382373624267 - 0.020884341620842555705*I
|
1249 |
+
|
1250 |
+
See Also
|
1251 |
+
========
|
1252 |
+
|
1253 |
+
andre, bell, bernoulli, euler, fibonacci, harmonic, lucas, genocchi,
|
1254 |
+
partition, tribonacci, sympy.functions.combinatorial.factorials.binomial
|
1255 |
+
|
1256 |
+
References
|
1257 |
+
==========
|
1258 |
+
|
1259 |
+
.. [1] https://en.wikipedia.org/wiki/Catalan_number
|
1260 |
+
.. [2] https://mathworld.wolfram.com/CatalanNumber.html
|
1261 |
+
.. [3] https://functions.wolfram.com/GammaBetaErf/CatalanNumber/
|
1262 |
+
.. [4] http://geometer.org/mathcircles/catalan.pdf
|
1263 |
+
|
1264 |
+
"""
|
1265 |
+
|
1266 |
+
@classmethod
|
1267 |
+
def eval(cls, n):
|
1268 |
+
from sympy.functions.special.gamma_functions import gamma
|
1269 |
+
if (n.is_Integer and n.is_nonnegative) or \
|
1270 |
+
(n.is_noninteger and n.is_negative):
|
1271 |
+
return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
|
1272 |
+
|
1273 |
+
if (n.is_integer and n.is_negative):
|
1274 |
+
if (n + 1).is_negative:
|
1275 |
+
return S.Zero
|
1276 |
+
if (n + 1).is_zero:
|
1277 |
+
return Rational(-1, 2)
|
1278 |
+
|
1279 |
+
def fdiff(self, argindex=1):
|
1280 |
+
from sympy.functions.elementary.exponential import log
|
1281 |
+
from sympy.functions.special.gamma_functions import polygamma
|
1282 |
+
n = self.args[0]
|
1283 |
+
return catalan(n)*(polygamma(0, n + S.Half) - polygamma(0, n + 2) + log(4))
|
1284 |
+
|
1285 |
+
def _eval_rewrite_as_binomial(self, n, **kwargs):
|
1286 |
+
return binomial(2*n, n)/(n + 1)
|
1287 |
+
|
1288 |
+
def _eval_rewrite_as_factorial(self, n, **kwargs):
|
1289 |
+
return factorial(2*n) / (factorial(n+1) * factorial(n))
|
1290 |
+
|
1291 |
+
def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
|
1292 |
+
from sympy.functions.special.gamma_functions import gamma
|
1293 |
+
# The gamma function allows to generalize Catalan numbers to complex n
|
1294 |
+
return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
|
1295 |
+
|
1296 |
+
def _eval_rewrite_as_hyper(self, n, **kwargs):
|
1297 |
+
from sympy.functions.special.hyper import hyper
|
1298 |
+
return hyper([1 - n, -n], [2], 1)
|
1299 |
+
|
1300 |
+
def _eval_rewrite_as_Product(self, n, **kwargs):
|
1301 |
+
from sympy.concrete.products import Product
|
1302 |
+
if not (n.is_integer and n.is_nonnegative):
|
1303 |
+
return self
|
1304 |
+
k = Dummy('k', integer=True, positive=True)
|
1305 |
+
return Product((n + k) / k, (k, 2, n))
|
1306 |
+
|
1307 |
+
def _eval_is_integer(self):
|
1308 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
1309 |
+
return True
|
1310 |
+
|
1311 |
+
def _eval_is_positive(self):
|
1312 |
+
if self.args[0].is_nonnegative:
|
1313 |
+
return True
|
1314 |
+
|
1315 |
+
def _eval_is_composite(self):
|
1316 |
+
if self.args[0].is_integer and (self.args[0] - 3).is_positive:
|
1317 |
+
return True
|
1318 |
+
|
1319 |
+
def _eval_evalf(self, prec):
|
1320 |
+
from sympy.functions.special.gamma_functions import gamma
|
1321 |
+
if self.args[0].is_number:
|
1322 |
+
return self.rewrite(gamma)._eval_evalf(prec)
|
1323 |
+
|
1324 |
+
|
1325 |
+
#----------------------------------------------------------------------------#
|
1326 |
+
# #
|
1327 |
+
# Genocchi numbers #
|
1328 |
+
# #
|
1329 |
+
#----------------------------------------------------------------------------#
|
1330 |
+
|
1331 |
+
|
1332 |
+
class genocchi(Function):
|
1333 |
+
r"""
|
1334 |
+
Genocchi numbers / Genocchi polynomials / Genocchi function
|
1335 |
+
|
1336 |
+
The Genocchi numbers are a sequence of integers `G_n` that satisfy the
|
1337 |
+
relation:
|
1338 |
+
|
1339 |
+
.. math:: \frac{-2t}{1 + e^{-t}} = \sum_{n=0}^\infty \frac{G_n t^n}{n!}
|
1340 |
+
|
1341 |
+
They are related to the Bernoulli numbers by
|
1342 |
+
|
1343 |
+
.. math:: G_n = 2 (1 - 2^n) B_n
|
1344 |
+
|
1345 |
+
and generalize like the Bernoulli numbers to the Genocchi polynomials and
|
1346 |
+
function as
|
1347 |
+
|
1348 |
+
.. math:: \operatorname{G}(s, a) = 2 \left(\operatorname{B}(s, a) -
|
1349 |
+
2^s \operatorname{B}\left(s, \frac{a+1}{2}\right)\right)
|
1350 |
+
|
1351 |
+
.. versionchanged:: 1.12
|
1352 |
+
``genocchi(1)`` gives `-1` instead of `1`.
|
1353 |
+
|
1354 |
+
Examples
|
1355 |
+
========
|
1356 |
+
|
1357 |
+
>>> from sympy import genocchi, Symbol
|
1358 |
+
>>> [genocchi(n) for n in range(9)]
|
1359 |
+
[0, -1, -1, 0, 1, 0, -3, 0, 17]
|
1360 |
+
>>> n = Symbol('n', integer=True, positive=True)
|
1361 |
+
>>> genocchi(2*n + 1)
|
1362 |
+
0
|
1363 |
+
>>> x = Symbol('x')
|
1364 |
+
>>> genocchi(4, x)
|
1365 |
+
-4*x**3 + 6*x**2 - 1
|
1366 |
+
|
1367 |
+
See Also
|
1368 |
+
========
|
1369 |
+
|
1370 |
+
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, partition, tribonacci
|
1371 |
+
sympy.polys.appellseqs.genocchi_poly
|
1372 |
+
|
1373 |
+
References
|
1374 |
+
==========
|
1375 |
+
|
1376 |
+
.. [1] https://en.wikipedia.org/wiki/Genocchi_number
|
1377 |
+
.. [2] https://mathworld.wolfram.com/GenocchiNumber.html
|
1378 |
+
.. [3] Peter Luschny, "An introduction to the Bernoulli function",
|
1379 |
+
https://arxiv.org/abs/2009.06743
|
1380 |
+
|
1381 |
+
"""
|
1382 |
+
|
1383 |
+
@classmethod
|
1384 |
+
def eval(cls, n, x=None):
|
1385 |
+
if x is S.One:
|
1386 |
+
return cls(n)
|
1387 |
+
elif n.is_integer is False or n.is_nonnegative is False:
|
1388 |
+
return
|
1389 |
+
# Genocchi numbers
|
1390 |
+
elif x is None:
|
1391 |
+
if n.is_odd and (n-1).is_positive:
|
1392 |
+
return S.Zero
|
1393 |
+
elif n.is_Number:
|
1394 |
+
return 2 * (1-S(2)**n) * bernoulli(n)
|
1395 |
+
# Genocchi polynomials
|
1396 |
+
elif n.is_Number:
|
1397 |
+
return genocchi_poly(n, x)
|
1398 |
+
|
1399 |
+
def _eval_rewrite_as_bernoulli(self, n, x=1, **kwargs):
|
1400 |
+
if x == 1 and n.is_integer and n.is_nonnegative:
|
1401 |
+
return 2 * (1-S(2)**n) * bernoulli(n)
|
1402 |
+
return 2 * (bernoulli(n, x) - 2**n * bernoulli(n, (x+1) / 2))
|
1403 |
+
|
1404 |
+
def _eval_rewrite_as_dirichlet_eta(self, n, x=1, **kwargs):
|
1405 |
+
from sympy.functions.special.zeta_functions import dirichlet_eta
|
1406 |
+
return -2*n * dirichlet_eta(1-n, x)
|
1407 |
+
|
1408 |
+
def _eval_is_integer(self):
|
1409 |
+
if len(self.args) > 1 and self.args[1] != 1:
|
1410 |
+
return
|
1411 |
+
n = self.args[0]
|
1412 |
+
if n.is_integer and n.is_nonnegative:
|
1413 |
+
return True
|
1414 |
+
|
1415 |
+
def _eval_is_negative(self):
|
1416 |
+
if len(self.args) > 1 and self.args[1] != 1:
|
1417 |
+
return
|
1418 |
+
n = self.args[0]
|
1419 |
+
if n.is_integer and n.is_nonnegative:
|
1420 |
+
if n.is_odd:
|
1421 |
+
return fuzzy_not((n-1).is_positive)
|
1422 |
+
return (n/2).is_odd
|
1423 |
+
|
1424 |
+
def _eval_is_positive(self):
|
1425 |
+
if len(self.args) > 1 and self.args[1] != 1:
|
1426 |
+
return
|
1427 |
+
n = self.args[0]
|
1428 |
+
if n.is_integer and n.is_nonnegative:
|
1429 |
+
if n.is_zero or n.is_odd:
|
1430 |
+
return False
|
1431 |
+
return (n/2).is_even
|
1432 |
+
|
1433 |
+
def _eval_is_even(self):
|
1434 |
+
if len(self.args) > 1 and self.args[1] != 1:
|
1435 |
+
return
|
1436 |
+
n = self.args[0]
|
1437 |
+
if n.is_integer and n.is_nonnegative:
|
1438 |
+
if n.is_even:
|
1439 |
+
return n.is_zero
|
1440 |
+
return (n-1).is_positive
|
1441 |
+
|
1442 |
+
def _eval_is_odd(self):
|
1443 |
+
if len(self.args) > 1 and self.args[1] != 1:
|
1444 |
+
return
|
1445 |
+
n = self.args[0]
|
1446 |
+
if n.is_integer and n.is_nonnegative:
|
1447 |
+
if n.is_even:
|
1448 |
+
return fuzzy_not(n.is_zero)
|
1449 |
+
return fuzzy_not((n-1).is_positive)
|
1450 |
+
|
1451 |
+
def _eval_is_prime(self):
|
1452 |
+
if len(self.args) > 1 and self.args[1] != 1:
|
1453 |
+
return
|
1454 |
+
n = self.args[0]
|
1455 |
+
# only G_6 = -3 and G_8 = 17 are prime,
|
1456 |
+
# but SymPy does not consider negatives as prime
|
1457 |
+
# so only n=8 is tested
|
1458 |
+
return (n-8).is_zero
|
1459 |
+
|
1460 |
+
def _eval_evalf(self, prec):
|
1461 |
+
if all(i.is_number for i in self.args):
|
1462 |
+
return self.rewrite(bernoulli)._eval_evalf(prec)
|
1463 |
+
|
1464 |
+
|
1465 |
+
#----------------------------------------------------------------------------#
|
1466 |
+
# #
|
1467 |
+
# Andre numbers #
|
1468 |
+
# #
|
1469 |
+
#----------------------------------------------------------------------------#
|
1470 |
+
|
1471 |
+
|
1472 |
+
class andre(Function):
|
1473 |
+
r"""
|
1474 |
+
Andre numbers / Andre function
|
1475 |
+
|
1476 |
+
The Andre number `\mathcal{A}_n` is Luschny's name for half the number of
|
1477 |
+
*alternating permutations* on `n` elements, where a permutation is alternating
|
1478 |
+
if adjacent elements alternately compare "greater" and "smaller" going from
|
1479 |
+
left to right. For example, `2 < 3 > 1 < 4` is an alternating permutation.
|
1480 |
+
|
1481 |
+
This sequence is A000111 in the OEIS, which assigns the names *up/down numbers*
|
1482 |
+
and *Euler zigzag numbers*. It satisfies a recurrence relation similar to that
|
1483 |
+
for the Catalan numbers, with `\mathcal{A}_0 = 1` and
|
1484 |
+
|
1485 |
+
.. math:: 2 \mathcal{A}_{n+1} = \sum_{k=0}^n \binom{n}{k} \mathcal{A}_k \mathcal{A}_{n-k}
|
1486 |
+
|
1487 |
+
The Bernoulli and Euler numbers are signed transformations of the odd- and
|
1488 |
+
even-indexed elements of this sequence respectively:
|
1489 |
+
|
1490 |
+
.. math :: \operatorname{B}_{2k} = \frac{2k \mathcal{A}_{2k-1}}{(-4)^k - (-16)^k}
|
1491 |
+
|
1492 |
+
.. math :: \operatorname{E}_{2k} = (-1)^k \mathcal{A}_{2k}
|
1493 |
+
|
1494 |
+
Like the Bernoulli and Euler numbers, the Andre numbers are interpolated by the
|
1495 |
+
entire Andre function:
|
1496 |
+
|
1497 |
+
.. math :: \mathcal{A}(s) = (-i)^{s+1} \operatorname{Li}_{-s}(i) +
|
1498 |
+
i^{s+1} \operatorname{Li}_{-s}(-i) = \\ \frac{2 \Gamma(s+1)}{(2\pi)^{s+1}}
|
1499 |
+
(\zeta(s+1, 1/4) - \zeta(s+1, 3/4) \cos{\pi s})
|
1500 |
+
|
1501 |
+
Examples
|
1502 |
+
========
|
1503 |
+
|
1504 |
+
>>> from sympy import andre, euler, bernoulli
|
1505 |
+
>>> [andre(n) for n in range(11)]
|
1506 |
+
[1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]
|
1507 |
+
>>> [(-1)**k * andre(2*k) for k in range(7)]
|
1508 |
+
[1, -1, 5, -61, 1385, -50521, 2702765]
|
1509 |
+
>>> [euler(2*k) for k in range(7)]
|
1510 |
+
[1, -1, 5, -61, 1385, -50521, 2702765]
|
1511 |
+
>>> [andre(2*k-1) * (2*k) / ((-4)**k - (-16)**k) for k in range(1, 8)]
|
1512 |
+
[1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6]
|
1513 |
+
>>> [bernoulli(2*k) for k in range(1, 8)]
|
1514 |
+
[1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6]
|
1515 |
+
|
1516 |
+
See Also
|
1517 |
+
========
|
1518 |
+
|
1519 |
+
bernoulli, catalan, euler, sympy.polys.appellseqs.andre_poly
|
1520 |
+
|
1521 |
+
References
|
1522 |
+
==========
|
1523 |
+
|
1524 |
+
.. [1] https://en.wikipedia.org/wiki/Alternating_permutation
|
1525 |
+
.. [2] https://mathworld.wolfram.com/EulerZigzagNumber.html
|
1526 |
+
.. [3] Peter Luschny, "An introduction to the Bernoulli function",
|
1527 |
+
https://arxiv.org/abs/2009.06743
|
1528 |
+
"""
|
1529 |
+
|
1530 |
+
@classmethod
|
1531 |
+
def eval(cls, n):
|
1532 |
+
if n is S.NaN:
|
1533 |
+
return S.NaN
|
1534 |
+
elif n is S.Infinity:
|
1535 |
+
return S.Infinity
|
1536 |
+
if n.is_zero:
|
1537 |
+
return S.One
|
1538 |
+
elif n == -1:
|
1539 |
+
return -log(2)
|
1540 |
+
elif n == -2:
|
1541 |
+
return -2*S.Catalan
|
1542 |
+
elif n.is_Integer:
|
1543 |
+
if n.is_nonnegative and n.is_even:
|
1544 |
+
return abs(euler(n))
|
1545 |
+
elif n.is_odd:
|
1546 |
+
from sympy.functions.special.zeta_functions import zeta
|
1547 |
+
m = -n-1
|
1548 |
+
return I**m * Rational(1-2**m, 4**m) * zeta(-n)
|
1549 |
+
|
1550 |
+
def _eval_rewrite_as_zeta(self, s, **kwargs):
|
1551 |
+
from sympy.functions.elementary.trigonometric import cos
|
1552 |
+
from sympy.functions.special.gamma_functions import gamma
|
1553 |
+
from sympy.functions.special.zeta_functions import zeta
|
1554 |
+
return 2 * gamma(s+1) / (2*pi)**(s+1) * \
|
1555 |
+
(zeta(s+1, S.One/4) - cos(pi*s) * zeta(s+1, S(3)/4))
|
1556 |
+
|
1557 |
+
def _eval_rewrite_as_polylog(self, s, **kwargs):
|
1558 |
+
from sympy.functions.special.zeta_functions import polylog
|
1559 |
+
return (-I)**(s+1) * polylog(-s, I) + I**(s+1) * polylog(-s, -I)
|
1560 |
+
|
1561 |
+
def _eval_is_integer(self):
|
1562 |
+
n = self.args[0]
|
1563 |
+
if n.is_integer and n.is_nonnegative:
|
1564 |
+
return True
|
1565 |
+
|
1566 |
+
def _eval_is_positive(self):
|
1567 |
+
if self.args[0].is_nonnegative:
|
1568 |
+
return True
|
1569 |
+
|
1570 |
+
def _eval_evalf(self, prec):
|
1571 |
+
if not self.args[0].is_number:
|
1572 |
+
return
|
1573 |
+
s = self.args[0]._to_mpmath(prec+12)
|
1574 |
+
with workprec(prec+12):
|
1575 |
+
sp, cp = mp.sinpi(s/2), mp.cospi(s/2)
|
1576 |
+
res = 2*mp.dirichlet(-s, (-sp, cp, sp, -cp))
|
1577 |
+
return Expr._from_mpmath(res, prec)
|
1578 |
+
|
1579 |
+
|
1580 |
+
#----------------------------------------------------------------------------#
|
1581 |
+
# #
|
1582 |
+
# Partition numbers #
|
1583 |
+
# #
|
1584 |
+
#----------------------------------------------------------------------------#
|
1585 |
+
|
1586 |
+
_npartition = [1, 1]
|
1587 |
+
class partition(Function):
|
1588 |
+
r"""
|
1589 |
+
Partition numbers
|
1590 |
+
|
1591 |
+
The Partition numbers are a sequence of integers `p_n` that represent the
|
1592 |
+
number of distinct ways of representing `n` as a sum of natural numbers
|
1593 |
+
(with order irrelevant). The generating function for `p_n` is given by:
|
1594 |
+
|
1595 |
+
.. math:: \sum_{n=0}^\infty p_n x^n = \prod_{k=1}^\infty (1 - x^k)^{-1}
|
1596 |
+
|
1597 |
+
Examples
|
1598 |
+
========
|
1599 |
+
|
1600 |
+
>>> from sympy import partition, Symbol
|
1601 |
+
>>> [partition(n) for n in range(9)]
|
1602 |
+
[1, 1, 2, 3, 5, 7, 11, 15, 22]
|
1603 |
+
>>> n = Symbol('n', integer=True, negative=True)
|
1604 |
+
>>> partition(n)
|
1605 |
+
0
|
1606 |
+
|
1607 |
+
See Also
|
1608 |
+
========
|
1609 |
+
|
1610 |
+
bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, tribonacci
|
1611 |
+
|
1612 |
+
References
|
1613 |
+
==========
|
1614 |
+
|
1615 |
+
.. [1] https://en.wikipedia.org/wiki/Partition_(number_theory%29
|
1616 |
+
.. [2] https://en.wikipedia.org/wiki/Pentagonal_number_theorem
|
1617 |
+
|
1618 |
+
"""
|
1619 |
+
|
1620 |
+
@staticmethod
|
1621 |
+
def _partition(n):
|
1622 |
+
L = len(_npartition)
|
1623 |
+
if n < L:
|
1624 |
+
return _npartition[n]
|
1625 |
+
# lengthen cache
|
1626 |
+
for _n in range(L, n + 1):
|
1627 |
+
v, p, i = 0, 0, 0
|
1628 |
+
while 1:
|
1629 |
+
s = 0
|
1630 |
+
p += 3*i + 1 # p = pentagonal number: 1, 5, 12, ...
|
1631 |
+
if _n >= p:
|
1632 |
+
s += _npartition[_n - p]
|
1633 |
+
i += 1
|
1634 |
+
gp = p + i # gp = generalized pentagonal: 2, 7, 15, ...
|
1635 |
+
if _n >= gp:
|
1636 |
+
s += _npartition[_n - gp]
|
1637 |
+
if s == 0:
|
1638 |
+
break
|
1639 |
+
else:
|
1640 |
+
v += s if i%2 == 1 else -s
|
1641 |
+
_npartition.append(v)
|
1642 |
+
return v
|
1643 |
+
|
1644 |
+
@classmethod
|
1645 |
+
def eval(cls, n):
|
1646 |
+
is_int = n.is_integer
|
1647 |
+
if is_int == False:
|
1648 |
+
raise ValueError("Partition numbers are defined only for "
|
1649 |
+
"integers")
|
1650 |
+
elif is_int:
|
1651 |
+
if n.is_negative:
|
1652 |
+
return S.Zero
|
1653 |
+
|
1654 |
+
if n.is_zero or (n - 1).is_zero:
|
1655 |
+
return S.One
|
1656 |
+
|
1657 |
+
if n.is_Integer:
|
1658 |
+
return Integer(cls._partition(n))
|
1659 |
+
|
1660 |
+
|
1661 |
+
def _eval_is_integer(self):
|
1662 |
+
if self.args[0].is_integer:
|
1663 |
+
return True
|
1664 |
+
|
1665 |
+
def _eval_is_negative(self):
|
1666 |
+
if self.args[0].is_integer:
|
1667 |
+
return False
|
1668 |
+
|
1669 |
+
def _eval_is_positive(self):
|
1670 |
+
n = self.args[0]
|
1671 |
+
if n.is_nonnegative and n.is_integer:
|
1672 |
+
return True
|
1673 |
+
|
1674 |
+
|
1675 |
+
#######################################################################
|
1676 |
+
###
|
1677 |
+
### Functions for enumerating partitions, permutations and combinations
|
1678 |
+
###
|
1679 |
+
#######################################################################
|
1680 |
+
|
1681 |
+
|
1682 |
+
class _MultisetHistogram(tuple):
|
1683 |
+
pass
|
1684 |
+
|
1685 |
+
|
1686 |
+
_N = -1
|
1687 |
+
_ITEMS = -2
|
1688 |
+
_M = slice(None, _ITEMS)
|
1689 |
+
|
1690 |
+
|
1691 |
+
def _multiset_histogram(n):
|
1692 |
+
"""Return tuple used in permutation and combination counting. Input
|
1693 |
+
is a dictionary giving items with counts as values or a sequence of
|
1694 |
+
items (which need not be sorted).
|
1695 |
+
|
1696 |
+
The data is stored in a class deriving from tuple so it is easily
|
1697 |
+
recognized and so it can be converted easily to a list.
|
1698 |
+
"""
|
1699 |
+
if isinstance(n, dict): # item: count
|
1700 |
+
if not all(isinstance(v, int) and v >= 0 for v in n.values()):
|
1701 |
+
raise ValueError
|
1702 |
+
tot = sum(n.values())
|
1703 |
+
items = sum(1 for k in n if n[k] > 0)
|
1704 |
+
return _MultisetHistogram([n[k] for k in n if n[k] > 0] + [items, tot])
|
1705 |
+
else:
|
1706 |
+
n = list(n)
|
1707 |
+
s = set(n)
|
1708 |
+
lens = len(s)
|
1709 |
+
lenn = len(n)
|
1710 |
+
if lens == lenn:
|
1711 |
+
n = [1]*lenn + [lenn, lenn]
|
1712 |
+
return _MultisetHistogram(n)
|
1713 |
+
m = dict(zip(s, range(lens)))
|
1714 |
+
d = dict(zip(range(lens), (0,)*lens))
|
1715 |
+
for i in n:
|
1716 |
+
d[m[i]] += 1
|
1717 |
+
return _multiset_histogram(d)
|
1718 |
+
|
1719 |
+
|
1720 |
+
def nP(n, k=None, replacement=False):
|
1721 |
+
"""Return the number of permutations of ``n`` items taken ``k`` at a time.
|
1722 |
+
|
1723 |
+
Possible values for ``n``:
|
1724 |
+
|
1725 |
+
integer - set of length ``n``
|
1726 |
+
|
1727 |
+
sequence - converted to a multiset internally
|
1728 |
+
|
1729 |
+
multiset - {element: multiplicity}
|
1730 |
+
|
1731 |
+
If ``k`` is None then the total of all permutations of length 0
|
1732 |
+
through the number of items represented by ``n`` will be returned.
|
1733 |
+
|
1734 |
+
If ``replacement`` is True then a given item can appear more than once
|
1735 |
+
in the ``k`` items. (For example, for 'ab' permutations of 2 would
|
1736 |
+
include 'aa', 'ab', 'ba' and 'bb'.) The multiplicity of elements in
|
1737 |
+
``n`` is ignored when ``replacement`` is True but the total number
|
1738 |
+
of elements is considered since no element can appear more times than
|
1739 |
+
the number of elements in ``n``.
|
1740 |
+
|
1741 |
+
Examples
|
1742 |
+
========
|
1743 |
+
|
1744 |
+
>>> from sympy.functions.combinatorial.numbers import nP
|
1745 |
+
>>> from sympy.utilities.iterables import multiset_permutations, multiset
|
1746 |
+
>>> nP(3, 2)
|
1747 |
+
6
|
1748 |
+
>>> nP('abc', 2) == nP(multiset('abc'), 2) == 6
|
1749 |
+
True
|
1750 |
+
>>> nP('aab', 2)
|
1751 |
+
3
|
1752 |
+
>>> nP([1, 2, 2], 2)
|
1753 |
+
3
|
1754 |
+
>>> [nP(3, i) for i in range(4)]
|
1755 |
+
[1, 3, 6, 6]
|
1756 |
+
>>> nP(3) == sum(_)
|
1757 |
+
True
|
1758 |
+
|
1759 |
+
When ``replacement`` is True, each item can have multiplicity
|
1760 |
+
equal to the length represented by ``n``:
|
1761 |
+
|
1762 |
+
>>> nP('aabc', replacement=True)
|
1763 |
+
121
|
1764 |
+
>>> [len(list(multiset_permutations('aaaabbbbcccc', i))) for i in range(5)]
|
1765 |
+
[1, 3, 9, 27, 81]
|
1766 |
+
>>> sum(_)
|
1767 |
+
121
|
1768 |
+
|
1769 |
+
See Also
|
1770 |
+
========
|
1771 |
+
sympy.utilities.iterables.multiset_permutations
|
1772 |
+
|
1773 |
+
References
|
1774 |
+
==========
|
1775 |
+
|
1776 |
+
.. [1] https://en.wikipedia.org/wiki/Permutation
|
1777 |
+
|
1778 |
+
"""
|
1779 |
+
try:
|
1780 |
+
n = as_int(n)
|
1781 |
+
except ValueError:
|
1782 |
+
return Integer(_nP(_multiset_histogram(n), k, replacement))
|
1783 |
+
return Integer(_nP(n, k, replacement))
|
1784 |
+
|
1785 |
+
|
1786 |
+
@cacheit
|
1787 |
+
def _nP(n, k=None, replacement=False):
|
1788 |
+
|
1789 |
+
if k == 0:
|
1790 |
+
return 1
|
1791 |
+
if isinstance(n, SYMPY_INTS): # n different items
|
1792 |
+
# assert n >= 0
|
1793 |
+
if k is None:
|
1794 |
+
return sum(_nP(n, i, replacement) for i in range(n + 1))
|
1795 |
+
elif replacement:
|
1796 |
+
return n**k
|
1797 |
+
elif k > n:
|
1798 |
+
return 0
|
1799 |
+
elif k == n:
|
1800 |
+
return factorial(k)
|
1801 |
+
elif k == 1:
|
1802 |
+
return n
|
1803 |
+
else:
|
1804 |
+
# assert k >= 0
|
1805 |
+
return _product(n - k + 1, n)
|
1806 |
+
elif isinstance(n, _MultisetHistogram):
|
1807 |
+
if k is None:
|
1808 |
+
return sum(_nP(n, i, replacement) for i in range(n[_N] + 1))
|
1809 |
+
elif replacement:
|
1810 |
+
return n[_ITEMS]**k
|
1811 |
+
elif k == n[_N]:
|
1812 |
+
return factorial(k)/prod([factorial(i) for i in n[_M] if i > 1])
|
1813 |
+
elif k > n[_N]:
|
1814 |
+
return 0
|
1815 |
+
elif k == 1:
|
1816 |
+
return n[_ITEMS]
|
1817 |
+
else:
|
1818 |
+
# assert k >= 0
|
1819 |
+
tot = 0
|
1820 |
+
n = list(n)
|
1821 |
+
for i in range(len(n[_M])):
|
1822 |
+
if not n[i]:
|
1823 |
+
continue
|
1824 |
+
n[_N] -= 1
|
1825 |
+
if n[i] == 1:
|
1826 |
+
n[i] = 0
|
1827 |
+
n[_ITEMS] -= 1
|
1828 |
+
tot += _nP(_MultisetHistogram(n), k - 1)
|
1829 |
+
n[_ITEMS] += 1
|
1830 |
+
n[i] = 1
|
1831 |
+
else:
|
1832 |
+
n[i] -= 1
|
1833 |
+
tot += _nP(_MultisetHistogram(n), k - 1)
|
1834 |
+
n[i] += 1
|
1835 |
+
n[_N] += 1
|
1836 |
+
return tot
|
1837 |
+
|
1838 |
+
|
1839 |
+
@cacheit
|
1840 |
+
def _AOP_product(n):
|
1841 |
+
"""for n = (m1, m2, .., mk) return the coefficients of the polynomial,
|
1842 |
+
prod(sum(x**i for i in range(nj + 1)) for nj in n); i.e. the coefficients
|
1843 |
+
of the product of AOPs (all-one polynomials) or order given in n. The
|
1844 |
+
resulting coefficient corresponding to x**r is the number of r-length
|
1845 |
+
combinations of sum(n) elements with multiplicities given in n.
|
1846 |
+
The coefficients are given as a default dictionary (so if a query is made
|
1847 |
+
for a key that is not present, 0 will be returned).
|
1848 |
+
|
1849 |
+
Examples
|
1850 |
+
========
|
1851 |
+
|
1852 |
+
>>> from sympy.functions.combinatorial.numbers import _AOP_product
|
1853 |
+
>>> from sympy.abc import x
|
1854 |
+
>>> n = (2, 2, 3) # e.g. aabbccc
|
1855 |
+
>>> prod = ((x**2 + x + 1)*(x**2 + x + 1)*(x**3 + x**2 + x + 1)).expand()
|
1856 |
+
>>> c = _AOP_product(n); dict(c)
|
1857 |
+
{0: 1, 1: 3, 2: 6, 3: 8, 4: 8, 5: 6, 6: 3, 7: 1}
|
1858 |
+
>>> [c[i] for i in range(8)] == [prod.coeff(x, i) for i in range(8)]
|
1859 |
+
True
|
1860 |
+
|
1861 |
+
The generating poly used here is the same as that listed in
|
1862 |
+
https://tinyurl.com/cep849r, but in a refactored form.
|
1863 |
+
|
1864 |
+
"""
|
1865 |
+
|
1866 |
+
n = list(n)
|
1867 |
+
ord = sum(n)
|
1868 |
+
need = (ord + 2)//2
|
1869 |
+
rv = [1]*(n.pop() + 1)
|
1870 |
+
rv.extend((0,) * (need - len(rv)))
|
1871 |
+
rv = rv[:need]
|
1872 |
+
while n:
|
1873 |
+
ni = n.pop()
|
1874 |
+
N = ni + 1
|
1875 |
+
was = rv[:]
|
1876 |
+
for i in range(1, min(N, len(rv))):
|
1877 |
+
rv[i] += rv[i - 1]
|
1878 |
+
for i in range(N, need):
|
1879 |
+
rv[i] += rv[i - 1] - was[i - N]
|
1880 |
+
rev = list(reversed(rv))
|
1881 |
+
if ord % 2:
|
1882 |
+
rv = rv + rev
|
1883 |
+
else:
|
1884 |
+
rv[-1:] = rev
|
1885 |
+
d = defaultdict(int)
|
1886 |
+
for i, r in enumerate(rv):
|
1887 |
+
d[i] = r
|
1888 |
+
return d
|
1889 |
+
|
1890 |
+
|
1891 |
+
def nC(n, k=None, replacement=False):
|
1892 |
+
"""Return the number of combinations of ``n`` items taken ``k`` at a time.
|
1893 |
+
|
1894 |
+
Possible values for ``n``:
|
1895 |
+
|
1896 |
+
integer - set of length ``n``
|
1897 |
+
|
1898 |
+
sequence - converted to a multiset internally
|
1899 |
+
|
1900 |
+
multiset - {element: multiplicity}
|
1901 |
+
|
1902 |
+
If ``k`` is None then the total of all combinations of length 0
|
1903 |
+
through the number of items represented in ``n`` will be returned.
|
1904 |
+
|
1905 |
+
If ``replacement`` is True then a given item can appear more than once
|
1906 |
+
in the ``k`` items. (For example, for 'ab' sets of 2 would include 'aa',
|
1907 |
+
'ab', and 'bb'.) The multiplicity of elements in ``n`` is ignored when
|
1908 |
+
``replacement`` is True but the total number of elements is considered
|
1909 |
+
since no element can appear more times than the number of elements in
|
1910 |
+
``n``.
|
1911 |
+
|
1912 |
+
Examples
|
1913 |
+
========
|
1914 |
+
|
1915 |
+
>>> from sympy.functions.combinatorial.numbers import nC
|
1916 |
+
>>> from sympy.utilities.iterables import multiset_combinations
|
1917 |
+
>>> nC(3, 2)
|
1918 |
+
3
|
1919 |
+
>>> nC('abc', 2)
|
1920 |
+
3
|
1921 |
+
>>> nC('aab', 2)
|
1922 |
+
2
|
1923 |
+
|
1924 |
+
When ``replacement`` is True, each item can have multiplicity
|
1925 |
+
equal to the length represented by ``n``:
|
1926 |
+
|
1927 |
+
>>> nC('aabc', replacement=True)
|
1928 |
+
35
|
1929 |
+
>>> [len(list(multiset_combinations('aaaabbbbcccc', i))) for i in range(5)]
|
1930 |
+
[1, 3, 6, 10, 15]
|
1931 |
+
>>> sum(_)
|
1932 |
+
35
|
1933 |
+
|
1934 |
+
If there are ``k`` items with multiplicities ``m_1, m_2, ..., m_k``
|
1935 |
+
then the total of all combinations of length 0 through ``k`` is the
|
1936 |
+
product, ``(m_1 + 1)*(m_2 + 1)*...*(m_k + 1)``. When the multiplicity
|
1937 |
+
of each item is 1 (i.e., k unique items) then there are 2**k
|
1938 |
+
combinations. For example, if there are 4 unique items, the total number
|
1939 |
+
of combinations is 16:
|
1940 |
+
|
1941 |
+
>>> sum(nC(4, i) for i in range(5))
|
1942 |
+
16
|
1943 |
+
|
1944 |
+
See Also
|
1945 |
+
========
|
1946 |
+
|
1947 |
+
sympy.utilities.iterables.multiset_combinations
|
1948 |
+
|
1949 |
+
References
|
1950 |
+
==========
|
1951 |
+
|
1952 |
+
.. [1] https://en.wikipedia.org/wiki/Combination
|
1953 |
+
.. [2] https://tinyurl.com/cep849r
|
1954 |
+
|
1955 |
+
"""
|
1956 |
+
|
1957 |
+
if isinstance(n, SYMPY_INTS):
|
1958 |
+
if k is None:
|
1959 |
+
if not replacement:
|
1960 |
+
return 2**n
|
1961 |
+
return sum(nC(n, i, replacement) for i in range(n + 1))
|
1962 |
+
if k < 0:
|
1963 |
+
raise ValueError("k cannot be negative")
|
1964 |
+
if replacement:
|
1965 |
+
return binomial(n + k - 1, k)
|
1966 |
+
return binomial(n, k)
|
1967 |
+
if isinstance(n, _MultisetHistogram):
|
1968 |
+
N = n[_N]
|
1969 |
+
if k is None:
|
1970 |
+
if not replacement:
|
1971 |
+
return prod(m + 1 for m in n[_M])
|
1972 |
+
return sum(nC(n, i, replacement) for i in range(N + 1))
|
1973 |
+
elif replacement:
|
1974 |
+
return nC(n[_ITEMS], k, replacement)
|
1975 |
+
# assert k >= 0
|
1976 |
+
elif k in (1, N - 1):
|
1977 |
+
return n[_ITEMS]
|
1978 |
+
elif k in (0, N):
|
1979 |
+
return 1
|
1980 |
+
return _AOP_product(tuple(n[_M]))[k]
|
1981 |
+
else:
|
1982 |
+
return nC(_multiset_histogram(n), k, replacement)
|
1983 |
+
|
1984 |
+
|
1985 |
+
def _eval_stirling1(n, k):
|
1986 |
+
if n == k == 0:
|
1987 |
+
return S.One
|
1988 |
+
if 0 in (n, k):
|
1989 |
+
return S.Zero
|
1990 |
+
|
1991 |
+
# some special values
|
1992 |
+
if n == k:
|
1993 |
+
return S.One
|
1994 |
+
elif k == n - 1:
|
1995 |
+
return binomial(n, 2)
|
1996 |
+
elif k == n - 2:
|
1997 |
+
return (3*n - 1)*binomial(n, 3)/4
|
1998 |
+
elif k == n - 3:
|
1999 |
+
return binomial(n, 2)*binomial(n, 4)
|
2000 |
+
|
2001 |
+
return _stirling1(n, k)
|
2002 |
+
|
2003 |
+
|
2004 |
+
@cacheit
|
2005 |
+
def _stirling1(n, k):
|
2006 |
+
row = [0, 1]+[0]*(k-1) # for n = 1
|
2007 |
+
for i in range(2, n+1):
|
2008 |
+
for j in range(min(k,i), 0, -1):
|
2009 |
+
row[j] = (i-1) * row[j] + row[j-1]
|
2010 |
+
return Integer(row[k])
|
2011 |
+
|
2012 |
+
|
2013 |
+
def _eval_stirling2(n, k):
|
2014 |
+
if n == k == 0:
|
2015 |
+
return S.One
|
2016 |
+
if 0 in (n, k):
|
2017 |
+
return S.Zero
|
2018 |
+
|
2019 |
+
# some special values
|
2020 |
+
if n == k:
|
2021 |
+
return S.One
|
2022 |
+
elif k == n - 1:
|
2023 |
+
return binomial(n, 2)
|
2024 |
+
elif k == 1:
|
2025 |
+
return S.One
|
2026 |
+
elif k == 2:
|
2027 |
+
return Integer(2**(n - 1) - 1)
|
2028 |
+
|
2029 |
+
return _stirling2(n, k)
|
2030 |
+
|
2031 |
+
|
2032 |
+
@cacheit
|
2033 |
+
def _stirling2(n, k):
|
2034 |
+
row = [0, 1]+[0]*(k-1) # for n = 1
|
2035 |
+
for i in range(2, n+1):
|
2036 |
+
for j in range(min(k,i), 0, -1):
|
2037 |
+
row[j] = j * row[j] + row[j-1]
|
2038 |
+
return Integer(row[k])
|
2039 |
+
|
2040 |
+
|
2041 |
+
def stirling(n, k, d=None, kind=2, signed=False):
|
2042 |
+
r"""Return Stirling number $S(n, k)$ of the first or second (default) kind.
|
2043 |
+
|
2044 |
+
The sum of all Stirling numbers of the second kind for $k = 1$
|
2045 |
+
through $n$ is ``bell(n)``. The recurrence relationship for these numbers
|
2046 |
+
is:
|
2047 |
+
|
2048 |
+
.. math :: {0 \brace 0} = 1; {n \brace 0} = {0 \brace k} = 0;
|
2049 |
+
|
2050 |
+
.. math :: {{n+1} \brace k} = j {n \brace k} + {n \brace {k-1}}
|
2051 |
+
|
2052 |
+
where $j$ is:
|
2053 |
+
$n$ for Stirling numbers of the first kind,
|
2054 |
+
$-n$ for signed Stirling numbers of the first kind,
|
2055 |
+
$k$ for Stirling numbers of the second kind.
|
2056 |
+
|
2057 |
+
The first kind of Stirling number counts the number of permutations of
|
2058 |
+
``n`` distinct items that have ``k`` cycles; the second kind counts the
|
2059 |
+
ways in which ``n`` distinct items can be partitioned into ``k`` parts.
|
2060 |
+
If ``d`` is given, the "reduced Stirling number of the second kind" is
|
2061 |
+
returned: $S^{d}(n, k) = S(n - d + 1, k - d + 1)$ with $n \ge k \ge d$.
|
2062 |
+
(This counts the ways to partition $n$ consecutive integers into $k$
|
2063 |
+
groups with no pairwise difference less than $d$. See example below.)
|
2064 |
+
|
2065 |
+
To obtain the signed Stirling numbers of the first kind, use keyword
|
2066 |
+
``signed=True``. Using this keyword automatically sets ``kind`` to 1.
|
2067 |
+
|
2068 |
+
Examples
|
2069 |
+
========
|
2070 |
+
|
2071 |
+
>>> from sympy.functions.combinatorial.numbers import stirling, bell
|
2072 |
+
>>> from sympy.combinatorics import Permutation
|
2073 |
+
>>> from sympy.utilities.iterables import multiset_partitions, permutations
|
2074 |
+
|
2075 |
+
First kind (unsigned by default):
|
2076 |
+
|
2077 |
+
>>> [stirling(6, i, kind=1) for i in range(7)]
|
2078 |
+
[0, 120, 274, 225, 85, 15, 1]
|
2079 |
+
>>> perms = list(permutations(range(4)))
|
2080 |
+
>>> [sum(Permutation(p).cycles == i for p in perms) for i in range(5)]
|
2081 |
+
[0, 6, 11, 6, 1]
|
2082 |
+
>>> [stirling(4, i, kind=1) for i in range(5)]
|
2083 |
+
[0, 6, 11, 6, 1]
|
2084 |
+
|
2085 |
+
First kind (signed):
|
2086 |
+
|
2087 |
+
>>> [stirling(4, i, signed=True) for i in range(5)]
|
2088 |
+
[0, -6, 11, -6, 1]
|
2089 |
+
|
2090 |
+
Second kind:
|
2091 |
+
|
2092 |
+
>>> [stirling(10, i) for i in range(12)]
|
2093 |
+
[0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1, 0]
|
2094 |
+
>>> sum(_) == bell(10)
|
2095 |
+
True
|
2096 |
+
>>> len(list(multiset_partitions(range(4), 2))) == stirling(4, 2)
|
2097 |
+
True
|
2098 |
+
|
2099 |
+
Reduced second kind:
|
2100 |
+
|
2101 |
+
>>> from sympy import subsets, oo
|
2102 |
+
>>> def delta(p):
|
2103 |
+
... if len(p) == 1:
|
2104 |
+
... return oo
|
2105 |
+
... return min(abs(i[0] - i[1]) for i in subsets(p, 2))
|
2106 |
+
>>> parts = multiset_partitions(range(5), 3)
|
2107 |
+
>>> d = 2
|
2108 |
+
>>> sum(1 for p in parts if all(delta(i) >= d for i in p))
|
2109 |
+
7
|
2110 |
+
>>> stirling(5, 3, 2)
|
2111 |
+
7
|
2112 |
+
|
2113 |
+
See Also
|
2114 |
+
========
|
2115 |
+
sympy.utilities.iterables.multiset_partitions
|
2116 |
+
|
2117 |
+
|
2118 |
+
References
|
2119 |
+
==========
|
2120 |
+
|
2121 |
+
.. [1] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
|
2122 |
+
.. [2] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
|
2123 |
+
|
2124 |
+
"""
|
2125 |
+
# TODO: make this a class like bell()
|
2126 |
+
|
2127 |
+
n = as_int(n)
|
2128 |
+
k = as_int(k)
|
2129 |
+
if n < 0:
|
2130 |
+
raise ValueError('n must be nonnegative')
|
2131 |
+
if k > n:
|
2132 |
+
return S.Zero
|
2133 |
+
if d:
|
2134 |
+
# assert k >= d
|
2135 |
+
# kind is ignored -- only kind=2 is supported
|
2136 |
+
return _eval_stirling2(n - d + 1, k - d + 1)
|
2137 |
+
elif signed:
|
2138 |
+
# kind is ignored -- only kind=1 is supported
|
2139 |
+
return S.NegativeOne**(n - k)*_eval_stirling1(n, k)
|
2140 |
+
|
2141 |
+
if kind == 1:
|
2142 |
+
return _eval_stirling1(n, k)
|
2143 |
+
elif kind == 2:
|
2144 |
+
return _eval_stirling2(n, k)
|
2145 |
+
else:
|
2146 |
+
raise ValueError('kind must be 1 or 2, not %s' % k)
|
2147 |
+
|
2148 |
+
|
2149 |
+
@cacheit
|
2150 |
+
def _nT(n, k):
|
2151 |
+
"""Return the partitions of ``n`` items into ``k`` parts. This
|
2152 |
+
is used by ``nT`` for the case when ``n`` is an integer."""
|
2153 |
+
# really quick exits
|
2154 |
+
if k > n or k < 0:
|
2155 |
+
return 0
|
2156 |
+
if k in (1, n):
|
2157 |
+
return 1
|
2158 |
+
if k == 0:
|
2159 |
+
return 0
|
2160 |
+
# exits that could be done below but this is quicker
|
2161 |
+
if k == 2:
|
2162 |
+
return n//2
|
2163 |
+
d = n - k
|
2164 |
+
if d <= 3:
|
2165 |
+
return d
|
2166 |
+
# quick exit
|
2167 |
+
if 3*k >= n: # or, equivalently, 2*k >= d
|
2168 |
+
# all the information needed in this case
|
2169 |
+
# will be in the cache needed to calculate
|
2170 |
+
# partition(d), so...
|
2171 |
+
# update cache
|
2172 |
+
tot = partition._partition(d)
|
2173 |
+
# and correct for values not needed
|
2174 |
+
if d - k > 0:
|
2175 |
+
tot -= sum(_npartition[:d - k])
|
2176 |
+
return tot
|
2177 |
+
# regular exit
|
2178 |
+
# nT(n, k) = Sum(nT(n - k, m), (m, 1, k));
|
2179 |
+
# calculate needed nT(i, j) values
|
2180 |
+
p = [1]*d
|
2181 |
+
for i in range(2, k + 1):
|
2182 |
+
for m in range(i + 1, d):
|
2183 |
+
p[m] += p[m - i]
|
2184 |
+
d -= 1
|
2185 |
+
# if p[0] were appended to the end of p then the last
|
2186 |
+
# k values of p are the nT(n, j) values for 0 < j < k in reverse
|
2187 |
+
# order p[-1] = nT(n, 1), p[-2] = nT(n, 2), etc.... Instead of
|
2188 |
+
# putting the 1 from p[0] there, however, it is simply added to
|
2189 |
+
# the sum below which is valid for 1 < k <= n//2
|
2190 |
+
return (1 + sum(p[1 - k:]))
|
2191 |
+
|
2192 |
+
|
2193 |
+
def nT(n, k=None):
|
2194 |
+
"""Return the number of ``k``-sized partitions of ``n`` items.
|
2195 |
+
|
2196 |
+
Possible values for ``n``:
|
2197 |
+
|
2198 |
+
integer - ``n`` identical items
|
2199 |
+
|
2200 |
+
sequence - converted to a multiset internally
|
2201 |
+
|
2202 |
+
multiset - {element: multiplicity}
|
2203 |
+
|
2204 |
+
Note: the convention for ``nT`` is different than that of ``nC`` and
|
2205 |
+
``nP`` in that
|
2206 |
+
here an integer indicates ``n`` *identical* items instead of a set of
|
2207 |
+
length ``n``; this is in keeping with the ``partitions`` function which
|
2208 |
+
treats its integer-``n`` input like a list of ``n`` 1s. One can use
|
2209 |
+
``range(n)`` for ``n`` to indicate ``n`` distinct items.
|
2210 |
+
|
2211 |
+
If ``k`` is None then the total number of ways to partition the elements
|
2212 |
+
represented in ``n`` will be returned.
|
2213 |
+
|
2214 |
+
Examples
|
2215 |
+
========
|
2216 |
+
|
2217 |
+
>>> from sympy.functions.combinatorial.numbers import nT
|
2218 |
+
|
2219 |
+
Partitions of the given multiset:
|
2220 |
+
|
2221 |
+
>>> [nT('aabbc', i) for i in range(1, 7)]
|
2222 |
+
[1, 8, 11, 5, 1, 0]
|
2223 |
+
>>> nT('aabbc') == sum(_)
|
2224 |
+
True
|
2225 |
+
|
2226 |
+
>>> [nT("mississippi", i) for i in range(1, 12)]
|
2227 |
+
[1, 74, 609, 1521, 1768, 1224, 579, 197, 50, 9, 1]
|
2228 |
+
|
2229 |
+
Partitions when all items are identical:
|
2230 |
+
|
2231 |
+
>>> [nT(5, i) for i in range(1, 6)]
|
2232 |
+
[1, 2, 2, 1, 1]
|
2233 |
+
>>> nT('1'*5) == sum(_)
|
2234 |
+
True
|
2235 |
+
|
2236 |
+
When all items are different:
|
2237 |
+
|
2238 |
+
>>> [nT(range(5), i) for i in range(1, 6)]
|
2239 |
+
[1, 15, 25, 10, 1]
|
2240 |
+
>>> nT(range(5)) == sum(_)
|
2241 |
+
True
|
2242 |
+
|
2243 |
+
Partitions of an integer expressed as a sum of positive integers:
|
2244 |
+
|
2245 |
+
>>> from sympy import partition
|
2246 |
+
>>> partition(4)
|
2247 |
+
5
|
2248 |
+
>>> nT(4, 1) + nT(4, 2) + nT(4, 3) + nT(4, 4)
|
2249 |
+
5
|
2250 |
+
>>> nT('1'*4)
|
2251 |
+
5
|
2252 |
+
|
2253 |
+
See Also
|
2254 |
+
========
|
2255 |
+
sympy.utilities.iterables.partitions
|
2256 |
+
sympy.utilities.iterables.multiset_partitions
|
2257 |
+
sympy.functions.combinatorial.numbers.partition
|
2258 |
+
|
2259 |
+
References
|
2260 |
+
==========
|
2261 |
+
|
2262 |
+
.. [1] https://web.archive.org/web/20210507012732/https://teaching.csse.uwa.edu.au/units/CITS7209/partition.pdf
|
2263 |
+
|
2264 |
+
"""
|
2265 |
+
|
2266 |
+
if isinstance(n, SYMPY_INTS):
|
2267 |
+
# n identical items
|
2268 |
+
if k is None:
|
2269 |
+
return partition(n)
|
2270 |
+
if isinstance(k, SYMPY_INTS):
|
2271 |
+
n = as_int(n)
|
2272 |
+
k = as_int(k)
|
2273 |
+
return Integer(_nT(n, k))
|
2274 |
+
if not isinstance(n, _MultisetHistogram):
|
2275 |
+
try:
|
2276 |
+
# if n contains hashable items there is some
|
2277 |
+
# quick handling that can be done
|
2278 |
+
u = len(set(n))
|
2279 |
+
if u <= 1:
|
2280 |
+
return nT(len(n), k)
|
2281 |
+
elif u == len(n):
|
2282 |
+
n = range(u)
|
2283 |
+
raise TypeError
|
2284 |
+
except TypeError:
|
2285 |
+
n = _multiset_histogram(n)
|
2286 |
+
N = n[_N]
|
2287 |
+
if k is None and N == 1:
|
2288 |
+
return 1
|
2289 |
+
if k in (1, N):
|
2290 |
+
return 1
|
2291 |
+
if k == 2 or N == 2 and k is None:
|
2292 |
+
m, r = divmod(N, 2)
|
2293 |
+
rv = sum(nC(n, i) for i in range(1, m + 1))
|
2294 |
+
if not r:
|
2295 |
+
rv -= nC(n, m)//2
|
2296 |
+
if k is None:
|
2297 |
+
rv += 1 # for k == 1
|
2298 |
+
return rv
|
2299 |
+
if N == n[_ITEMS]:
|
2300 |
+
# all distinct
|
2301 |
+
if k is None:
|
2302 |
+
return bell(N)
|
2303 |
+
return stirling(N, k)
|
2304 |
+
m = MultisetPartitionTraverser()
|
2305 |
+
if k is None:
|
2306 |
+
return m.count_partitions(n[_M])
|
2307 |
+
# MultisetPartitionTraverser does not have a range-limited count
|
2308 |
+
# method, so need to enumerate and count
|
2309 |
+
tot = 0
|
2310 |
+
for discard in m.enum_range(n[_M], k-1, k):
|
2311 |
+
tot += 1
|
2312 |
+
return tot
|
2313 |
+
|
2314 |
+
|
2315 |
+
#-----------------------------------------------------------------------------#
|
2316 |
+
# #
|
2317 |
+
# Motzkin numbers #
|
2318 |
+
# #
|
2319 |
+
#-----------------------------------------------------------------------------#
|
2320 |
+
|
2321 |
+
|
2322 |
+
class motzkin(Function):
|
2323 |
+
"""
|
2324 |
+
The nth Motzkin number is the number
|
2325 |
+
of ways of drawing non-intersecting chords
|
2326 |
+
between n points on a circle (not necessarily touching
|
2327 |
+
every point by a chord). The Motzkin numbers are named
|
2328 |
+
after Theodore Motzkin and have diverse applications
|
2329 |
+
in geometry, combinatorics and number theory.
|
2330 |
+
|
2331 |
+
Motzkin numbers are the integer sequence defined by the
|
2332 |
+
initial terms `M_0 = 1`, `M_1 = 1` and the two-term recurrence relation
|
2333 |
+
`M_n = \frac{2*n + 1}{n + 2} * M_{n-1} + \frac{3n - 3}{n + 2} * M_{n-2}`.
|
2334 |
+
|
2335 |
+
|
2336 |
+
Examples
|
2337 |
+
========
|
2338 |
+
|
2339 |
+
>>> from sympy import motzkin
|
2340 |
+
|
2341 |
+
>>> motzkin.is_motzkin(5)
|
2342 |
+
False
|
2343 |
+
>>> motzkin.find_motzkin_numbers_in_range(2,300)
|
2344 |
+
[2, 4, 9, 21, 51, 127]
|
2345 |
+
>>> motzkin.find_motzkin_numbers_in_range(2,900)
|
2346 |
+
[2, 4, 9, 21, 51, 127, 323, 835]
|
2347 |
+
>>> motzkin.find_first_n_motzkins(10)
|
2348 |
+
[1, 1, 2, 4, 9, 21, 51, 127, 323, 835]
|
2349 |
+
|
2350 |
+
|
2351 |
+
References
|
2352 |
+
==========
|
2353 |
+
|
2354 |
+
.. [1] https://en.wikipedia.org/wiki/Motzkin_number
|
2355 |
+
.. [2] https://mathworld.wolfram.com/MotzkinNumber.html
|
2356 |
+
|
2357 |
+
"""
|
2358 |
+
|
2359 |
+
@staticmethod
|
2360 |
+
def is_motzkin(n):
|
2361 |
+
try:
|
2362 |
+
n = as_int(n)
|
2363 |
+
except ValueError:
|
2364 |
+
return False
|
2365 |
+
if n > 0:
|
2366 |
+
if n in (1, 2):
|
2367 |
+
return True
|
2368 |
+
|
2369 |
+
tn1 = 1
|
2370 |
+
tn = 2
|
2371 |
+
i = 3
|
2372 |
+
while tn < n:
|
2373 |
+
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
|
2374 |
+
i += 1
|
2375 |
+
tn1 = tn
|
2376 |
+
tn = a
|
2377 |
+
|
2378 |
+
if tn == n:
|
2379 |
+
return True
|
2380 |
+
else:
|
2381 |
+
return False
|
2382 |
+
|
2383 |
+
else:
|
2384 |
+
return False
|
2385 |
+
|
2386 |
+
@staticmethod
|
2387 |
+
def find_motzkin_numbers_in_range(x, y):
|
2388 |
+
if 0 <= x <= y:
|
2389 |
+
motzkins = []
|
2390 |
+
if x <= 1 <= y:
|
2391 |
+
motzkins.append(1)
|
2392 |
+
tn1 = 1
|
2393 |
+
tn = 2
|
2394 |
+
i = 3
|
2395 |
+
while tn <= y:
|
2396 |
+
if tn >= x:
|
2397 |
+
motzkins.append(tn)
|
2398 |
+
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
|
2399 |
+
i += 1
|
2400 |
+
tn1 = tn
|
2401 |
+
tn = int(a)
|
2402 |
+
|
2403 |
+
return motzkins
|
2404 |
+
|
2405 |
+
else:
|
2406 |
+
raise ValueError('The provided range is not valid. This condition should satisfy x <= y')
|
2407 |
+
|
2408 |
+
@staticmethod
|
2409 |
+
def find_first_n_motzkins(n):
|
2410 |
+
try:
|
2411 |
+
n = as_int(n)
|
2412 |
+
except ValueError:
|
2413 |
+
raise ValueError('The provided number must be a positive integer')
|
2414 |
+
if n < 0:
|
2415 |
+
raise ValueError('The provided number must be a positive integer')
|
2416 |
+
motzkins = [1]
|
2417 |
+
if n >= 1:
|
2418 |
+
motzkins.append(1)
|
2419 |
+
tn1 = 1
|
2420 |
+
tn = 2
|
2421 |
+
i = 3
|
2422 |
+
while i <= n:
|
2423 |
+
motzkins.append(tn)
|
2424 |
+
a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
|
2425 |
+
i += 1
|
2426 |
+
tn1 = tn
|
2427 |
+
tn = int(a)
|
2428 |
+
|
2429 |
+
return motzkins
|
2430 |
+
|
2431 |
+
@staticmethod
|
2432 |
+
@recurrence_memo([S.One, S.One])
|
2433 |
+
def _motzkin(n, prev):
|
2434 |
+
return ((2*n + 1)*prev[-1] + (3*n - 3)*prev[-2]) // (n + 2)
|
2435 |
+
|
2436 |
+
@classmethod
|
2437 |
+
def eval(cls, n):
|
2438 |
+
try:
|
2439 |
+
n = as_int(n)
|
2440 |
+
except ValueError:
|
2441 |
+
raise ValueError('The provided number must be a positive integer')
|
2442 |
+
if n < 0:
|
2443 |
+
raise ValueError('The provided number must be a positive integer')
|
2444 |
+
return Integer(cls._motzkin(n - 1))
|
2445 |
+
|
2446 |
+
|
2447 |
+
def nD(i=None, brute=None, *, n=None, m=None):
|
2448 |
+
"""return the number of derangements for: ``n`` unique items, ``i``
|
2449 |
+
items (as a sequence or multiset), or multiplicities, ``m`` given
|
2450 |
+
as a sequence or multiset.
|
2451 |
+
|
2452 |
+
Examples
|
2453 |
+
========
|
2454 |
+
|
2455 |
+
>>> from sympy.utilities.iterables import generate_derangements as enum
|
2456 |
+
>>> from sympy.functions.combinatorial.numbers import nD
|
2457 |
+
|
2458 |
+
A derangement ``d`` of sequence ``s`` has all ``d[i] != s[i]``:
|
2459 |
+
|
2460 |
+
>>> set([''.join(i) for i in enum('abc')])
|
2461 |
+
{'bca', 'cab'}
|
2462 |
+
>>> nD('abc')
|
2463 |
+
2
|
2464 |
+
|
2465 |
+
Input as iterable or dictionary (multiset form) is accepted:
|
2466 |
+
|
2467 |
+
>>> assert nD([1, 2, 2, 3, 3, 3]) == nD({1: 1, 2: 2, 3: 3})
|
2468 |
+
|
2469 |
+
By default, a brute-force enumeration and count of multiset permutations
|
2470 |
+
is only done if there are fewer than 9 elements. There may be cases when
|
2471 |
+
there is high multiplicity with few unique elements that will benefit
|
2472 |
+
from a brute-force enumeration, too. For this reason, the `brute`
|
2473 |
+
keyword (default None) is provided. When False, the brute-force
|
2474 |
+
enumeration will never be used. When True, it will always be used.
|
2475 |
+
|
2476 |
+
>>> nD('1111222233', brute=True)
|
2477 |
+
44
|
2478 |
+
|
2479 |
+
For convenience, one may specify ``n`` distinct items using the
|
2480 |
+
``n`` keyword:
|
2481 |
+
|
2482 |
+
>>> assert nD(n=3) == nD('abc') == 2
|
2483 |
+
|
2484 |
+
Since the number of derangments depends on the multiplicity of the
|
2485 |
+
elements and not the elements themselves, it may be more convenient
|
2486 |
+
to give a list or multiset of multiplicities using keyword ``m``:
|
2487 |
+
|
2488 |
+
>>> assert nD('abc') == nD(m=(1,1,1)) == nD(m={1:3}) == 2
|
2489 |
+
|
2490 |
+
"""
|
2491 |
+
from sympy.integrals.integrals import integrate
|
2492 |
+
from sympy.functions.special.polynomials import laguerre
|
2493 |
+
from sympy.abc import x
|
2494 |
+
def ok(x):
|
2495 |
+
if not isinstance(x, SYMPY_INTS):
|
2496 |
+
raise TypeError('expecting integer values')
|
2497 |
+
if x < 0:
|
2498 |
+
raise ValueError('value must not be negative')
|
2499 |
+
return True
|
2500 |
+
|
2501 |
+
if (i, n, m).count(None) != 2:
|
2502 |
+
raise ValueError('enter only 1 of i, n, or m')
|
2503 |
+
if i is not None:
|
2504 |
+
if isinstance(i, SYMPY_INTS):
|
2505 |
+
raise TypeError('items must be a list or dictionary')
|
2506 |
+
if not i:
|
2507 |
+
return S.Zero
|
2508 |
+
if type(i) is not dict:
|
2509 |
+
s = list(i)
|
2510 |
+
ms = multiset(s)
|
2511 |
+
elif type(i) is dict:
|
2512 |
+
all(ok(_) for _ in i.values())
|
2513 |
+
ms = {k: v for k, v in i.items() if v}
|
2514 |
+
s = None
|
2515 |
+
if not ms:
|
2516 |
+
return S.Zero
|
2517 |
+
N = sum(ms.values())
|
2518 |
+
counts = multiset(ms.values())
|
2519 |
+
nkey = len(ms)
|
2520 |
+
elif n is not None:
|
2521 |
+
ok(n)
|
2522 |
+
if not n:
|
2523 |
+
return S.Zero
|
2524 |
+
return subfactorial(n)
|
2525 |
+
elif m is not None:
|
2526 |
+
if isinstance(m, dict):
|
2527 |
+
all(ok(i) and ok(j) for i, j in m.items())
|
2528 |
+
counts = {k: v for k, v in m.items() if k*v}
|
2529 |
+
elif iterable(m) or isinstance(m, str):
|
2530 |
+
m = list(m)
|
2531 |
+
all(ok(i) for i in m)
|
2532 |
+
counts = multiset([i for i in m if i])
|
2533 |
+
else:
|
2534 |
+
raise TypeError('expecting iterable')
|
2535 |
+
if not counts:
|
2536 |
+
return S.Zero
|
2537 |
+
N = sum(k*v for k, v in counts.items())
|
2538 |
+
nkey = sum(counts.values())
|
2539 |
+
s = None
|
2540 |
+
big = int(max(counts))
|
2541 |
+
if big == 1: # no repetition
|
2542 |
+
return subfactorial(nkey)
|
2543 |
+
nval = len(counts)
|
2544 |
+
if big*2 > N:
|
2545 |
+
return S.Zero
|
2546 |
+
if big*2 == N:
|
2547 |
+
if nkey == 2 and nval == 1:
|
2548 |
+
return S.One # aaabbb
|
2549 |
+
if nkey - 1 == big: # one element repeated
|
2550 |
+
return factorial(big) # e.g. abc part of abcddd
|
2551 |
+
if N < 9 and brute is None or brute:
|
2552 |
+
# for all possibilities, this was found to be faster
|
2553 |
+
if s is None:
|
2554 |
+
s = []
|
2555 |
+
i = 0
|
2556 |
+
for m, v in counts.items():
|
2557 |
+
for j in range(v):
|
2558 |
+
s.extend([i]*m)
|
2559 |
+
i += 1
|
2560 |
+
return Integer(sum(1 for i in multiset_derangements(s)))
|
2561 |
+
from sympy.functions.elementary.exponential import exp
|
2562 |
+
return Integer(abs(integrate(exp(-x)*Mul(*[
|
2563 |
+
laguerre(i, x)**m for i, m in counts.items()]), (x, 0, oo))))
|
venv/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (203 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_factorials.cpython-310.pyc
ADDED
Binary file (22 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_numbers.cpython-310.pyc
ADDED
Binary file (35.9 kB). View file
|
|
venv/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.concrete.products import Product
|
2 |
+
from sympy.core.function import expand_func
|
3 |
+
from sympy.core.mod import Mod
|
4 |
+
from sympy.core.mul import Mul
|
5 |
+
from sympy.core import EulerGamma
|
6 |
+
from sympy.core.numbers import (Float, I, Rational, nan, oo, pi, zoo)
|
7 |
+
from sympy.core.relational import Eq
|
8 |
+
from sympy.core.singleton import S
|
9 |
+
from sympy.core.symbol import (Dummy, Symbol, symbols)
|
10 |
+
from sympy.functions.combinatorial.factorials import (ff, rf, binomial, factorial, factorial2)
|
11 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
12 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
13 |
+
from sympy.functions.special.gamma_functions import (gamma, polygamma)
|
14 |
+
from sympy.polys.polytools import Poly
|
15 |
+
from sympy.series.order import O
|
16 |
+
from sympy.simplify.simplify import simplify
|
17 |
+
from sympy.core.expr import unchanged
|
18 |
+
from sympy.core.function import ArgumentIndexError
|
19 |
+
from sympy.functions.combinatorial.factorials import subfactorial
|
20 |
+
from sympy.functions.special.gamma_functions import uppergamma
|
21 |
+
from sympy.testing.pytest import XFAIL, raises, slow
|
22 |
+
|
23 |
+
#Solves and Fixes Issue #10388 - This is the updated test for the same solved issue
|
24 |
+
|
25 |
+
def test_rf_eval_apply():
|
26 |
+
x, y = symbols('x,y')
|
27 |
+
n, k = symbols('n k', integer=True)
|
28 |
+
m = Symbol('m', integer=True, nonnegative=True)
|
29 |
+
|
30 |
+
assert rf(nan, y) is nan
|
31 |
+
assert rf(x, nan) is nan
|
32 |
+
|
33 |
+
assert unchanged(rf, x, y)
|
34 |
+
|
35 |
+
assert rf(oo, 0) == 1
|
36 |
+
assert rf(-oo, 0) == 1
|
37 |
+
|
38 |
+
assert rf(oo, 6) is oo
|
39 |
+
assert rf(-oo, 7) is -oo
|
40 |
+
assert rf(-oo, 6) is oo
|
41 |
+
|
42 |
+
assert rf(oo, -6) is oo
|
43 |
+
assert rf(-oo, -7) is oo
|
44 |
+
|
45 |
+
assert rf(-1, pi) == 0
|
46 |
+
assert rf(-5, 1 + I) == 0
|
47 |
+
|
48 |
+
assert unchanged(rf, -3, k)
|
49 |
+
assert unchanged(rf, x, Symbol('k', integer=False))
|
50 |
+
assert rf(-3, Symbol('k', integer=False)) == 0
|
51 |
+
assert rf(Symbol('x', negative=True, integer=True), Symbol('k', integer=False)) == 0
|
52 |
+
|
53 |
+
assert rf(x, 0) == 1
|
54 |
+
assert rf(x, 1) == x
|
55 |
+
assert rf(x, 2) == x*(x + 1)
|
56 |
+
assert rf(x, 3) == x*(x + 1)*(x + 2)
|
57 |
+
assert rf(x, 5) == x*(x + 1)*(x + 2)*(x + 3)*(x + 4)
|
58 |
+
|
59 |
+
assert rf(x, -1) == 1/(x - 1)
|
60 |
+
assert rf(x, -2) == 1/((x - 1)*(x - 2))
|
61 |
+
assert rf(x, -3) == 1/((x - 1)*(x - 2)*(x - 3))
|
62 |
+
|
63 |
+
assert rf(1, 100) == factorial(100)
|
64 |
+
|
65 |
+
assert rf(x**2 + 3*x, 2) == (x**2 + 3*x)*(x**2 + 3*x + 1)
|
66 |
+
assert isinstance(rf(x**2 + 3*x, 2), Mul)
|
67 |
+
assert rf(x**3 + x, -2) == 1/((x**3 + x - 1)*(x**3 + x - 2))
|
68 |
+
|
69 |
+
assert rf(Poly(x**2 + 3*x, x), 2) == Poly(x**4 + 8*x**3 + 19*x**2 + 12*x, x)
|
70 |
+
assert isinstance(rf(Poly(x**2 + 3*x, x), 2), Poly)
|
71 |
+
raises(ValueError, lambda: rf(Poly(x**2 + 3*x, x, y), 2))
|
72 |
+
assert rf(Poly(x**3 + x, x), -2) == 1/(x**6 - 9*x**5 + 35*x**4 - 75*x**3 + 94*x**2 - 66*x + 20)
|
73 |
+
raises(ValueError, lambda: rf(Poly(x**3 + x, x, y), -2))
|
74 |
+
|
75 |
+
assert rf(x, m).is_integer is None
|
76 |
+
assert rf(n, k).is_integer is None
|
77 |
+
assert rf(n, m).is_integer is True
|
78 |
+
assert rf(n, k + pi).is_integer is False
|
79 |
+
assert rf(n, m + pi).is_integer is False
|
80 |
+
assert rf(pi, m).is_integer is False
|
81 |
+
|
82 |
+
def check(x, k, o, n):
|
83 |
+
a, b = Dummy(), Dummy()
|
84 |
+
r = lambda x, k: o(a, b).rewrite(n).subs({a:x,b:k})
|
85 |
+
for i in range(-5,5):
|
86 |
+
for j in range(-5,5):
|
87 |
+
assert o(i, j) == r(i, j), (o, n, i, j)
|
88 |
+
check(x, k, rf, ff)
|
89 |
+
check(x, k, rf, binomial)
|
90 |
+
check(n, k, rf, factorial)
|
91 |
+
check(x, y, rf, factorial)
|
92 |
+
check(x, y, rf, binomial)
|
93 |
+
|
94 |
+
assert rf(x, k).rewrite(ff) == ff(x + k - 1, k)
|
95 |
+
assert rf(x, k).rewrite(gamma) == Piecewise(
|
96 |
+
(gamma(k + x)/gamma(x), x > 0),
|
97 |
+
((-1)**k*gamma(1 - x)/gamma(-k - x + 1), True))
|
98 |
+
assert rf(5, k).rewrite(gamma) == gamma(k + 5)/24
|
99 |
+
assert rf(x, k).rewrite(binomial) == factorial(k)*binomial(x + k - 1, k)
|
100 |
+
assert rf(n, k).rewrite(factorial) == Piecewise(
|
101 |
+
(factorial(k + n - 1)/factorial(n - 1), n > 0),
|
102 |
+
((-1)**k*factorial(-n)/factorial(-k - n), True))
|
103 |
+
assert rf(5, k).rewrite(factorial) == factorial(k + 4)/24
|
104 |
+
assert rf(x, y).rewrite(factorial) == rf(x, y)
|
105 |
+
assert rf(x, y).rewrite(binomial) == rf(x, y)
|
106 |
+
|
107 |
+
import random
|
108 |
+
from mpmath import rf as mpmath_rf
|
109 |
+
for i in range(100):
|
110 |
+
x = -500 + 500 * random.random()
|
111 |
+
k = -500 + 500 * random.random()
|
112 |
+
assert (abs(mpmath_rf(x, k) - rf(x, k)) < 10**(-15))
|
113 |
+
|
114 |
+
|
115 |
+
def test_ff_eval_apply():
|
116 |
+
x, y = symbols('x,y')
|
117 |
+
n, k = symbols('n k', integer=True)
|
118 |
+
m = Symbol('m', integer=True, nonnegative=True)
|
119 |
+
|
120 |
+
assert ff(nan, y) is nan
|
121 |
+
assert ff(x, nan) is nan
|
122 |
+
|
123 |
+
assert unchanged(ff, x, y)
|
124 |
+
|
125 |
+
assert ff(oo, 0) == 1
|
126 |
+
assert ff(-oo, 0) == 1
|
127 |
+
|
128 |
+
assert ff(oo, 6) is oo
|
129 |
+
assert ff(-oo, 7) is -oo
|
130 |
+
assert ff(-oo, 6) is oo
|
131 |
+
|
132 |
+
assert ff(oo, -6) is oo
|
133 |
+
assert ff(-oo, -7) is oo
|
134 |
+
|
135 |
+
assert ff(x, 0) == 1
|
136 |
+
assert ff(x, 1) == x
|
137 |
+
assert ff(x, 2) == x*(x - 1)
|
138 |
+
assert ff(x, 3) == x*(x - 1)*(x - 2)
|
139 |
+
assert ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4)
|
140 |
+
|
141 |
+
assert ff(x, -1) == 1/(x + 1)
|
142 |
+
assert ff(x, -2) == 1/((x + 1)*(x + 2))
|
143 |
+
assert ff(x, -3) == 1/((x + 1)*(x + 2)*(x + 3))
|
144 |
+
|
145 |
+
assert ff(100, 100) == factorial(100)
|
146 |
+
|
147 |
+
assert ff(2*x**2 - 5*x, 2) == (2*x**2 - 5*x)*(2*x**2 - 5*x - 1)
|
148 |
+
assert isinstance(ff(2*x**2 - 5*x, 2), Mul)
|
149 |
+
assert ff(x**2 + 3*x, -2) == 1/((x**2 + 3*x + 1)*(x**2 + 3*x + 2))
|
150 |
+
|
151 |
+
assert ff(Poly(2*x**2 - 5*x, x), 2) == Poly(4*x**4 - 28*x**3 + 59*x**2 - 35*x, x)
|
152 |
+
assert isinstance(ff(Poly(2*x**2 - 5*x, x), 2), Poly)
|
153 |
+
raises(ValueError, lambda: ff(Poly(2*x**2 - 5*x, x, y), 2))
|
154 |
+
assert ff(Poly(x**2 + 3*x, x), -2) == 1/(x**4 + 12*x**3 + 49*x**2 + 78*x + 40)
|
155 |
+
raises(ValueError, lambda: ff(Poly(x**2 + 3*x, x, y), -2))
|
156 |
+
|
157 |
+
|
158 |
+
assert ff(x, m).is_integer is None
|
159 |
+
assert ff(n, k).is_integer is None
|
160 |
+
assert ff(n, m).is_integer is True
|
161 |
+
assert ff(n, k + pi).is_integer is False
|
162 |
+
assert ff(n, m + pi).is_integer is False
|
163 |
+
assert ff(pi, m).is_integer is False
|
164 |
+
|
165 |
+
assert isinstance(ff(x, x), ff)
|
166 |
+
assert ff(n, n) == factorial(n)
|
167 |
+
|
168 |
+
def check(x, k, o, n):
|
169 |
+
a, b = Dummy(), Dummy()
|
170 |
+
r = lambda x, k: o(a, b).rewrite(n).subs({a:x,b:k})
|
171 |
+
for i in range(-5,5):
|
172 |
+
for j in range(-5,5):
|
173 |
+
assert o(i, j) == r(i, j), (o, n)
|
174 |
+
check(x, k, ff, rf)
|
175 |
+
check(x, k, ff, gamma)
|
176 |
+
check(n, k, ff, factorial)
|
177 |
+
check(x, k, ff, binomial)
|
178 |
+
check(x, y, ff, factorial)
|
179 |
+
check(x, y, ff, binomial)
|
180 |
+
|
181 |
+
assert ff(x, k).rewrite(rf) == rf(x - k + 1, k)
|
182 |
+
assert ff(x, k).rewrite(gamma) == Piecewise(
|
183 |
+
(gamma(x + 1)/gamma(-k + x + 1), x >= 0),
|
184 |
+
((-1)**k*gamma(k - x)/gamma(-x), True))
|
185 |
+
assert ff(5, k).rewrite(gamma) == 120/gamma(6 - k)
|
186 |
+
assert ff(n, k).rewrite(factorial) == Piecewise(
|
187 |
+
(factorial(n)/factorial(-k + n), n >= 0),
|
188 |
+
((-1)**k*factorial(k - n - 1)/factorial(-n - 1), True))
|
189 |
+
assert ff(5, k).rewrite(factorial) == 120/factorial(5 - k)
|
190 |
+
assert ff(x, k).rewrite(binomial) == factorial(k) * binomial(x, k)
|
191 |
+
assert ff(x, y).rewrite(factorial) == ff(x, y)
|
192 |
+
assert ff(x, y).rewrite(binomial) == ff(x, y)
|
193 |
+
|
194 |
+
import random
|
195 |
+
from mpmath import ff as mpmath_ff
|
196 |
+
for i in range(100):
|
197 |
+
x = -500 + 500 * random.random()
|
198 |
+
k = -500 + 500 * random.random()
|
199 |
+
a = mpmath_ff(x, k)
|
200 |
+
b = ff(x, k)
|
201 |
+
assert (abs(a - b) < abs(a) * 10**(-15))
|
202 |
+
|
203 |
+
|
204 |
+
def test_rf_ff_eval_hiprec():
|
205 |
+
maple = Float('6.9109401292234329956525265438452')
|
206 |
+
us = ff(18, Rational(2, 3)).evalf(32)
|
207 |
+
assert abs(us - maple)/us < 1e-31
|
208 |
+
|
209 |
+
maple = Float('6.8261540131125511557924466355367')
|
210 |
+
us = rf(18, Rational(2, 3)).evalf(32)
|
211 |
+
assert abs(us - maple)/us < 1e-31
|
212 |
+
|
213 |
+
maple = Float('34.007346127440197150854651814225')
|
214 |
+
us = rf(Float('4.4', 32), Float('2.2', 32));
|
215 |
+
assert abs(us - maple)/us < 1e-31
|
216 |
+
|
217 |
+
|
218 |
+
def test_rf_lambdify_mpmath():
|
219 |
+
from sympy.utilities.lambdify import lambdify
|
220 |
+
x, y = symbols('x,y')
|
221 |
+
f = lambdify((x,y), rf(x, y), 'mpmath')
|
222 |
+
maple = Float('34.007346127440197')
|
223 |
+
us = f(4.4, 2.2)
|
224 |
+
assert abs(us - maple)/us < 1e-15
|
225 |
+
|
226 |
+
|
227 |
+
def test_factorial():
|
228 |
+
x = Symbol('x')
|
229 |
+
n = Symbol('n', integer=True)
|
230 |
+
k = Symbol('k', integer=True, nonnegative=True)
|
231 |
+
r = Symbol('r', integer=False)
|
232 |
+
s = Symbol('s', integer=False, negative=True)
|
233 |
+
t = Symbol('t', nonnegative=True)
|
234 |
+
u = Symbol('u', noninteger=True)
|
235 |
+
|
236 |
+
assert factorial(-2) is zoo
|
237 |
+
assert factorial(0) == 1
|
238 |
+
assert factorial(7) == 5040
|
239 |
+
assert factorial(19) == 121645100408832000
|
240 |
+
assert factorial(31) == 8222838654177922817725562880000000
|
241 |
+
assert factorial(n).func == factorial
|
242 |
+
assert factorial(2*n).func == factorial
|
243 |
+
|
244 |
+
assert factorial(x).is_integer is None
|
245 |
+
assert factorial(n).is_integer is None
|
246 |
+
assert factorial(k).is_integer
|
247 |
+
assert factorial(r).is_integer is None
|
248 |
+
|
249 |
+
assert factorial(n).is_positive is None
|
250 |
+
assert factorial(k).is_positive
|
251 |
+
|
252 |
+
assert factorial(x).is_real is None
|
253 |
+
assert factorial(n).is_real is None
|
254 |
+
assert factorial(k).is_real is True
|
255 |
+
assert factorial(r).is_real is None
|
256 |
+
assert factorial(s).is_real is True
|
257 |
+
assert factorial(t).is_real is True
|
258 |
+
assert factorial(u).is_real is True
|
259 |
+
|
260 |
+
assert factorial(x).is_composite is None
|
261 |
+
assert factorial(n).is_composite is None
|
262 |
+
assert factorial(k).is_composite is None
|
263 |
+
assert factorial(k + 3).is_composite is True
|
264 |
+
assert factorial(r).is_composite is None
|
265 |
+
assert factorial(s).is_composite is None
|
266 |
+
assert factorial(t).is_composite is None
|
267 |
+
assert factorial(u).is_composite is None
|
268 |
+
|
269 |
+
assert factorial(oo) is oo
|
270 |
+
|
271 |
+
|
272 |
+
def test_factorial_Mod():
|
273 |
+
pr = Symbol('pr', prime=True)
|
274 |
+
p, q = 10**9 + 9, 10**9 + 33 # prime modulo
|
275 |
+
r, s = 10**7 + 5, 33333333 # composite modulo
|
276 |
+
assert Mod(factorial(pr - 1), pr) == pr - 1
|
277 |
+
assert Mod(factorial(pr - 1), -pr) == -1
|
278 |
+
assert Mod(factorial(r - 1, evaluate=False), r) == 0
|
279 |
+
assert Mod(factorial(s - 1, evaluate=False), s) == 0
|
280 |
+
assert Mod(factorial(p - 1, evaluate=False), p) == p - 1
|
281 |
+
assert Mod(factorial(q - 1, evaluate=False), q) == q - 1
|
282 |
+
assert Mod(factorial(p - 50, evaluate=False), p) == 854928834
|
283 |
+
assert Mod(factorial(q - 1800, evaluate=False), q) == 905504050
|
284 |
+
assert Mod(factorial(153, evaluate=False), r) == Mod(factorial(153), r)
|
285 |
+
assert Mod(factorial(255, evaluate=False), s) == Mod(factorial(255), s)
|
286 |
+
assert Mod(factorial(4, evaluate=False), 3) == S.Zero
|
287 |
+
assert Mod(factorial(5, evaluate=False), 6) == S.Zero
|
288 |
+
|
289 |
+
|
290 |
+
def test_factorial_diff():
|
291 |
+
n = Symbol('n', integer=True)
|
292 |
+
|
293 |
+
assert factorial(n).diff(n) == \
|
294 |
+
gamma(1 + n)*polygamma(0, 1 + n)
|
295 |
+
assert factorial(n**2).diff(n) == \
|
296 |
+
2*n*gamma(1 + n**2)*polygamma(0, 1 + n**2)
|
297 |
+
raises(ArgumentIndexError, lambda: factorial(n**2).fdiff(2))
|
298 |
+
|
299 |
+
|
300 |
+
def test_factorial_series():
|
301 |
+
n = Symbol('n', integer=True)
|
302 |
+
|
303 |
+
assert factorial(n).series(n, 0, 3) == \
|
304 |
+
1 - n*EulerGamma + n**2*(EulerGamma**2/2 + pi**2/12) + O(n**3)
|
305 |
+
|
306 |
+
|
307 |
+
def test_factorial_rewrite():
|
308 |
+
n = Symbol('n', integer=True)
|
309 |
+
k = Symbol('k', integer=True, nonnegative=True)
|
310 |
+
|
311 |
+
assert factorial(n).rewrite(gamma) == gamma(n + 1)
|
312 |
+
_i = Dummy('i')
|
313 |
+
assert factorial(k).rewrite(Product).dummy_eq(Product(_i, (_i, 1, k)))
|
314 |
+
assert factorial(n).rewrite(Product) == factorial(n)
|
315 |
+
|
316 |
+
|
317 |
+
def test_factorial2():
|
318 |
+
n = Symbol('n', integer=True)
|
319 |
+
|
320 |
+
assert factorial2(-1) == 1
|
321 |
+
assert factorial2(0) == 1
|
322 |
+
assert factorial2(7) == 105
|
323 |
+
assert factorial2(8) == 384
|
324 |
+
|
325 |
+
# The following is exhaustive
|
326 |
+
tt = Symbol('tt', integer=True, nonnegative=True)
|
327 |
+
tte = Symbol('tte', even=True, nonnegative=True)
|
328 |
+
tpe = Symbol('tpe', even=True, positive=True)
|
329 |
+
tto = Symbol('tto', odd=True, nonnegative=True)
|
330 |
+
tf = Symbol('tf', integer=True, nonnegative=False)
|
331 |
+
tfe = Symbol('tfe', even=True, nonnegative=False)
|
332 |
+
tfo = Symbol('tfo', odd=True, nonnegative=False)
|
333 |
+
ft = Symbol('ft', integer=False, nonnegative=True)
|
334 |
+
ff = Symbol('ff', integer=False, nonnegative=False)
|
335 |
+
fn = Symbol('fn', integer=False)
|
336 |
+
nt = Symbol('nt', nonnegative=True)
|
337 |
+
nf = Symbol('nf', nonnegative=False)
|
338 |
+
nn = Symbol('nn')
|
339 |
+
z = Symbol('z', zero=True)
|
340 |
+
#Solves and Fixes Issue #10388 - This is the updated test for the same solved issue
|
341 |
+
raises(ValueError, lambda: factorial2(oo))
|
342 |
+
raises(ValueError, lambda: factorial2(Rational(5, 2)))
|
343 |
+
raises(ValueError, lambda: factorial2(-4))
|
344 |
+
assert factorial2(n).is_integer is None
|
345 |
+
assert factorial2(tt - 1).is_integer
|
346 |
+
assert factorial2(tte - 1).is_integer
|
347 |
+
assert factorial2(tpe - 3).is_integer
|
348 |
+
assert factorial2(tto - 4).is_integer
|
349 |
+
assert factorial2(tto - 2).is_integer
|
350 |
+
assert factorial2(tf).is_integer is None
|
351 |
+
assert factorial2(tfe).is_integer is None
|
352 |
+
assert factorial2(tfo).is_integer is None
|
353 |
+
assert factorial2(ft).is_integer is None
|
354 |
+
assert factorial2(ff).is_integer is None
|
355 |
+
assert factorial2(fn).is_integer is None
|
356 |
+
assert factorial2(nt).is_integer is None
|
357 |
+
assert factorial2(nf).is_integer is None
|
358 |
+
assert factorial2(nn).is_integer is None
|
359 |
+
|
360 |
+
assert factorial2(n).is_positive is None
|
361 |
+
assert factorial2(tt - 1).is_positive is True
|
362 |
+
assert factorial2(tte - 1).is_positive is True
|
363 |
+
assert factorial2(tpe - 3).is_positive is True
|
364 |
+
assert factorial2(tpe - 1).is_positive is True
|
365 |
+
assert factorial2(tto - 2).is_positive is True
|
366 |
+
assert factorial2(tto - 1).is_positive is True
|
367 |
+
assert factorial2(tf).is_positive is None
|
368 |
+
assert factorial2(tfe).is_positive is None
|
369 |
+
assert factorial2(tfo).is_positive is None
|
370 |
+
assert factorial2(ft).is_positive is None
|
371 |
+
assert factorial2(ff).is_positive is None
|
372 |
+
assert factorial2(fn).is_positive is None
|
373 |
+
assert factorial2(nt).is_positive is None
|
374 |
+
assert factorial2(nf).is_positive is None
|
375 |
+
assert factorial2(nn).is_positive is None
|
376 |
+
|
377 |
+
assert factorial2(tt).is_even is None
|
378 |
+
assert factorial2(tt).is_odd is None
|
379 |
+
assert factorial2(tte).is_even is None
|
380 |
+
assert factorial2(tte).is_odd is None
|
381 |
+
assert factorial2(tte + 2).is_even is True
|
382 |
+
assert factorial2(tpe).is_even is True
|
383 |
+
assert factorial2(tpe).is_odd is False
|
384 |
+
assert factorial2(tto).is_odd is True
|
385 |
+
assert factorial2(tf).is_even is None
|
386 |
+
assert factorial2(tf).is_odd is None
|
387 |
+
assert factorial2(tfe).is_even is None
|
388 |
+
assert factorial2(tfe).is_odd is None
|
389 |
+
assert factorial2(tfo).is_even is False
|
390 |
+
assert factorial2(tfo).is_odd is None
|
391 |
+
assert factorial2(z).is_even is False
|
392 |
+
assert factorial2(z).is_odd is True
|
393 |
+
|
394 |
+
|
395 |
+
def test_factorial2_rewrite():
|
396 |
+
n = Symbol('n', integer=True)
|
397 |
+
assert factorial2(n).rewrite(gamma) == \
|
398 |
+
2**(n/2)*Piecewise((1, Eq(Mod(n, 2), 0)), (sqrt(2)/sqrt(pi), Eq(Mod(n, 2), 1)))*gamma(n/2 + 1)
|
399 |
+
assert factorial2(2*n).rewrite(gamma) == 2**n*gamma(n + 1)
|
400 |
+
assert factorial2(2*n + 1).rewrite(gamma) == \
|
401 |
+
sqrt(2)*2**(n + S.Half)*gamma(n + Rational(3, 2))/sqrt(pi)
|
402 |
+
|
403 |
+
|
404 |
+
def test_binomial():
|
405 |
+
x = Symbol('x')
|
406 |
+
n = Symbol('n', integer=True)
|
407 |
+
nz = Symbol('nz', integer=True, nonzero=True)
|
408 |
+
k = Symbol('k', integer=True)
|
409 |
+
kp = Symbol('kp', integer=True, positive=True)
|
410 |
+
kn = Symbol('kn', integer=True, negative=True)
|
411 |
+
u = Symbol('u', negative=True)
|
412 |
+
v = Symbol('v', nonnegative=True)
|
413 |
+
p = Symbol('p', positive=True)
|
414 |
+
z = Symbol('z', zero=True)
|
415 |
+
nt = Symbol('nt', integer=False)
|
416 |
+
kt = Symbol('kt', integer=False)
|
417 |
+
a = Symbol('a', integer=True, nonnegative=True)
|
418 |
+
b = Symbol('b', integer=True, nonnegative=True)
|
419 |
+
|
420 |
+
assert binomial(0, 0) == 1
|
421 |
+
assert binomial(1, 1) == 1
|
422 |
+
assert binomial(10, 10) == 1
|
423 |
+
assert binomial(n, z) == 1
|
424 |
+
assert binomial(1, 2) == 0
|
425 |
+
assert binomial(-1, 2) == 1
|
426 |
+
assert binomial(1, -1) == 0
|
427 |
+
assert binomial(-1, 1) == -1
|
428 |
+
assert binomial(-1, -1) == 0
|
429 |
+
assert binomial(S.Half, S.Half) == 1
|
430 |
+
assert binomial(-10, 1) == -10
|
431 |
+
assert binomial(-10, 7) == -11440
|
432 |
+
assert binomial(n, -1) == 0 # holds for all integers (negative, zero, positive)
|
433 |
+
assert binomial(kp, -1) == 0
|
434 |
+
assert binomial(nz, 0) == 1
|
435 |
+
assert expand_func(binomial(n, 1)) == n
|
436 |
+
assert expand_func(binomial(n, 2)) == n*(n - 1)/2
|
437 |
+
assert expand_func(binomial(n, n - 2)) == n*(n - 1)/2
|
438 |
+
assert expand_func(binomial(n, n - 1)) == n
|
439 |
+
assert binomial(n, 3).func == binomial
|
440 |
+
assert binomial(n, 3).expand(func=True) == n**3/6 - n**2/2 + n/3
|
441 |
+
assert expand_func(binomial(n, 3)) == n*(n - 2)*(n - 1)/6
|
442 |
+
assert binomial(n, n).func == binomial # e.g. (-1, -1) == 0, (2, 2) == 1
|
443 |
+
assert binomial(n, n + 1).func == binomial # e.g. (-1, 0) == 1
|
444 |
+
assert binomial(kp, kp + 1) == 0
|
445 |
+
assert binomial(kn, kn) == 0 # issue #14529
|
446 |
+
assert binomial(n, u).func == binomial
|
447 |
+
assert binomial(kp, u).func == binomial
|
448 |
+
assert binomial(n, p).func == binomial
|
449 |
+
assert binomial(n, k).func == binomial
|
450 |
+
assert binomial(n, n + p).func == binomial
|
451 |
+
assert binomial(kp, kp + p).func == binomial
|
452 |
+
|
453 |
+
assert expand_func(binomial(n, n - 3)) == n*(n - 2)*(n - 1)/6
|
454 |
+
|
455 |
+
assert binomial(n, k).is_integer
|
456 |
+
assert binomial(nt, k).is_integer is None
|
457 |
+
assert binomial(x, nt).is_integer is False
|
458 |
+
|
459 |
+
assert binomial(gamma(25), 6) == 79232165267303928292058750056084441948572511312165380965440075720159859792344339983120618959044048198214221915637090855535036339620413440000
|
460 |
+
assert binomial(1324, 47) == 906266255662694632984994480774946083064699457235920708992926525848438478406790323869952
|
461 |
+
assert binomial(1735, 43) == 190910140420204130794758005450919715396159959034348676124678207874195064798202216379800
|
462 |
+
assert binomial(2512, 53) == 213894469313832631145798303740098720367984955243020898718979538096223399813295457822575338958939834177325304000
|
463 |
+
assert binomial(3383, 52) == 27922807788818096863529701501764372757272890613101645521813434902890007725667814813832027795881839396839287659777235
|
464 |
+
assert binomial(4321, 51) == 124595639629264868916081001263541480185227731958274383287107643816863897851139048158022599533438936036467601690983780576
|
465 |
+
|
466 |
+
assert binomial(a, b).is_nonnegative is True
|
467 |
+
assert binomial(-1, 2, evaluate=False).is_nonnegative is True
|
468 |
+
assert binomial(10, 5, evaluate=False).is_nonnegative is True
|
469 |
+
assert binomial(10, -3, evaluate=False).is_nonnegative is True
|
470 |
+
assert binomial(-10, -3, evaluate=False).is_nonnegative is True
|
471 |
+
assert binomial(-10, 2, evaluate=False).is_nonnegative is True
|
472 |
+
assert binomial(-10, 1, evaluate=False).is_nonnegative is False
|
473 |
+
assert binomial(-10, 7, evaluate=False).is_nonnegative is False
|
474 |
+
|
475 |
+
# issue #14625
|
476 |
+
for _ in (pi, -pi, nt, v, a):
|
477 |
+
assert binomial(_, _) == 1
|
478 |
+
assert binomial(_, _ - 1) == _
|
479 |
+
assert isinstance(binomial(u, u), binomial)
|
480 |
+
assert isinstance(binomial(u, u - 1), binomial)
|
481 |
+
assert isinstance(binomial(x, x), binomial)
|
482 |
+
assert isinstance(binomial(x, x - 1), binomial)
|
483 |
+
|
484 |
+
#issue #18802
|
485 |
+
assert expand_func(binomial(x + 1, x)) == x + 1
|
486 |
+
assert expand_func(binomial(x, x - 1)) == x
|
487 |
+
assert expand_func(binomial(x + 1, x - 1)) == x*(x + 1)/2
|
488 |
+
assert expand_func(binomial(x**2 + 1, x**2)) == x**2 + 1
|
489 |
+
|
490 |
+
# issue #13980 and #13981
|
491 |
+
assert binomial(-7, -5) == 0
|
492 |
+
assert binomial(-23, -12) == 0
|
493 |
+
assert binomial(Rational(13, 2), -10) == 0
|
494 |
+
assert binomial(-49, -51) == 0
|
495 |
+
|
496 |
+
assert binomial(19, Rational(-7, 2)) == S(-68719476736)/(911337863661225*pi)
|
497 |
+
assert binomial(0, Rational(3, 2)) == S(-2)/(3*pi)
|
498 |
+
assert binomial(-3, Rational(-7, 2)) is zoo
|
499 |
+
assert binomial(kn, kt) is zoo
|
500 |
+
|
501 |
+
assert binomial(nt, kt).func == binomial
|
502 |
+
assert binomial(nt, Rational(15, 6)) == 8*gamma(nt + 1)/(15*sqrt(pi)*gamma(nt - Rational(3, 2)))
|
503 |
+
assert binomial(Rational(20, 3), Rational(-10, 8)) == gamma(Rational(23, 3))/(gamma(Rational(-1, 4))*gamma(Rational(107, 12)))
|
504 |
+
assert binomial(Rational(19, 2), Rational(-7, 2)) == Rational(-1615, 8388608)
|
505 |
+
assert binomial(Rational(-13, 5), Rational(-7, 8)) == gamma(Rational(-8, 5))/(gamma(Rational(-29, 40))*gamma(Rational(1, 8)))
|
506 |
+
assert binomial(Rational(-19, 8), Rational(-13, 5)) == gamma(Rational(-11, 8))/(gamma(Rational(-8, 5))*gamma(Rational(49, 40)))
|
507 |
+
|
508 |
+
# binomial for complexes
|
509 |
+
assert binomial(I, Rational(-89, 8)) == gamma(1 + I)/(gamma(Rational(-81, 8))*gamma(Rational(97, 8) + I))
|
510 |
+
assert binomial(I, 2*I) == gamma(1 + I)/(gamma(1 - I)*gamma(1 + 2*I))
|
511 |
+
assert binomial(-7, I) is zoo
|
512 |
+
assert binomial(Rational(-7, 6), I) == gamma(Rational(-1, 6))/(gamma(Rational(-1, 6) - I)*gamma(1 + I))
|
513 |
+
assert binomial((1+2*I), (1+3*I)) == gamma(2 + 2*I)/(gamma(1 - I)*gamma(2 + 3*I))
|
514 |
+
assert binomial(I, 5) == Rational(1, 3) - I/S(12)
|
515 |
+
assert binomial((2*I + 3), 7) == -13*I/S(63)
|
516 |
+
assert isinstance(binomial(I, n), binomial)
|
517 |
+
assert expand_func(binomial(3, 2, evaluate=False)) == 3
|
518 |
+
assert expand_func(binomial(n, 0, evaluate=False)) == 1
|
519 |
+
assert expand_func(binomial(n, -2, evaluate=False)) == 0
|
520 |
+
assert expand_func(binomial(n, k)) == binomial(n, k)
|
521 |
+
|
522 |
+
|
523 |
+
def test_binomial_Mod():
|
524 |
+
p, q = 10**5 + 3, 10**9 + 33 # prime modulo
|
525 |
+
r = 10**7 + 5 # composite modulo
|
526 |
+
|
527 |
+
# A few tests to get coverage
|
528 |
+
# Lucas Theorem
|
529 |
+
assert Mod(binomial(156675, 4433, evaluate=False), p) == Mod(binomial(156675, 4433), p)
|
530 |
+
|
531 |
+
# factorial Mod
|
532 |
+
assert Mod(binomial(1234, 432, evaluate=False), q) == Mod(binomial(1234, 432), q)
|
533 |
+
|
534 |
+
# binomial factorize
|
535 |
+
assert Mod(binomial(253, 113, evaluate=False), r) == Mod(binomial(253, 113), r)
|
536 |
+
|
537 |
+
|
538 |
+
@slow
|
539 |
+
def test_binomial_Mod_slow():
|
540 |
+
p, q = 10**5 + 3, 10**9 + 33 # prime modulo
|
541 |
+
r, s = 10**7 + 5, 33333333 # composite modulo
|
542 |
+
|
543 |
+
n, k, m = symbols('n k m')
|
544 |
+
assert (binomial(n, k) % q).subs({n: s, k: p}) == Mod(binomial(s, p), q)
|
545 |
+
assert (binomial(n, k) % m).subs({n: 8, k: 5, m: 13}) == 4
|
546 |
+
assert (binomial(9, k) % 7).subs(k, 2) == 1
|
547 |
+
|
548 |
+
# Lucas Theorem
|
549 |
+
assert Mod(binomial(123456, 43253, evaluate=False), p) == Mod(binomial(123456, 43253), p)
|
550 |
+
assert Mod(binomial(-178911, 237, evaluate=False), p) == Mod(-binomial(178911 + 237 - 1, 237), p)
|
551 |
+
assert Mod(binomial(-178911, 238, evaluate=False), p) == Mod(binomial(178911 + 238 - 1, 238), p)
|
552 |
+
|
553 |
+
# factorial Mod
|
554 |
+
assert Mod(binomial(9734, 451, evaluate=False), q) == Mod(binomial(9734, 451), q)
|
555 |
+
assert Mod(binomial(-10733, 4459, evaluate=False), q) == Mod(binomial(-10733, 4459), q)
|
556 |
+
assert Mod(binomial(-15733, 4458, evaluate=False), q) == Mod(binomial(-15733, 4458), q)
|
557 |
+
assert Mod(binomial(23, -38, evaluate=False), q) is S.Zero
|
558 |
+
assert Mod(binomial(23, 38, evaluate=False), q) is S.Zero
|
559 |
+
|
560 |
+
# binomial factorize
|
561 |
+
assert Mod(binomial(753, 119, evaluate=False), r) == Mod(binomial(753, 119), r)
|
562 |
+
assert Mod(binomial(3781, 948, evaluate=False), s) == Mod(binomial(3781, 948), s)
|
563 |
+
assert Mod(binomial(25773, 1793, evaluate=False), s) == Mod(binomial(25773, 1793), s)
|
564 |
+
assert Mod(binomial(-753, 118, evaluate=False), r) == Mod(binomial(-753, 118), r)
|
565 |
+
assert Mod(binomial(-25773, 1793, evaluate=False), s) == Mod(binomial(-25773, 1793), s)
|
566 |
+
|
567 |
+
|
568 |
+
def test_binomial_diff():
|
569 |
+
n = Symbol('n', integer=True)
|
570 |
+
k = Symbol('k', integer=True)
|
571 |
+
|
572 |
+
assert binomial(n, k).diff(n) == \
|
573 |
+
(-polygamma(0, 1 + n - k) + polygamma(0, 1 + n))*binomial(n, k)
|
574 |
+
assert binomial(n**2, k**3).diff(n) == \
|
575 |
+
2*n*(-polygamma(
|
576 |
+
0, 1 + n**2 - k**3) + polygamma(0, 1 + n**2))*binomial(n**2, k**3)
|
577 |
+
|
578 |
+
assert binomial(n, k).diff(k) == \
|
579 |
+
(-polygamma(0, 1 + k) + polygamma(0, 1 + n - k))*binomial(n, k)
|
580 |
+
assert binomial(n**2, k**3).diff(k) == \
|
581 |
+
3*k**2*(-polygamma(
|
582 |
+
0, 1 + k**3) + polygamma(0, 1 + n**2 - k**3))*binomial(n**2, k**3)
|
583 |
+
raises(ArgumentIndexError, lambda: binomial(n, k).fdiff(3))
|
584 |
+
|
585 |
+
|
586 |
+
def test_binomial_rewrite():
|
587 |
+
n = Symbol('n', integer=True)
|
588 |
+
k = Symbol('k', integer=True)
|
589 |
+
x = Symbol('x')
|
590 |
+
|
591 |
+
assert binomial(n, k).rewrite(
|
592 |
+
factorial) == factorial(n)/(factorial(k)*factorial(n - k))
|
593 |
+
assert binomial(
|
594 |
+
n, k).rewrite(gamma) == gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
|
595 |
+
assert binomial(n, k).rewrite(ff) == ff(n, k) / factorial(k)
|
596 |
+
assert binomial(n, x).rewrite(ff) == binomial(n, x)
|
597 |
+
|
598 |
+
|
599 |
+
@XFAIL
|
600 |
+
def test_factorial_simplify_fail():
|
601 |
+
# simplify(factorial(x + 1).diff(x) - ((x + 1)*factorial(x)).diff(x))) == 0
|
602 |
+
from sympy.abc import x
|
603 |
+
assert simplify(x*polygamma(0, x + 1) - x*polygamma(0, x + 2) +
|
604 |
+
polygamma(0, x + 1) - polygamma(0, x + 2) + 1) == 0
|
605 |
+
|
606 |
+
|
607 |
+
def test_subfactorial():
|
608 |
+
assert all(subfactorial(i) == ans for i, ans in enumerate(
|
609 |
+
[1, 0, 1, 2, 9, 44, 265, 1854, 14833, 133496]))
|
610 |
+
assert subfactorial(oo) is oo
|
611 |
+
assert subfactorial(nan) is nan
|
612 |
+
assert subfactorial(23) == 9510425471055777937262
|
613 |
+
assert unchanged(subfactorial, 2.2)
|
614 |
+
|
615 |
+
x = Symbol('x')
|
616 |
+
assert subfactorial(x).rewrite(uppergamma) == uppergamma(x + 1, -1)/S.Exp1
|
617 |
+
|
618 |
+
tt = Symbol('tt', integer=True, nonnegative=True)
|
619 |
+
tf = Symbol('tf', integer=True, nonnegative=False)
|
620 |
+
tn = Symbol('tf', integer=True)
|
621 |
+
ft = Symbol('ft', integer=False, nonnegative=True)
|
622 |
+
ff = Symbol('ff', integer=False, nonnegative=False)
|
623 |
+
fn = Symbol('ff', integer=False)
|
624 |
+
nt = Symbol('nt', nonnegative=True)
|
625 |
+
nf = Symbol('nf', nonnegative=False)
|
626 |
+
nn = Symbol('nf')
|
627 |
+
te = Symbol('te', even=True, nonnegative=True)
|
628 |
+
to = Symbol('to', odd=True, nonnegative=True)
|
629 |
+
assert subfactorial(tt).is_integer
|
630 |
+
assert subfactorial(tf).is_integer is None
|
631 |
+
assert subfactorial(tn).is_integer is None
|
632 |
+
assert subfactorial(ft).is_integer is None
|
633 |
+
assert subfactorial(ff).is_integer is None
|
634 |
+
assert subfactorial(fn).is_integer is None
|
635 |
+
assert subfactorial(nt).is_integer is None
|
636 |
+
assert subfactorial(nf).is_integer is None
|
637 |
+
assert subfactorial(nn).is_integer is None
|
638 |
+
assert subfactorial(tt).is_nonnegative
|
639 |
+
assert subfactorial(tf).is_nonnegative is None
|
640 |
+
assert subfactorial(tn).is_nonnegative is None
|
641 |
+
assert subfactorial(ft).is_nonnegative is None
|
642 |
+
assert subfactorial(ff).is_nonnegative is None
|
643 |
+
assert subfactorial(fn).is_nonnegative is None
|
644 |
+
assert subfactorial(nt).is_nonnegative is None
|
645 |
+
assert subfactorial(nf).is_nonnegative is None
|
646 |
+
assert subfactorial(nn).is_nonnegative is None
|
647 |
+
assert subfactorial(tt).is_even is None
|
648 |
+
assert subfactorial(tt).is_odd is None
|
649 |
+
assert subfactorial(te).is_odd is True
|
650 |
+
assert subfactorial(to).is_even is True
|
venv/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/test_comb_numbers.py
ADDED
@@ -0,0 +1,852 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import string
|
2 |
+
|
3 |
+
from sympy.concrete.products import Product
|
4 |
+
from sympy.concrete.summations import Sum
|
5 |
+
from sympy.core.function import (diff, expand_func)
|
6 |
+
from sympy.core import (EulerGamma, TribonacciConstant)
|
7 |
+
from sympy.core.numbers import (Float, I, Rational, oo, pi)
|
8 |
+
from sympy.core.singleton import S
|
9 |
+
from sympy.core.symbol import (Dummy, Symbol, symbols)
|
10 |
+
from sympy.functions.combinatorial.numbers import carmichael
|
11 |
+
from sympy.functions.elementary.complexes import (im, re)
|
12 |
+
from sympy.functions.elementary.integers import floor
|
13 |
+
from sympy.polys.polytools import cancel
|
14 |
+
from sympy.series.limits import limit, Limit
|
15 |
+
from sympy.series.order import O
|
16 |
+
from sympy.functions import (
|
17 |
+
bernoulli, harmonic, bell, fibonacci, tribonacci, lucas, euler, catalan,
|
18 |
+
genocchi, andre, partition, motzkin, binomial, gamma, sqrt, cbrt, hyper, log, digamma,
|
19 |
+
trigamma, polygamma, factorial, sin, cos, cot, polylog, zeta, dirichlet_eta)
|
20 |
+
from sympy.functions.combinatorial.numbers import _nT
|
21 |
+
|
22 |
+
from sympy.core.expr import unchanged
|
23 |
+
from sympy.core.numbers import GoldenRatio, Integer
|
24 |
+
|
25 |
+
from sympy.testing.pytest import raises, nocache_fail, warns_deprecated_sympy
|
26 |
+
from sympy.abc import x
|
27 |
+
|
28 |
+
|
29 |
+
def test_carmichael():
|
30 |
+
assert carmichael.find_carmichael_numbers_in_range(0, 561) == []
|
31 |
+
assert carmichael.find_carmichael_numbers_in_range(561, 562) == [561]
|
32 |
+
assert carmichael.find_carmichael_numbers_in_range(561, 1105) == carmichael.find_carmichael_numbers_in_range(561,
|
33 |
+
562)
|
34 |
+
assert carmichael.find_first_n_carmichaels(5) == [561, 1105, 1729, 2465, 2821]
|
35 |
+
raises(ValueError, lambda: carmichael.is_carmichael(-2))
|
36 |
+
raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(-2, 2))
|
37 |
+
raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(22, 2))
|
38 |
+
with warns_deprecated_sympy():
|
39 |
+
assert carmichael.is_prime(2821) == False
|
40 |
+
|
41 |
+
|
42 |
+
def test_bernoulli():
|
43 |
+
assert bernoulli(0) == 1
|
44 |
+
assert bernoulli(1) == Rational(1, 2)
|
45 |
+
assert bernoulli(2) == Rational(1, 6)
|
46 |
+
assert bernoulli(3) == 0
|
47 |
+
assert bernoulli(4) == Rational(-1, 30)
|
48 |
+
assert bernoulli(5) == 0
|
49 |
+
assert bernoulli(6) == Rational(1, 42)
|
50 |
+
assert bernoulli(7) == 0
|
51 |
+
assert bernoulli(8) == Rational(-1, 30)
|
52 |
+
assert bernoulli(10) == Rational(5, 66)
|
53 |
+
assert bernoulli(1000001) == 0
|
54 |
+
|
55 |
+
assert bernoulli(0, x) == 1
|
56 |
+
assert bernoulli(1, x) == x - S.Half
|
57 |
+
assert bernoulli(2, x) == x**2 - x + Rational(1, 6)
|
58 |
+
assert bernoulli(3, x) == x**3 - (3*x**2)/2 + x/2
|
59 |
+
|
60 |
+
# Should be fast; computed with mpmath
|
61 |
+
b = bernoulli(1000)
|
62 |
+
assert b.p % 10**10 == 7950421099
|
63 |
+
assert b.q == 342999030
|
64 |
+
|
65 |
+
b = bernoulli(10**6, evaluate=False).evalf()
|
66 |
+
assert str(b) == '-2.23799235765713e+4767529'
|
67 |
+
|
68 |
+
# Issue #8527
|
69 |
+
l = Symbol('l', integer=True)
|
70 |
+
m = Symbol('m', integer=True, nonnegative=True)
|
71 |
+
n = Symbol('n', integer=True, positive=True)
|
72 |
+
assert isinstance(bernoulli(2 * l + 1), bernoulli)
|
73 |
+
assert isinstance(bernoulli(2 * m + 1), bernoulli)
|
74 |
+
assert bernoulli(2 * n + 1) == 0
|
75 |
+
|
76 |
+
assert bernoulli(x, 1) == bernoulli(x)
|
77 |
+
|
78 |
+
assert str(bernoulli(0.0, 2.3).evalf(n=10)) == '1.000000000'
|
79 |
+
assert str(bernoulli(1.0).evalf(n=10)) == '0.5000000000'
|
80 |
+
assert str(bernoulli(1.2).evalf(n=10)) == '0.4195995367'
|
81 |
+
assert str(bernoulli(1.2, 0.8).evalf(n=10)) == '0.2144830348'
|
82 |
+
assert str(bernoulli(1.2, -0.8).evalf(n=10)) == '-1.158865646 - 0.6745558744*I'
|
83 |
+
assert str(bernoulli(3.0, 1j).evalf(n=10)) == '1.5 - 0.5*I'
|
84 |
+
assert str(bernoulli(I).evalf(n=10)) == '0.9268485643 - 0.5821580598*I'
|
85 |
+
assert str(bernoulli(I, I).evalf(n=10)) == '0.1267792071 + 0.01947413152*I'
|
86 |
+
assert bernoulli(x).evalf() == bernoulli(x)
|
87 |
+
|
88 |
+
|
89 |
+
def test_bernoulli_rewrite():
|
90 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
91 |
+
n = Symbol('n', integer=True, nonnegative=True)
|
92 |
+
|
93 |
+
assert bernoulli(-1).rewrite(zeta) == pi**2/6
|
94 |
+
assert bernoulli(-2).rewrite(zeta) == 2*zeta(3)
|
95 |
+
assert not bernoulli(n, -3).rewrite(zeta).has(harmonic)
|
96 |
+
assert bernoulli(-4, x).rewrite(zeta) == 4*zeta(5, x)
|
97 |
+
assert isinstance(bernoulli(n, x).rewrite(zeta), Piecewise)
|
98 |
+
assert bernoulli(n+1, x).rewrite(zeta) == -(n+1) * zeta(-n, x)
|
99 |
+
|
100 |
+
|
101 |
+
def test_fibonacci():
|
102 |
+
assert [fibonacci(n) for n in range(-3, 5)] == [2, -1, 1, 0, 1, 1, 2, 3]
|
103 |
+
assert fibonacci(100) == 354224848179261915075
|
104 |
+
assert [lucas(n) for n in range(-3, 5)] == [-4, 3, -1, 2, 1, 3, 4, 7]
|
105 |
+
assert lucas(100) == 792070839848372253127
|
106 |
+
|
107 |
+
assert fibonacci(1, x) == 1
|
108 |
+
assert fibonacci(2, x) == x
|
109 |
+
assert fibonacci(3, x) == x**2 + 1
|
110 |
+
assert fibonacci(4, x) == x**3 + 2*x
|
111 |
+
|
112 |
+
# issue #8800
|
113 |
+
n = Dummy('n')
|
114 |
+
assert fibonacci(n).limit(n, S.Infinity) is S.Infinity
|
115 |
+
assert lucas(n).limit(n, S.Infinity) is S.Infinity
|
116 |
+
|
117 |
+
assert fibonacci(n).rewrite(sqrt) == \
|
118 |
+
2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5
|
119 |
+
assert fibonacci(n).rewrite(sqrt).subs(n, 10).expand() == fibonacci(10)
|
120 |
+
assert fibonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \
|
121 |
+
Float(fibonacci(10))
|
122 |
+
assert lucas(n).rewrite(sqrt) == \
|
123 |
+
(fibonacci(n-1).rewrite(sqrt) + fibonacci(n+1).rewrite(sqrt)).simplify()
|
124 |
+
assert lucas(n).rewrite(sqrt).subs(n, 10).expand() == lucas(10)
|
125 |
+
raises(ValueError, lambda: fibonacci(-3, x))
|
126 |
+
|
127 |
+
|
128 |
+
def test_tribonacci():
|
129 |
+
assert [tribonacci(n) for n in range(8)] == [0, 1, 1, 2, 4, 7, 13, 24]
|
130 |
+
assert tribonacci(100) == 98079530178586034536500564
|
131 |
+
|
132 |
+
assert tribonacci(0, x) == 0
|
133 |
+
assert tribonacci(1, x) == 1
|
134 |
+
assert tribonacci(2, x) == x**2
|
135 |
+
assert tribonacci(3, x) == x**4 + x
|
136 |
+
assert tribonacci(4, x) == x**6 + 2*x**3 + 1
|
137 |
+
assert tribonacci(5, x) == x**8 + 3*x**5 + 3*x**2
|
138 |
+
|
139 |
+
n = Dummy('n')
|
140 |
+
assert tribonacci(n).limit(n, S.Infinity) is S.Infinity
|
141 |
+
|
142 |
+
w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2
|
143 |
+
a = (1 + cbrt(19 + 3*sqrt(33)) + cbrt(19 - 3*sqrt(33))) / 3
|
144 |
+
b = (1 + w*cbrt(19 + 3*sqrt(33)) + w**2*cbrt(19 - 3*sqrt(33))) / 3
|
145 |
+
c = (1 + w**2*cbrt(19 + 3*sqrt(33)) + w*cbrt(19 - 3*sqrt(33))) / 3
|
146 |
+
assert tribonacci(n).rewrite(sqrt) == \
|
147 |
+
(a**(n + 1)/((a - b)*(a - c))
|
148 |
+
+ b**(n + 1)/((b - a)*(b - c))
|
149 |
+
+ c**(n + 1)/((c - a)*(c - b)))
|
150 |
+
assert tribonacci(n).rewrite(sqrt).subs(n, 4).simplify() == tribonacci(4)
|
151 |
+
assert tribonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \
|
152 |
+
Float(tribonacci(10))
|
153 |
+
assert tribonacci(n).rewrite(TribonacciConstant) == floor(
|
154 |
+
3*TribonacciConstant**n*(102*sqrt(33) + 586)**Rational(1, 3)/
|
155 |
+
(-2*(102*sqrt(33) + 586)**Rational(1, 3) + 4 + (102*sqrt(33)
|
156 |
+
+ 586)**Rational(2, 3)) + S.Half)
|
157 |
+
raises(ValueError, lambda: tribonacci(-1, x))
|
158 |
+
|
159 |
+
|
160 |
+
@nocache_fail
|
161 |
+
def test_bell():
|
162 |
+
assert [bell(n) for n in range(8)] == [1, 1, 2, 5, 15, 52, 203, 877]
|
163 |
+
|
164 |
+
assert bell(0, x) == 1
|
165 |
+
assert bell(1, x) == x
|
166 |
+
assert bell(2, x) == x**2 + x
|
167 |
+
assert bell(5, x) == x**5 + 10*x**4 + 25*x**3 + 15*x**2 + x
|
168 |
+
assert bell(oo) is S.Infinity
|
169 |
+
raises(ValueError, lambda: bell(oo, x))
|
170 |
+
|
171 |
+
raises(ValueError, lambda: bell(-1))
|
172 |
+
raises(ValueError, lambda: bell(S.Half))
|
173 |
+
|
174 |
+
X = symbols('x:6')
|
175 |
+
# X = (x0, x1, .. x5)
|
176 |
+
# at the same time: X[1] = x1, X[2] = x2 for standard readablity.
|
177 |
+
# but we must supply zero-based indexed object X[1:] = (x1, .. x5)
|
178 |
+
|
179 |
+
assert bell(6, 2, X[1:]) == 6*X[5]*X[1] + 15*X[4]*X[2] + 10*X[3]**2
|
180 |
+
assert bell(
|
181 |
+
6, 3, X[1:]) == 15*X[4]*X[1]**2 + 60*X[3]*X[2]*X[1] + 15*X[2]**3
|
182 |
+
|
183 |
+
X = (1, 10, 100, 1000, 10000)
|
184 |
+
assert bell(6, 2, X) == (6 + 15 + 10)*10000
|
185 |
+
|
186 |
+
X = (1, 2, 3, 3, 5)
|
187 |
+
assert bell(6, 2, X) == 6*5 + 15*3*2 + 10*3**2
|
188 |
+
|
189 |
+
X = (1, 2, 3, 5)
|
190 |
+
assert bell(6, 3, X) == 15*5 + 60*3*2 + 15*2**3
|
191 |
+
|
192 |
+
# Dobinski's formula
|
193 |
+
n = Symbol('n', integer=True, nonnegative=True)
|
194 |
+
# For large numbers, this is too slow
|
195 |
+
# For nonintegers, there are significant precision errors
|
196 |
+
for i in [0, 2, 3, 7, 13, 42, 55]:
|
197 |
+
# Running without the cache this is either very slow or goes into an
|
198 |
+
# infinite loop.
|
199 |
+
assert bell(i).evalf() == bell(n).rewrite(Sum).evalf(subs={n: i})
|
200 |
+
|
201 |
+
m = Symbol("m")
|
202 |
+
assert bell(m).rewrite(Sum) == bell(m)
|
203 |
+
assert bell(n, m).rewrite(Sum) == bell(n, m)
|
204 |
+
# issue 9184
|
205 |
+
n = Dummy('n')
|
206 |
+
assert bell(n).limit(n, S.Infinity) is S.Infinity
|
207 |
+
|
208 |
+
|
209 |
+
def test_harmonic():
|
210 |
+
n = Symbol("n")
|
211 |
+
m = Symbol("m")
|
212 |
+
|
213 |
+
assert harmonic(n, 0) == n
|
214 |
+
assert harmonic(n).evalf() == harmonic(n)
|
215 |
+
assert harmonic(n, 1) == harmonic(n)
|
216 |
+
assert harmonic(1, n) == 1
|
217 |
+
|
218 |
+
assert harmonic(0, 1) == 0
|
219 |
+
assert harmonic(1, 1) == 1
|
220 |
+
assert harmonic(2, 1) == Rational(3, 2)
|
221 |
+
assert harmonic(3, 1) == Rational(11, 6)
|
222 |
+
assert harmonic(4, 1) == Rational(25, 12)
|
223 |
+
assert harmonic(0, 2) == 0
|
224 |
+
assert harmonic(1, 2) == 1
|
225 |
+
assert harmonic(2, 2) == Rational(5, 4)
|
226 |
+
assert harmonic(3, 2) == Rational(49, 36)
|
227 |
+
assert harmonic(4, 2) == Rational(205, 144)
|
228 |
+
assert harmonic(0, 3) == 0
|
229 |
+
assert harmonic(1, 3) == 1
|
230 |
+
assert harmonic(2, 3) == Rational(9, 8)
|
231 |
+
assert harmonic(3, 3) == Rational(251, 216)
|
232 |
+
assert harmonic(4, 3) == Rational(2035, 1728)
|
233 |
+
|
234 |
+
assert harmonic(oo, -1) is S.NaN
|
235 |
+
assert harmonic(oo, 0) is oo
|
236 |
+
assert harmonic(oo, S.Half) is oo
|
237 |
+
assert harmonic(oo, 1) is oo
|
238 |
+
assert harmonic(oo, 2) == (pi**2)/6
|
239 |
+
assert harmonic(oo, 3) == zeta(3)
|
240 |
+
assert harmonic(oo, Dummy(negative=True)) is S.NaN
|
241 |
+
ip = Dummy(integer=True, positive=True)
|
242 |
+
if (1/ip <= 1) is True: #---------------------------------+
|
243 |
+
assert None, 'delete this if-block and the next line' #|
|
244 |
+
ip = Dummy(even=True, positive=True) #--------------------+
|
245 |
+
assert harmonic(oo, 1/ip) is oo
|
246 |
+
assert harmonic(oo, 1 + ip) is zeta(1 + ip)
|
247 |
+
|
248 |
+
assert harmonic(0, m) == 0
|
249 |
+
assert harmonic(-1, -1) == 0
|
250 |
+
assert harmonic(-1, 0) == -1
|
251 |
+
assert harmonic(-1, 1) is S.ComplexInfinity
|
252 |
+
assert harmonic(-1, 2) is S.NaN
|
253 |
+
assert harmonic(-3, -2) == -5
|
254 |
+
assert harmonic(-3, -3) == 9
|
255 |
+
|
256 |
+
|
257 |
+
def test_harmonic_rational():
|
258 |
+
ne = S(6)
|
259 |
+
no = S(5)
|
260 |
+
pe = S(8)
|
261 |
+
po = S(9)
|
262 |
+
qe = S(10)
|
263 |
+
qo = S(13)
|
264 |
+
|
265 |
+
Heee = harmonic(ne + pe/qe)
|
266 |
+
Aeee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
|
267 |
+
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
|
268 |
+
+ pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(13944145, 4720968))
|
269 |
+
|
270 |
+
Heeo = harmonic(ne + pe/qo)
|
271 |
+
Aeeo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(4, 13)) + 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(32, 13))
|
272 |
+
+ 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13))
|
273 |
+
- 2*log(sin(pi*Rational(4, 13)))*cos(pi/13) + pi*cot(pi*Rational(5, 13))/2 - 2*log(sin(pi/13))*cos(pi*Rational(3, 13))
|
274 |
+
+ Rational(2422020029, 702257080))
|
275 |
+
|
276 |
+
Heoe = harmonic(ne + po/qe)
|
277 |
+
Aeoe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4)
|
278 |
+
+ 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
|
279 |
+
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
|
280 |
+
+ 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4)
|
281 |
+
+ Rational(11818877030, 4286604231) + pi*sqrt(2*sqrt(5) + 5)/2)
|
282 |
+
|
283 |
+
Heoo = harmonic(ne + po/qo)
|
284 |
+
Aeoo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(54, 13)) + 2*log(sin(pi*Rational(4, 13)))*cos(pi*Rational(6, 13))
|
285 |
+
+ 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13)
|
286 |
+
- 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2
|
287 |
+
- 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(3, 13)) + Rational(11669332571, 3628714320))
|
288 |
+
|
289 |
+
Hoee = harmonic(no + pe/qe)
|
290 |
+
Aoee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
|
291 |
+
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
|
292 |
+
+ pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(779405, 277704))
|
293 |
+
|
294 |
+
Hoeo = harmonic(no + pe/qo)
|
295 |
+
Aoeo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(4, 13)) + 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(32, 13))
|
296 |
+
+ 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13))
|
297 |
+
- 2*log(sin(pi*Rational(4, 13)))*cos(pi/13) + pi*cot(pi*Rational(5, 13))/2
|
298 |
+
- 2*log(sin(pi/13))*cos(pi*Rational(3, 13)) + Rational(53857323, 16331560))
|
299 |
+
|
300 |
+
Hooe = harmonic(no + po/qe)
|
301 |
+
Aooe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4)
|
302 |
+
+ 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
|
303 |
+
+ 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
|
304 |
+
+ 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4)
|
305 |
+
+ Rational(486853480, 186374097) + pi*sqrt(2*sqrt(5) + 5)/2)
|
306 |
+
|
307 |
+
Hooo = harmonic(no + po/qo)
|
308 |
+
Aooo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(54, 13)) + 2*log(sin(pi*Rational(4, 13)))*cos(pi*Rational(6, 13))
|
309 |
+
+ 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13)
|
310 |
+
- 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2
|
311 |
+
- 2*log(sin(pi*Rational(2, 13)))*cos(3*pi/13) + Rational(383693479, 125128080))
|
312 |
+
|
313 |
+
H = [Heee, Heeo, Heoe, Heoo, Hoee, Hoeo, Hooe, Hooo]
|
314 |
+
A = [Aeee, Aeeo, Aeoe, Aeoo, Aoee, Aoeo, Aooe, Aooo]
|
315 |
+
for h, a in zip(H, A):
|
316 |
+
e = expand_func(h).doit()
|
317 |
+
assert cancel(e/a) == 1
|
318 |
+
assert abs(h.n() - a.n()) < 1e-12
|
319 |
+
|
320 |
+
|
321 |
+
def test_harmonic_evalf():
|
322 |
+
assert str(harmonic(1.5).evalf(n=10)) == '1.280372306'
|
323 |
+
assert str(harmonic(1.5, 2).evalf(n=10)) == '1.154576311' # issue 7443
|
324 |
+
assert str(harmonic(4.0, -3).evalf(n=10)) == '100.0000000'
|
325 |
+
assert str(harmonic(7.0, 1.0).evalf(n=10)) == '2.592857143'
|
326 |
+
assert str(harmonic(1, pi).evalf(n=10)) == '1.000000000'
|
327 |
+
assert str(harmonic(2, pi).evalf(n=10)) == '1.113314732'
|
328 |
+
assert str(harmonic(1000.0, pi).evalf(n=10)) == '1.176241563'
|
329 |
+
assert str(harmonic(I).evalf(n=10)) == '0.6718659855 + 1.076674047*I'
|
330 |
+
assert str(harmonic(I, I).evalf(n=10)) == '-0.3970915266 + 1.9629689*I'
|
331 |
+
|
332 |
+
assert harmonic(-1.0, 1).evalf() is S.NaN
|
333 |
+
assert harmonic(-2.0, 2.0).evalf() is S.NaN
|
334 |
+
|
335 |
+
def test_harmonic_rewrite():
|
336 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
337 |
+
n = Symbol("n")
|
338 |
+
m = Symbol("m", integer=True, positive=True)
|
339 |
+
x1 = Symbol("x1", positive=True)
|
340 |
+
x2 = Symbol("x2", negative=True)
|
341 |
+
|
342 |
+
assert harmonic(n).rewrite(digamma) == polygamma(0, n + 1) + EulerGamma
|
343 |
+
assert harmonic(n).rewrite(trigamma) == polygamma(0, n + 1) + EulerGamma
|
344 |
+
assert harmonic(n).rewrite(polygamma) == polygamma(0, n + 1) + EulerGamma
|
345 |
+
|
346 |
+
assert harmonic(n,3).rewrite(polygamma) == polygamma(2, n + 1)/2 - polygamma(2, 1)/2
|
347 |
+
assert isinstance(harmonic(n,m).rewrite(polygamma), Piecewise)
|
348 |
+
|
349 |
+
assert expand_func(harmonic(n+4)) == harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)
|
350 |
+
assert expand_func(harmonic(n-4)) == harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n
|
351 |
+
|
352 |
+
assert harmonic(n, m).rewrite("tractable") == harmonic(n, m).rewrite(polygamma)
|
353 |
+
assert harmonic(n, x1).rewrite("tractable") == harmonic(n, x1)
|
354 |
+
assert harmonic(n, x1 + 1).rewrite("tractable") == zeta(x1 + 1) - zeta(x1 + 1, n + 1)
|
355 |
+
assert harmonic(n, x2).rewrite("tractable") == zeta(x2) - zeta(x2, n + 1)
|
356 |
+
|
357 |
+
_k = Dummy("k")
|
358 |
+
assert harmonic(n).rewrite(Sum).dummy_eq(Sum(1/_k, (_k, 1, n)))
|
359 |
+
assert harmonic(n, m).rewrite(Sum).dummy_eq(Sum(_k**(-m), (_k, 1, n)))
|
360 |
+
|
361 |
+
|
362 |
+
def test_harmonic_calculus():
|
363 |
+
y = Symbol("y", positive=True)
|
364 |
+
z = Symbol("z", negative=True)
|
365 |
+
assert harmonic(x, 1).limit(x, 0) == 0
|
366 |
+
assert harmonic(x, y).limit(x, 0) == 0
|
367 |
+
assert harmonic(x, 1).series(x, y, 2) == \
|
368 |
+
harmonic(y) + (x - y)*zeta(2, y + 1) + O((x - y)**2, (x, y))
|
369 |
+
assert limit(harmonic(x, y), x, oo) == harmonic(oo, y)
|
370 |
+
assert limit(harmonic(x, y + 1), x, oo) == zeta(y + 1)
|
371 |
+
assert limit(harmonic(x, y - 1), x, oo) == harmonic(oo, y - 1)
|
372 |
+
assert limit(harmonic(x, z), x, oo) == Limit(harmonic(x, z), x, oo, dir='-')
|
373 |
+
assert limit(harmonic(x, z + 1), x, oo) == oo
|
374 |
+
assert limit(harmonic(x, z + 2), x, oo) == harmonic(oo, z + 2)
|
375 |
+
assert limit(harmonic(x, z - 1), x, oo) == Limit(harmonic(x, z - 1), x, oo, dir='-')
|
376 |
+
|
377 |
+
|
378 |
+
def test_euler():
|
379 |
+
assert euler(0) == 1
|
380 |
+
assert euler(1) == 0
|
381 |
+
assert euler(2) == -1
|
382 |
+
assert euler(3) == 0
|
383 |
+
assert euler(4) == 5
|
384 |
+
assert euler(6) == -61
|
385 |
+
assert euler(8) == 1385
|
386 |
+
|
387 |
+
assert euler(20, evaluate=False) != 370371188237525
|
388 |
+
|
389 |
+
n = Symbol('n', integer=True)
|
390 |
+
assert euler(n) != -1
|
391 |
+
assert euler(n).subs(n, 2) == -1
|
392 |
+
|
393 |
+
assert euler(-1) == S.Pi / 2
|
394 |
+
assert euler(-1, 1) == 2*log(2)
|
395 |
+
assert euler(-2).evalf() == (2*S.Catalan).evalf()
|
396 |
+
assert euler(-3).evalf() == (S.Pi**3 / 16).evalf()
|
397 |
+
assert str(euler(2.3).evalf(n=10)) == '-1.052850274'
|
398 |
+
assert str(euler(1.2, 3.4).evalf(n=10)) == '3.575613489'
|
399 |
+
assert str(euler(I).evalf(n=10)) == '1.248446443 - 0.7675445124*I'
|
400 |
+
assert str(euler(I, I).evalf(n=10)) == '0.04812930469 + 0.01052411008*I'
|
401 |
+
|
402 |
+
assert euler(20).evalf() == 370371188237525.0
|
403 |
+
assert euler(20, evaluate=False).evalf() == 370371188237525.0
|
404 |
+
|
405 |
+
assert euler(n).rewrite(Sum) == euler(n)
|
406 |
+
n = Symbol('n', integer=True, nonnegative=True)
|
407 |
+
assert euler(2*n + 1).rewrite(Sum) == 0
|
408 |
+
_j = Dummy('j')
|
409 |
+
_k = Dummy('k')
|
410 |
+
assert euler(2*n).rewrite(Sum).dummy_eq(
|
411 |
+
I*Sum((-1)**_j*2**(-_k)*I**(-_k)*(-2*_j + _k)**(2*n + 1)*
|
412 |
+
binomial(_k, _j)/_k, (_j, 0, _k), (_k, 1, 2*n + 1)))
|
413 |
+
|
414 |
+
|
415 |
+
def test_euler_odd():
|
416 |
+
n = Symbol('n', odd=True, positive=True)
|
417 |
+
assert euler(n) == 0
|
418 |
+
n = Symbol('n', odd=True)
|
419 |
+
assert euler(n) != 0
|
420 |
+
|
421 |
+
|
422 |
+
def test_euler_polynomials():
|
423 |
+
assert euler(0, x) == 1
|
424 |
+
assert euler(1, x) == x - S.Half
|
425 |
+
assert euler(2, x) == x**2 - x
|
426 |
+
assert euler(3, x) == x**3 - (3*x**2)/2 + Rational(1, 4)
|
427 |
+
m = Symbol('m')
|
428 |
+
assert isinstance(euler(m, x), euler)
|
429 |
+
from sympy.core.numbers import Float
|
430 |
+
A = Float('-0.46237208575048694923364757452876131e8') # from Maple
|
431 |
+
B = euler(19, S.Pi).evalf(32)
|
432 |
+
assert abs((A - B)/A) < 1e-31
|
433 |
+
|
434 |
+
|
435 |
+
def test_euler_polynomial_rewrite():
|
436 |
+
m = Symbol('m')
|
437 |
+
A = euler(m, x).rewrite('Sum');
|
438 |
+
assert A.subs({m:3, x:5}).doit() == euler(3, 5)
|
439 |
+
|
440 |
+
|
441 |
+
def test_catalan():
|
442 |
+
n = Symbol('n', integer=True)
|
443 |
+
m = Symbol('m', integer=True, positive=True)
|
444 |
+
k = Symbol('k', integer=True, nonnegative=True)
|
445 |
+
p = Symbol('p', nonnegative=True)
|
446 |
+
|
447 |
+
catalans = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786]
|
448 |
+
for i, c in enumerate(catalans):
|
449 |
+
assert catalan(i) == c
|
450 |
+
assert catalan(n).rewrite(factorial).subs(n, i) == c
|
451 |
+
assert catalan(n).rewrite(Product).subs(n, i).doit() == c
|
452 |
+
|
453 |
+
assert unchanged(catalan, x)
|
454 |
+
assert catalan(2*x).rewrite(binomial) == binomial(4*x, 2*x)/(2*x + 1)
|
455 |
+
assert catalan(S.Half).rewrite(gamma) == 8/(3*pi)
|
456 |
+
assert catalan(S.Half).rewrite(factorial).rewrite(gamma) ==\
|
457 |
+
8 / (3 * pi)
|
458 |
+
assert catalan(3*x).rewrite(gamma) == 4**(
|
459 |
+
3*x)*gamma(3*x + S.Half)/(sqrt(pi)*gamma(3*x + 2))
|
460 |
+
assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2,), 1)
|
461 |
+
|
462 |
+
assert catalan(n).rewrite(factorial) == factorial(2*n) / (factorial(n + 1)
|
463 |
+
* factorial(n))
|
464 |
+
assert isinstance(catalan(n).rewrite(Product), catalan)
|
465 |
+
assert isinstance(catalan(m).rewrite(Product), Product)
|
466 |
+
|
467 |
+
assert diff(catalan(x), x) == (polygamma(
|
468 |
+
0, x + S.Half) - polygamma(0, x + 2) + log(4))*catalan(x)
|
469 |
+
|
470 |
+
assert catalan(x).evalf() == catalan(x)
|
471 |
+
c = catalan(S.Half).evalf()
|
472 |
+
assert str(c) == '0.848826363156775'
|
473 |
+
c = catalan(I).evalf(3)
|
474 |
+
assert str((re(c), im(c))) == '(0.398, -0.0209)'
|
475 |
+
|
476 |
+
# Assumptions
|
477 |
+
assert catalan(p).is_positive is True
|
478 |
+
assert catalan(k).is_integer is True
|
479 |
+
assert catalan(m+3).is_composite is True
|
480 |
+
|
481 |
+
|
482 |
+
def test_genocchi():
|
483 |
+
genocchis = [0, -1, -1, 0, 1, 0, -3, 0, 17]
|
484 |
+
for n, g in enumerate(genocchis):
|
485 |
+
assert genocchi(n) == g
|
486 |
+
|
487 |
+
m = Symbol('m', integer=True)
|
488 |
+
n = Symbol('n', integer=True, positive=True)
|
489 |
+
assert unchanged(genocchi, m)
|
490 |
+
assert genocchi(2*n + 1) == 0
|
491 |
+
gn = 2 * (1 - 2**n) * bernoulli(n)
|
492 |
+
assert genocchi(n).rewrite(bernoulli).factor() == gn.factor()
|
493 |
+
gnx = 2 * (bernoulli(n, x) - 2**n * bernoulli(n, (x+1) / 2))
|
494 |
+
assert genocchi(n, x).rewrite(bernoulli).factor() == gnx.factor()
|
495 |
+
assert genocchi(2 * n).is_odd
|
496 |
+
assert genocchi(2 * n).is_even is False
|
497 |
+
assert genocchi(2 * n + 1).is_even
|
498 |
+
assert genocchi(n).is_integer
|
499 |
+
assert genocchi(4 * n).is_positive
|
500 |
+
# these are the only 2 prime Genocchi numbers
|
501 |
+
assert genocchi(6, evaluate=False).is_prime == S(-3).is_prime
|
502 |
+
assert genocchi(8, evaluate=False).is_prime
|
503 |
+
assert genocchi(4 * n + 2).is_negative
|
504 |
+
assert genocchi(4 * n + 1).is_negative is False
|
505 |
+
assert genocchi(4 * n - 2).is_negative
|
506 |
+
|
507 |
+
g0 = genocchi(0, evaluate=False)
|
508 |
+
assert g0.is_positive is False
|
509 |
+
assert g0.is_negative is False
|
510 |
+
assert g0.is_even is True
|
511 |
+
assert g0.is_odd is False
|
512 |
+
|
513 |
+
assert genocchi(0, x) == 0
|
514 |
+
assert genocchi(1, x) == -1
|
515 |
+
assert genocchi(2, x) == 1 - 2*x
|
516 |
+
assert genocchi(3, x) == 3*x - 3*x**2
|
517 |
+
assert genocchi(4, x) == -1 + 6*x**2 - 4*x**3
|
518 |
+
y = Symbol("y")
|
519 |
+
assert genocchi(5, (x+y)**100) == -5*(x+y)**400 + 10*(x+y)**300 - 5*(x+y)**100
|
520 |
+
|
521 |
+
assert str(genocchi(5.0, 4.0).evalf(n=10)) == '-660.0000000'
|
522 |
+
assert str(genocchi(Rational(5, 4)).evalf(n=10)) == '-1.104286457'
|
523 |
+
assert str(genocchi(-2).evalf(n=10)) == '3.606170709'
|
524 |
+
assert str(genocchi(1.3, 3.7).evalf(n=10)) == '-1.847375373'
|
525 |
+
assert str(genocchi(I, 1.0).evalf(n=10)) == '-0.3161917278 - 1.45311955*I'
|
526 |
+
|
527 |
+
n = Symbol('n')
|
528 |
+
assert genocchi(n, x).rewrite(dirichlet_eta) == -2*n * dirichlet_eta(1-n, x)
|
529 |
+
|
530 |
+
|
531 |
+
def test_andre():
|
532 |
+
nums = [1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]
|
533 |
+
for n, a in enumerate(nums):
|
534 |
+
assert andre(n) == a
|
535 |
+
assert andre(S.Infinity) == S.Infinity
|
536 |
+
assert andre(-1) == -log(2)
|
537 |
+
assert andre(-2) == -2*S.Catalan
|
538 |
+
assert andre(-3) == 3*zeta(3)/16
|
539 |
+
assert andre(-5) == -15*zeta(5)/256
|
540 |
+
# In fact andre(-2*n) is related to the Dirichlet *beta* function
|
541 |
+
# at 2*n, but SymPy doesn't implement that (or general L-functions)
|
542 |
+
assert unchanged(andre, -4)
|
543 |
+
|
544 |
+
n = Symbol('n', integer=True, nonnegative=True)
|
545 |
+
assert unchanged(andre, n)
|
546 |
+
assert andre(n).is_integer is True
|
547 |
+
assert andre(n).is_positive is True
|
548 |
+
|
549 |
+
assert str(andre(10, evaluate=False).evalf(n=10)) == '50521.00000'
|
550 |
+
assert str(andre(-1, evaluate=False).evalf(n=10)) == '-0.6931471806'
|
551 |
+
assert str(andre(-2, evaluate=False).evalf(n=10)) == '-1.831931188'
|
552 |
+
assert str(andre(-4, evaluate=False).evalf(n=10)) == '1.977889103'
|
553 |
+
assert str(andre(I, evaluate=False).evalf(n=10)) == '2.378417833 + 0.6343322845*I'
|
554 |
+
|
555 |
+
assert andre(x).rewrite(polylog) == \
|
556 |
+
(-I)**(x+1) * polylog(-x, I) + I**(x+1) * polylog(-x, -I)
|
557 |
+
assert andre(x).rewrite(zeta) == \
|
558 |
+
2 * gamma(x+1) / (2*pi)**(x+1) * \
|
559 |
+
(zeta(x+1, Rational(1,4)) - cos(pi*x) * zeta(x+1, Rational(3,4)))
|
560 |
+
|
561 |
+
|
562 |
+
@nocache_fail
|
563 |
+
def test_partition():
|
564 |
+
partition_nums = [1, 1, 2, 3, 5, 7, 11, 15, 22]
|
565 |
+
for n, p in enumerate(partition_nums):
|
566 |
+
assert partition(n) == p
|
567 |
+
|
568 |
+
x = Symbol('x')
|
569 |
+
y = Symbol('y', real=True)
|
570 |
+
m = Symbol('m', integer=True)
|
571 |
+
n = Symbol('n', integer=True, negative=True)
|
572 |
+
p = Symbol('p', integer=True, nonnegative=True)
|
573 |
+
assert partition(m).is_integer
|
574 |
+
assert not partition(m).is_negative
|
575 |
+
assert partition(m).is_nonnegative
|
576 |
+
assert partition(n).is_zero
|
577 |
+
assert partition(p).is_positive
|
578 |
+
assert partition(x).subs(x, 7) == 15
|
579 |
+
assert partition(y).subs(y, 8) == 22
|
580 |
+
raises(ValueError, lambda: partition(Rational(5, 4)))
|
581 |
+
|
582 |
+
|
583 |
+
def test__nT():
|
584 |
+
assert [_nT(i, j) for i in range(5) for j in range(i + 2)] == [
|
585 |
+
1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 2, 1, 1, 0]
|
586 |
+
check = [_nT(10, i) for i in range(11)]
|
587 |
+
assert check == [0, 1, 5, 8, 9, 7, 5, 3, 2, 1, 1]
|
588 |
+
assert all(type(i) is int for i in check)
|
589 |
+
assert _nT(10, 5) == 7
|
590 |
+
assert _nT(100, 98) == 2
|
591 |
+
assert _nT(100, 100) == 1
|
592 |
+
assert _nT(10, 3) == 8
|
593 |
+
|
594 |
+
|
595 |
+
def test_nC_nP_nT():
|
596 |
+
from sympy.utilities.iterables import (
|
597 |
+
multiset_permutations, multiset_combinations, multiset_partitions,
|
598 |
+
partitions, subsets, permutations)
|
599 |
+
from sympy.functions.combinatorial.numbers import (
|
600 |
+
nP, nC, nT, stirling, _stirling1, _stirling2, _multiset_histogram, _AOP_product)
|
601 |
+
|
602 |
+
from sympy.combinatorics.permutations import Permutation
|
603 |
+
from sympy.core.random import choice
|
604 |
+
|
605 |
+
c = string.ascii_lowercase
|
606 |
+
for i in range(100):
|
607 |
+
s = ''.join(choice(c) for i in range(7))
|
608 |
+
u = len(s) == len(set(s))
|
609 |
+
try:
|
610 |
+
tot = 0
|
611 |
+
for i in range(8):
|
612 |
+
check = nP(s, i)
|
613 |
+
tot += check
|
614 |
+
assert len(list(multiset_permutations(s, i))) == check
|
615 |
+
if u:
|
616 |
+
assert nP(len(s), i) == check
|
617 |
+
assert nP(s) == tot
|
618 |
+
except AssertionError:
|
619 |
+
print(s, i, 'failed perm test')
|
620 |
+
raise ValueError()
|
621 |
+
|
622 |
+
for i in range(100):
|
623 |
+
s = ''.join(choice(c) for i in range(7))
|
624 |
+
u = len(s) == len(set(s))
|
625 |
+
try:
|
626 |
+
tot = 0
|
627 |
+
for i in range(8):
|
628 |
+
check = nC(s, i)
|
629 |
+
tot += check
|
630 |
+
assert len(list(multiset_combinations(s, i))) == check
|
631 |
+
if u:
|
632 |
+
assert nC(len(s), i) == check
|
633 |
+
assert nC(s) == tot
|
634 |
+
if u:
|
635 |
+
assert nC(len(s)) == tot
|
636 |
+
except AssertionError:
|
637 |
+
print(s, i, 'failed combo test')
|
638 |
+
raise ValueError()
|
639 |
+
|
640 |
+
for i in range(1, 10):
|
641 |
+
tot = 0
|
642 |
+
for j in range(1, i + 2):
|
643 |
+
check = nT(i, j)
|
644 |
+
assert check.is_Integer
|
645 |
+
tot += check
|
646 |
+
assert sum(1 for p in partitions(i, j, size=True) if p[0] == j) == check
|
647 |
+
assert nT(i) == tot
|
648 |
+
|
649 |
+
for i in range(1, 10):
|
650 |
+
tot = 0
|
651 |
+
for j in range(1, i + 2):
|
652 |
+
check = nT(range(i), j)
|
653 |
+
tot += check
|
654 |
+
assert len(list(multiset_partitions(list(range(i)), j))) == check
|
655 |
+
assert nT(range(i)) == tot
|
656 |
+
|
657 |
+
for i in range(100):
|
658 |
+
s = ''.join(choice(c) for i in range(7))
|
659 |
+
u = len(s) == len(set(s))
|
660 |
+
try:
|
661 |
+
tot = 0
|
662 |
+
for i in range(1, 8):
|
663 |
+
check = nT(s, i)
|
664 |
+
tot += check
|
665 |
+
assert len(list(multiset_partitions(s, i))) == check
|
666 |
+
if u:
|
667 |
+
assert nT(range(len(s)), i) == check
|
668 |
+
if u:
|
669 |
+
assert nT(range(len(s))) == tot
|
670 |
+
assert nT(s) == tot
|
671 |
+
except AssertionError:
|
672 |
+
print(s, i, 'failed partition test')
|
673 |
+
raise ValueError()
|
674 |
+
|
675 |
+
# tests for Stirling numbers of the first kind that are not tested in the
|
676 |
+
# above
|
677 |
+
assert [stirling(9, i, kind=1) for i in range(11)] == [
|
678 |
+
0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1, 0]
|
679 |
+
perms = list(permutations(range(4)))
|
680 |
+
assert [sum(1 for p in perms if Permutation(p).cycles == i)
|
681 |
+
for i in range(5)] == [0, 6, 11, 6, 1] == [
|
682 |
+
stirling(4, i, kind=1) for i in range(5)]
|
683 |
+
# http://oeis.org/A008275
|
684 |
+
assert [stirling(n, k, signed=1)
|
685 |
+
for n in range(10) for k in range(1, n + 1)] == [
|
686 |
+
1, -1,
|
687 |
+
1, 2, -3,
|
688 |
+
1, -6, 11, -6,
|
689 |
+
1, 24, -50, 35, -10,
|
690 |
+
1, -120, 274, -225, 85, -15,
|
691 |
+
1, 720, -1764, 1624, -735, 175, -21,
|
692 |
+
1, -5040, 13068, -13132, 6769, -1960, 322, -28,
|
693 |
+
1, 40320, -109584, 118124, -67284, 22449, -4536, 546, -36, 1]
|
694 |
+
# https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
|
695 |
+
assert [stirling(n, k, kind=1)
|
696 |
+
for n in range(10) for k in range(n+1)] == [
|
697 |
+
1,
|
698 |
+
0, 1,
|
699 |
+
0, 1, 1,
|
700 |
+
0, 2, 3, 1,
|
701 |
+
0, 6, 11, 6, 1,
|
702 |
+
0, 24, 50, 35, 10, 1,
|
703 |
+
0, 120, 274, 225, 85, 15, 1,
|
704 |
+
0, 720, 1764, 1624, 735, 175, 21, 1,
|
705 |
+
0, 5040, 13068, 13132, 6769, 1960, 322, 28, 1,
|
706 |
+
0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1]
|
707 |
+
# https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
|
708 |
+
assert [stirling(n, k, kind=2)
|
709 |
+
for n in range(10) for k in range(n+1)] == [
|
710 |
+
1,
|
711 |
+
0, 1,
|
712 |
+
0, 1, 1,
|
713 |
+
0, 1, 3, 1,
|
714 |
+
0, 1, 7, 6, 1,
|
715 |
+
0, 1, 15, 25, 10, 1,
|
716 |
+
0, 1, 31, 90, 65, 15, 1,
|
717 |
+
0, 1, 63, 301, 350, 140, 21, 1,
|
718 |
+
0, 1, 127, 966, 1701, 1050, 266, 28, 1,
|
719 |
+
0, 1, 255, 3025, 7770, 6951, 2646, 462, 36, 1]
|
720 |
+
assert stirling(3, 4, kind=1) == stirling(3, 4, kind=1) == 0
|
721 |
+
raises(ValueError, lambda: stirling(-2, 2))
|
722 |
+
|
723 |
+
# Assertion that the return type is SymPy Integer.
|
724 |
+
assert isinstance(_stirling1(6, 3), Integer)
|
725 |
+
assert isinstance(_stirling2(6, 3), Integer)
|
726 |
+
|
727 |
+
def delta(p):
|
728 |
+
if len(p) == 1:
|
729 |
+
return oo
|
730 |
+
return min(abs(i[0] - i[1]) for i in subsets(p, 2))
|
731 |
+
parts = multiset_partitions(range(5), 3)
|
732 |
+
d = 2
|
733 |
+
assert (sum(1 for p in parts if all(delta(i) >= d for i in p)) ==
|
734 |
+
stirling(5, 3, d=d) == 7)
|
735 |
+
|
736 |
+
# other coverage tests
|
737 |
+
assert nC('abb', 2) == nC('aab', 2) == 2
|
738 |
+
assert nP(3, 3, replacement=True) == nP('aabc', 3, replacement=True) == 27
|
739 |
+
assert nP(3, 4) == 0
|
740 |
+
assert nP('aabc', 5) == 0
|
741 |
+
assert nC(4, 2, replacement=True) == nC('abcdd', 2, replacement=True) == \
|
742 |
+
len(list(multiset_combinations('aabbccdd', 2))) == 10
|
743 |
+
assert nC('abcdd') == sum(nC('abcdd', i) for i in range(6)) == 24
|
744 |
+
assert nC(list('abcdd'), 4) == 4
|
745 |
+
assert nT('aaaa') == nT(4) == len(list(partitions(4))) == 5
|
746 |
+
assert nT('aaab') == len(list(multiset_partitions('aaab'))) == 7
|
747 |
+
assert nC('aabb'*3, 3) == 4 # aaa, bbb, abb, baa
|
748 |
+
assert dict(_AOP_product((4,1,1,1))) == {
|
749 |
+
0: 1, 1: 4, 2: 7, 3: 8, 4: 8, 5: 7, 6: 4, 7: 1}
|
750 |
+
# the following was the first t that showed a problem in a previous form of
|
751 |
+
# the function, so it's not as random as it may appear
|
752 |
+
t = (3, 9, 4, 6, 6, 5, 5, 2, 10, 4)
|
753 |
+
assert sum(_AOP_product(t)[i] for i in range(55)) == 58212000
|
754 |
+
raises(ValueError, lambda: _multiset_histogram({1:'a'}))
|
755 |
+
|
756 |
+
|
757 |
+
def test_PR_14617():
|
758 |
+
from sympy.functions.combinatorial.numbers import nT
|
759 |
+
for n in (0, []):
|
760 |
+
for k in (-1, 0, 1):
|
761 |
+
if k == 0:
|
762 |
+
assert nT(n, k) == 1
|
763 |
+
else:
|
764 |
+
assert nT(n, k) == 0
|
765 |
+
|
766 |
+
|
767 |
+
def test_issue_8496():
|
768 |
+
n = Symbol("n")
|
769 |
+
k = Symbol("k")
|
770 |
+
|
771 |
+
raises(TypeError, lambda: catalan(n, k))
|
772 |
+
|
773 |
+
|
774 |
+
def test_issue_8601():
|
775 |
+
n = Symbol('n', integer=True, negative=True)
|
776 |
+
|
777 |
+
assert catalan(n - 1) is S.Zero
|
778 |
+
assert catalan(Rational(-1, 2)) is S.ComplexInfinity
|
779 |
+
assert catalan(-S.One) == Rational(-1, 2)
|
780 |
+
c1 = catalan(-5.6).evalf()
|
781 |
+
assert str(c1) == '6.93334070531408e-5'
|
782 |
+
c2 = catalan(-35.4).evalf()
|
783 |
+
assert str(c2) == '-4.14189164517449e-24'
|
784 |
+
|
785 |
+
|
786 |
+
def test_motzkin():
|
787 |
+
assert motzkin.is_motzkin(4) == True
|
788 |
+
assert motzkin.is_motzkin(9) == True
|
789 |
+
assert motzkin.is_motzkin(10) == False
|
790 |
+
assert motzkin.find_motzkin_numbers_in_range(10,200) == [21, 51, 127]
|
791 |
+
assert motzkin.find_motzkin_numbers_in_range(10,400) == [21, 51, 127, 323]
|
792 |
+
assert motzkin.find_motzkin_numbers_in_range(10,1600) == [21, 51, 127, 323, 835]
|
793 |
+
assert motzkin.find_first_n_motzkins(5) == [1, 1, 2, 4, 9]
|
794 |
+
assert motzkin.find_first_n_motzkins(7) == [1, 1, 2, 4, 9, 21, 51]
|
795 |
+
assert motzkin.find_first_n_motzkins(10) == [1, 1, 2, 4, 9, 21, 51, 127, 323, 835]
|
796 |
+
raises(ValueError, lambda: motzkin.eval(77.58))
|
797 |
+
raises(ValueError, lambda: motzkin.eval(-8))
|
798 |
+
raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(-2,7))
|
799 |
+
raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(13,7))
|
800 |
+
raises(ValueError, lambda: motzkin.find_first_n_motzkins(112.8))
|
801 |
+
|
802 |
+
|
803 |
+
def test_nD_derangements():
|
804 |
+
from sympy.utilities.iterables import (partitions, multiset,
|
805 |
+
multiset_derangements, multiset_permutations)
|
806 |
+
from sympy.functions.combinatorial.numbers import nD
|
807 |
+
|
808 |
+
got = []
|
809 |
+
for i in partitions(8, k=4):
|
810 |
+
s = []
|
811 |
+
it = 0
|
812 |
+
for k, v in i.items():
|
813 |
+
for i in range(v):
|
814 |
+
s.extend([it]*k)
|
815 |
+
it += 1
|
816 |
+
ms = multiset(s)
|
817 |
+
c1 = sum(1 for i in multiset_permutations(s) if
|
818 |
+
all(i != j for i, j in zip(i, s)))
|
819 |
+
assert c1 == nD(ms) == nD(ms, 0) == nD(ms, 1)
|
820 |
+
v = [tuple(i) for i in multiset_derangements(s)]
|
821 |
+
c2 = len(v)
|
822 |
+
assert c2 == len(set(v))
|
823 |
+
assert c1 == c2
|
824 |
+
got.append(c1)
|
825 |
+
assert got == [1, 4, 6, 12, 24, 24, 61, 126, 315, 780, 297, 772,
|
826 |
+
2033, 5430, 14833]
|
827 |
+
|
828 |
+
assert nD('1112233456', brute=True) == nD('1112233456') == 16356
|
829 |
+
assert nD('') == nD([]) == nD({}) == 0
|
830 |
+
assert nD({1: 0}) == 0
|
831 |
+
raises(ValueError, lambda: nD({1: -1}))
|
832 |
+
assert nD('112') == 0
|
833 |
+
assert nD(i='112') == 0
|
834 |
+
assert [nD(n=i) for i in range(6)] == [0, 0, 1, 2, 9, 44]
|
835 |
+
assert nD((i for i in range(4))) == nD('0123') == 9
|
836 |
+
assert nD(m=(i for i in range(4))) == 3
|
837 |
+
assert nD(m={0: 1, 1: 1, 2: 1, 3: 1}) == 3
|
838 |
+
assert nD(m=[0, 1, 2, 3]) == 3
|
839 |
+
raises(TypeError, lambda: nD(m=0))
|
840 |
+
raises(TypeError, lambda: nD(-1))
|
841 |
+
assert nD({-1: 1, -2: 1}) == 1
|
842 |
+
assert nD(m={0: 3}) == 0
|
843 |
+
raises(ValueError, lambda: nD(i='123', n=3))
|
844 |
+
raises(ValueError, lambda: nD(i='123', m=(1,2)))
|
845 |
+
raises(ValueError, lambda: nD(n=0, m=(1,2)))
|
846 |
+
raises(ValueError, lambda: nD({1: -1}))
|
847 |
+
raises(ValueError, lambda: nD(m={-1: 1, 2: 1}))
|
848 |
+
raises(ValueError, lambda: nD(m={1: -1, 2: 1}))
|
849 |
+
raises(ValueError, lambda: nD(m=[-1, 2]))
|
850 |
+
raises(TypeError, lambda: nD({1: x}))
|
851 |
+
raises(TypeError, lambda: nD(m={1: x}))
|
852 |
+
raises(TypeError, lambda: nD(m={x: 1}))
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
# Stub __init__.py for sympy.functions.elementary
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (194 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/_trigonometric_special.cpython-310.pyc
ADDED
Binary file (8.55 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/complexes.cpython-310.pyc
ADDED
Binary file (39 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/exponential.cpython-310.pyc
ADDED
Binary file (34.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/hyperbolic.cpython-310.pyc
ADDED
Binary file (55.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/integers.cpython-310.pyc
ADDED
Binary file (16 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/miscellaneous.cpython-310.pyc
ADDED
Binary file (30.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/piecewise.cpython-310.pyc
ADDED
Binary file (44.7 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/trigonometric.cpython-310.pyc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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
r"""A module for special angle forumlas for trigonometric functions
|
2 |
+
|
3 |
+
TODO
|
4 |
+
====
|
5 |
+
|
6 |
+
This module should be developed in the future to contain direct squrae root
|
7 |
+
representation of
|
8 |
+
|
9 |
+
.. math
|
10 |
+
F(\frac{n}{m} \pi)
|
11 |
+
|
12 |
+
for every
|
13 |
+
|
14 |
+
- $m \in \{ 3, 5, 17, 257, 65537 \}$
|
15 |
+
- $n \in \mathbb{N}$, $0 \le n < m$
|
16 |
+
- $F \in \{\sin, \cos, \tan, \csc, \sec, \cot\}$
|
17 |
+
|
18 |
+
Without multi-step rewrites
|
19 |
+
(e.g. $\tan \to \cos/\sin \to \cos/\sqrt \to \ sqrt$)
|
20 |
+
or using chebyshev identities
|
21 |
+
(e.g. $\cos \to \cos + \cos^2 + \cdots \to \sqrt{} + \sqrt{}^2 + \cdots $),
|
22 |
+
which are trivial to implement in sympy,
|
23 |
+
and had used to give overly complicated expressions.
|
24 |
+
|
25 |
+
The reference can be found below, if anyone may need help implementing them.
|
26 |
+
|
27 |
+
References
|
28 |
+
==========
|
29 |
+
|
30 |
+
.. [*] Gottlieb, Christian. (1999). The Simple and straightforward construction
|
31 |
+
of the regular 257-gon. The Mathematical Intelligencer. 21. 31-37.
|
32 |
+
10.1007/BF03024829.
|
33 |
+
.. [*] https://resources.wolframcloud.com/FunctionRepository/resources/Cos2PiOverFermatPrime
|
34 |
+
"""
|
35 |
+
from __future__ import annotations
|
36 |
+
from typing import Callable
|
37 |
+
from functools import reduce
|
38 |
+
from sympy.core.expr import Expr
|
39 |
+
from sympy.core.singleton import S
|
40 |
+
from sympy.core.numbers import igcdex, Integer
|
41 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
42 |
+
from sympy.core.cache import cacheit
|
43 |
+
|
44 |
+
|
45 |
+
def migcdex(*x: int) -> tuple[tuple[int, ...], int]:
|
46 |
+
r"""Compute extended gcd for multiple integers.
|
47 |
+
|
48 |
+
Explanation
|
49 |
+
===========
|
50 |
+
|
51 |
+
Given the integers $x_1, \cdots, x_n$ and
|
52 |
+
an extended gcd for multiple arguments are defined as a solution
|
53 |
+
$(y_1, \cdots, y_n), g$ for the diophantine equation
|
54 |
+
$x_1 y_1 + \cdots + x_n y_n = g$ such that
|
55 |
+
$g = \gcd(x_1, \cdots, x_n)$.
|
56 |
+
|
57 |
+
Examples
|
58 |
+
========
|
59 |
+
|
60 |
+
>>> from sympy.functions.elementary._trigonometric_special import migcdex
|
61 |
+
>>> migcdex()
|
62 |
+
((), 0)
|
63 |
+
>>> migcdex(4)
|
64 |
+
((1,), 4)
|
65 |
+
>>> migcdex(4, 6)
|
66 |
+
((-1, 1), 2)
|
67 |
+
>>> migcdex(6, 10, 15)
|
68 |
+
((1, 1, -1), 1)
|
69 |
+
"""
|
70 |
+
if not x:
|
71 |
+
return (), 0
|
72 |
+
|
73 |
+
if len(x) == 1:
|
74 |
+
return (1,), x[0]
|
75 |
+
|
76 |
+
if len(x) == 2:
|
77 |
+
u, v, h = igcdex(x[0], x[1])
|
78 |
+
return (u, v), h
|
79 |
+
|
80 |
+
y, g = migcdex(*x[1:])
|
81 |
+
u, v, h = igcdex(x[0], g)
|
82 |
+
return (u, *(v * i for i in y)), h
|
83 |
+
|
84 |
+
|
85 |
+
def ipartfrac(*denoms: int) -> tuple[int, ...]:
|
86 |
+
r"""Compute the the partial fraction decomposition.
|
87 |
+
|
88 |
+
Explanation
|
89 |
+
===========
|
90 |
+
|
91 |
+
Given a rational number $\frac{1}{q_1 \cdots q_n}$ where all
|
92 |
+
$q_1, \cdots, q_n$ are pairwise coprime,
|
93 |
+
|
94 |
+
A partial fraction decomposition is defined as
|
95 |
+
|
96 |
+
.. math::
|
97 |
+
\frac{1}{q_1 \cdots q_n} = \frac{p_1}{q_1} + \cdots + \frac{p_n}{q_n}
|
98 |
+
|
99 |
+
And it can be derived from solving the following diophantine equation for
|
100 |
+
the $p_1, \cdots, p_n$
|
101 |
+
|
102 |
+
.. math::
|
103 |
+
1 = p_1 \prod_{i \ne 1}q_i + \cdots + p_n \prod_{i \ne n}q_i
|
104 |
+
|
105 |
+
Where $q_1, \cdots, q_n$ being pairwise coprime implies
|
106 |
+
$\gcd(\prod_{i \ne 1}q_i, \cdots, \prod_{i \ne n}q_i) = 1$,
|
107 |
+
which guarantees the existance of the solution.
|
108 |
+
|
109 |
+
It is sufficient to compute partial fraction decomposition only
|
110 |
+
for numerator $1$ because partial fraction decomposition for any
|
111 |
+
$\frac{n}{q_1 \cdots q_n}$ can be easily computed by multiplying
|
112 |
+
the result by $n$ afterwards.
|
113 |
+
|
114 |
+
Parameters
|
115 |
+
==========
|
116 |
+
|
117 |
+
denoms : int
|
118 |
+
The pairwise coprime integer denominators $q_i$ which defines the
|
119 |
+
rational number $\frac{1}{q_1 \cdots q_n}$
|
120 |
+
|
121 |
+
Returns
|
122 |
+
=======
|
123 |
+
|
124 |
+
tuple[int, ...]
|
125 |
+
The list of numerators which semantically corresponds to $p_i$ of the
|
126 |
+
partial fraction decomposition
|
127 |
+
$\frac{1}{q_1 \cdots q_n} = \frac{p_1}{q_1} + \cdots + \frac{p_n}{q_n}$
|
128 |
+
|
129 |
+
Examples
|
130 |
+
========
|
131 |
+
|
132 |
+
>>> from sympy import Rational, Mul
|
133 |
+
>>> from sympy.functions.elementary._trigonometric_special import ipartfrac
|
134 |
+
|
135 |
+
>>> denoms = 2, 3, 5
|
136 |
+
>>> numers = ipartfrac(2, 3, 5)
|
137 |
+
>>> numers
|
138 |
+
(1, 7, -14)
|
139 |
+
|
140 |
+
>>> Rational(1, Mul(*denoms))
|
141 |
+
1/30
|
142 |
+
>>> out = 0
|
143 |
+
>>> for n, d in zip(numers, denoms):
|
144 |
+
... out += Rational(n, d)
|
145 |
+
>>> out
|
146 |
+
1/30
|
147 |
+
"""
|
148 |
+
if not denoms:
|
149 |
+
return ()
|
150 |
+
|
151 |
+
def mul(x: int, y: int) -> int:
|
152 |
+
return x * y
|
153 |
+
|
154 |
+
denom = reduce(mul, denoms)
|
155 |
+
a = [denom // x for x in denoms]
|
156 |
+
h, _ = migcdex(*a)
|
157 |
+
return h
|
158 |
+
|
159 |
+
|
160 |
+
def fermat_coords(n: int) -> list[int] | None:
|
161 |
+
"""If n can be factored in terms of Fermat primes with
|
162 |
+
multiplicity of each being 1, return those primes, else
|
163 |
+
None
|
164 |
+
"""
|
165 |
+
primes = []
|
166 |
+
for p in [3, 5, 17, 257, 65537]:
|
167 |
+
quotient, remainder = divmod(n, p)
|
168 |
+
if remainder == 0:
|
169 |
+
n = quotient
|
170 |
+
primes.append(p)
|
171 |
+
if n == 1:
|
172 |
+
return primes
|
173 |
+
return None
|
174 |
+
|
175 |
+
|
176 |
+
@cacheit
|
177 |
+
def cos_3() -> Expr:
|
178 |
+
r"""Computes $\cos \frac{\pi}{3}$ in square roots"""
|
179 |
+
return S.Half
|
180 |
+
|
181 |
+
|
182 |
+
@cacheit
|
183 |
+
def cos_5() -> Expr:
|
184 |
+
r"""Computes $\cos \frac{\pi}{5}$ in square roots"""
|
185 |
+
return (sqrt(5) + 1) / 4
|
186 |
+
|
187 |
+
|
188 |
+
@cacheit
|
189 |
+
def cos_17() -> Expr:
|
190 |
+
r"""Computes $\cos \frac{\pi}{17}$ in square roots"""
|
191 |
+
return sqrt(
|
192 |
+
(15 + sqrt(17)) / 32 + sqrt(2) * (sqrt(17 - sqrt(17)) +
|
193 |
+
sqrt(sqrt(2) * (-8 * sqrt(17 + sqrt(17)) - (1 - sqrt(17))
|
194 |
+
* sqrt(17 - sqrt(17))) + 6 * sqrt(17) + 34)) / 32)
|
195 |
+
|
196 |
+
|
197 |
+
@cacheit
|
198 |
+
def cos_257() -> Expr:
|
199 |
+
r"""Computes $\cos \frac{\pi}{257}$ in square roots
|
200 |
+
|
201 |
+
References
|
202 |
+
==========
|
203 |
+
|
204 |
+
.. [*] https://math.stackexchange.com/questions/516142/how-does-cos2-pi-257-look-like-in-real-radicals
|
205 |
+
.. [*] https://r-knott.surrey.ac.uk/Fibonacci/simpleTrig.html
|
206 |
+
"""
|
207 |
+
def f1(a: Expr, b: Expr) -> tuple[Expr, Expr]:
|
208 |
+
return (a + sqrt(a**2 + b)) / 2, (a - sqrt(a**2 + b)) / 2
|
209 |
+
|
210 |
+
def f2(a: Expr, b: Expr) -> Expr:
|
211 |
+
return (a - sqrt(a**2 + b))/2
|
212 |
+
|
213 |
+
t1, t2 = f1(S.NegativeOne, Integer(256))
|
214 |
+
z1, z3 = f1(t1, Integer(64))
|
215 |
+
z2, z4 = f1(t2, Integer(64))
|
216 |
+
y1, y5 = f1(z1, 4*(5 + t1 + 2*z1))
|
217 |
+
y6, y2 = f1(z2, 4*(5 + t2 + 2*z2))
|
218 |
+
y3, y7 = f1(z3, 4*(5 + t1 + 2*z3))
|
219 |
+
y8, y4 = f1(z4, 4*(5 + t2 + 2*z4))
|
220 |
+
x1, x9 = f1(y1, -4*(t1 + y1 + y3 + 2*y6))
|
221 |
+
x2, x10 = f1(y2, -4*(t2 + y2 + y4 + 2*y7))
|
222 |
+
x3, x11 = f1(y3, -4*(t1 + y3 + y5 + 2*y8))
|
223 |
+
x4, x12 = f1(y4, -4*(t2 + y4 + y6 + 2*y1))
|
224 |
+
x5, x13 = f1(y5, -4*(t1 + y5 + y7 + 2*y2))
|
225 |
+
x6, x14 = f1(y6, -4*(t2 + y6 + y8 + 2*y3))
|
226 |
+
x15, x7 = f1(y7, -4*(t1 + y7 + y1 + 2*y4))
|
227 |
+
x8, x16 = f1(y8, -4*(t2 + y8 + y2 + 2*y5))
|
228 |
+
v1 = f2(x1, -4*(x1 + x2 + x3 + x6))
|
229 |
+
v2 = f2(x2, -4*(x2 + x3 + x4 + x7))
|
230 |
+
v3 = f2(x8, -4*(x8 + x9 + x10 + x13))
|
231 |
+
v4 = f2(x9, -4*(x9 + x10 + x11 + x14))
|
232 |
+
v5 = f2(x10, -4*(x10 + x11 + x12 + x15))
|
233 |
+
v6 = f2(x16, -4*(x16 + x1 + x2 + x5))
|
234 |
+
u1 = -f2(-v1, -4*(v2 + v3))
|
235 |
+
u2 = -f2(-v4, -4*(v5 + v6))
|
236 |
+
w1 = -2*f2(-u1, -4*u2)
|
237 |
+
return sqrt(sqrt(2)*sqrt(w1 + 4)/8 + S.Half)
|
238 |
+
|
239 |
+
|
240 |
+
def cos_table() -> dict[int, Callable[[], Expr]]:
|
241 |
+
r"""Lazily evaluated table for $\cos \frac{\pi}{n}$ in square roots for
|
242 |
+
$n \in \{3, 5, 17, 257, 65537\}$.
|
243 |
+
|
244 |
+
Notes
|
245 |
+
=====
|
246 |
+
|
247 |
+
65537 is the only other known Fermat prime and it is nearly impossible to
|
248 |
+
build in the current SymPy due to performance issues.
|
249 |
+
|
250 |
+
References
|
251 |
+
==========
|
252 |
+
|
253 |
+
https://r-knott.surrey.ac.uk/Fibonacci/simpleTrig.html
|
254 |
+
"""
|
255 |
+
return {
|
256 |
+
3: cos_3,
|
257 |
+
5: cos_5,
|
258 |
+
17: cos_17,
|
259 |
+
257: cos_257
|
260 |
+
}
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (205 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__pycache__/bench_exp.cpython-310.pyc
ADDED
Binary file (530 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/bench_exp.py
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.symbol import symbols
|
2 |
+
from sympy.functions.elementary.exponential import exp
|
3 |
+
|
4 |
+
x, y = symbols('x,y')
|
5 |
+
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Tuple as tTuple
|
2 |
+
|
3 |
+
from sympy.core import S, Add, Mul, sympify, Symbol, Dummy, Basic
|
4 |
+
from sympy.core.expr import Expr
|
5 |
+
from sympy.core.exprtools import factor_terms
|
6 |
+
from sympy.core.function import (Function, Derivative, ArgumentIndexError,
|
7 |
+
AppliedUndef, expand_mul)
|
8 |
+
from sympy.core.logic import fuzzy_not, fuzzy_or
|
9 |
+
from sympy.core.numbers import pi, I, oo
|
10 |
+
from sympy.core.power import Pow
|
11 |
+
from sympy.core.relational import Eq
|
12 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
13 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
14 |
+
|
15 |
+
###############################################################################
|
16 |
+
######################### REAL and IMAGINARY PARTS ############################
|
17 |
+
###############################################################################
|
18 |
+
|
19 |
+
|
20 |
+
class re(Function):
|
21 |
+
"""
|
22 |
+
Returns real part of expression. This function performs only
|
23 |
+
elementary analysis and so it will fail to decompose properly
|
24 |
+
more complicated expressions. If completely simplified result
|
25 |
+
is needed then use ``Basic.as_real_imag()`` or perform complex
|
26 |
+
expansion on instance of this function.
|
27 |
+
|
28 |
+
Examples
|
29 |
+
========
|
30 |
+
|
31 |
+
>>> from sympy import re, im, I, E, symbols
|
32 |
+
>>> x, y = symbols('x y', real=True)
|
33 |
+
>>> re(2*E)
|
34 |
+
2*E
|
35 |
+
>>> re(2*I + 17)
|
36 |
+
17
|
37 |
+
>>> re(2*I)
|
38 |
+
0
|
39 |
+
>>> re(im(x) + x*I + 2)
|
40 |
+
2
|
41 |
+
>>> re(5 + I + 2)
|
42 |
+
7
|
43 |
+
|
44 |
+
Parameters
|
45 |
+
==========
|
46 |
+
|
47 |
+
arg : Expr
|
48 |
+
Real or complex expression.
|
49 |
+
|
50 |
+
Returns
|
51 |
+
=======
|
52 |
+
|
53 |
+
expr : Expr
|
54 |
+
Real part of expression.
|
55 |
+
|
56 |
+
See Also
|
57 |
+
========
|
58 |
+
|
59 |
+
im
|
60 |
+
"""
|
61 |
+
|
62 |
+
args: tTuple[Expr]
|
63 |
+
|
64 |
+
is_extended_real = True
|
65 |
+
unbranched = True # implicitly works on the projection to C
|
66 |
+
_singularities = True # non-holomorphic
|
67 |
+
|
68 |
+
@classmethod
|
69 |
+
def eval(cls, arg):
|
70 |
+
if arg is S.NaN:
|
71 |
+
return S.NaN
|
72 |
+
elif arg is S.ComplexInfinity:
|
73 |
+
return S.NaN
|
74 |
+
elif arg.is_extended_real:
|
75 |
+
return arg
|
76 |
+
elif arg.is_imaginary or (I*arg).is_extended_real:
|
77 |
+
return S.Zero
|
78 |
+
elif arg.is_Matrix:
|
79 |
+
return arg.as_real_imag()[0]
|
80 |
+
elif arg.is_Function and isinstance(arg, conjugate):
|
81 |
+
return re(arg.args[0])
|
82 |
+
else:
|
83 |
+
|
84 |
+
included, reverted, excluded = [], [], []
|
85 |
+
args = Add.make_args(arg)
|
86 |
+
for term in args:
|
87 |
+
coeff = term.as_coefficient(I)
|
88 |
+
|
89 |
+
if coeff is not None:
|
90 |
+
if not coeff.is_extended_real:
|
91 |
+
reverted.append(coeff)
|
92 |
+
elif not term.has(I) and term.is_extended_real:
|
93 |
+
excluded.append(term)
|
94 |
+
else:
|
95 |
+
# Try to do some advanced expansion. If
|
96 |
+
# impossible, don't try to do re(arg) again
|
97 |
+
# (because this is what we are trying to do now).
|
98 |
+
real_imag = term.as_real_imag(ignore=arg)
|
99 |
+
if real_imag:
|
100 |
+
excluded.append(real_imag[0])
|
101 |
+
else:
|
102 |
+
included.append(term)
|
103 |
+
|
104 |
+
if len(args) != len(included):
|
105 |
+
a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
|
106 |
+
|
107 |
+
return cls(a) - im(b) + c
|
108 |
+
|
109 |
+
def as_real_imag(self, deep=True, **hints):
|
110 |
+
"""
|
111 |
+
Returns the real number with a zero imaginary part.
|
112 |
+
|
113 |
+
"""
|
114 |
+
return (self, S.Zero)
|
115 |
+
|
116 |
+
def _eval_derivative(self, x):
|
117 |
+
if x.is_extended_real or self.args[0].is_extended_real:
|
118 |
+
return re(Derivative(self.args[0], x, evaluate=True))
|
119 |
+
if x.is_imaginary or self.args[0].is_imaginary:
|
120 |
+
return -I \
|
121 |
+
* im(Derivative(self.args[0], x, evaluate=True))
|
122 |
+
|
123 |
+
def _eval_rewrite_as_im(self, arg, **kwargs):
|
124 |
+
return self.args[0] - I*im(self.args[0])
|
125 |
+
|
126 |
+
def _eval_is_algebraic(self):
|
127 |
+
return self.args[0].is_algebraic
|
128 |
+
|
129 |
+
def _eval_is_zero(self):
|
130 |
+
# is_imaginary implies nonzero
|
131 |
+
return fuzzy_or([self.args[0].is_imaginary, self.args[0].is_zero])
|
132 |
+
|
133 |
+
def _eval_is_finite(self):
|
134 |
+
if self.args[0].is_finite:
|
135 |
+
return True
|
136 |
+
|
137 |
+
def _eval_is_complex(self):
|
138 |
+
if self.args[0].is_finite:
|
139 |
+
return True
|
140 |
+
|
141 |
+
|
142 |
+
class im(Function):
|
143 |
+
"""
|
144 |
+
Returns imaginary part of expression. This function performs only
|
145 |
+
elementary analysis and so it will fail to decompose properly more
|
146 |
+
complicated expressions. If completely simplified result is needed then
|
147 |
+
use ``Basic.as_real_imag()`` or perform complex expansion on instance of
|
148 |
+
this function.
|
149 |
+
|
150 |
+
Examples
|
151 |
+
========
|
152 |
+
|
153 |
+
>>> from sympy import re, im, E, I
|
154 |
+
>>> from sympy.abc import x, y
|
155 |
+
>>> im(2*E)
|
156 |
+
0
|
157 |
+
>>> im(2*I + 17)
|
158 |
+
2
|
159 |
+
>>> im(x*I)
|
160 |
+
re(x)
|
161 |
+
>>> im(re(x) + y)
|
162 |
+
im(y)
|
163 |
+
>>> im(2 + 3*I)
|
164 |
+
3
|
165 |
+
|
166 |
+
Parameters
|
167 |
+
==========
|
168 |
+
|
169 |
+
arg : Expr
|
170 |
+
Real or complex expression.
|
171 |
+
|
172 |
+
Returns
|
173 |
+
=======
|
174 |
+
|
175 |
+
expr : Expr
|
176 |
+
Imaginary part of expression.
|
177 |
+
|
178 |
+
See Also
|
179 |
+
========
|
180 |
+
|
181 |
+
re
|
182 |
+
"""
|
183 |
+
|
184 |
+
args: tTuple[Expr]
|
185 |
+
|
186 |
+
is_extended_real = True
|
187 |
+
unbranched = True # implicitly works on the projection to C
|
188 |
+
_singularities = True # non-holomorphic
|
189 |
+
|
190 |
+
@classmethod
|
191 |
+
def eval(cls, arg):
|
192 |
+
if arg is S.NaN:
|
193 |
+
return S.NaN
|
194 |
+
elif arg is S.ComplexInfinity:
|
195 |
+
return S.NaN
|
196 |
+
elif arg.is_extended_real:
|
197 |
+
return S.Zero
|
198 |
+
elif arg.is_imaginary or (I*arg).is_extended_real:
|
199 |
+
return -I * arg
|
200 |
+
elif arg.is_Matrix:
|
201 |
+
return arg.as_real_imag()[1]
|
202 |
+
elif arg.is_Function and isinstance(arg, conjugate):
|
203 |
+
return -im(arg.args[0])
|
204 |
+
else:
|
205 |
+
included, reverted, excluded = [], [], []
|
206 |
+
args = Add.make_args(arg)
|
207 |
+
for term in args:
|
208 |
+
coeff = term.as_coefficient(I)
|
209 |
+
|
210 |
+
if coeff is not None:
|
211 |
+
if not coeff.is_extended_real:
|
212 |
+
reverted.append(coeff)
|
213 |
+
else:
|
214 |
+
excluded.append(coeff)
|
215 |
+
elif term.has(I) or not term.is_extended_real:
|
216 |
+
# Try to do some advanced expansion. If
|
217 |
+
# impossible, don't try to do im(arg) again
|
218 |
+
# (because this is what we are trying to do now).
|
219 |
+
real_imag = term.as_real_imag(ignore=arg)
|
220 |
+
if real_imag:
|
221 |
+
excluded.append(real_imag[1])
|
222 |
+
else:
|
223 |
+
included.append(term)
|
224 |
+
|
225 |
+
if len(args) != len(included):
|
226 |
+
a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
|
227 |
+
|
228 |
+
return cls(a) + re(b) + c
|
229 |
+
|
230 |
+
def as_real_imag(self, deep=True, **hints):
|
231 |
+
"""
|
232 |
+
Return the imaginary part with a zero real part.
|
233 |
+
|
234 |
+
"""
|
235 |
+
return (self, S.Zero)
|
236 |
+
|
237 |
+
def _eval_derivative(self, x):
|
238 |
+
if x.is_extended_real or self.args[0].is_extended_real:
|
239 |
+
return im(Derivative(self.args[0], x, evaluate=True))
|
240 |
+
if x.is_imaginary or self.args[0].is_imaginary:
|
241 |
+
return -I \
|
242 |
+
* re(Derivative(self.args[0], x, evaluate=True))
|
243 |
+
|
244 |
+
def _eval_rewrite_as_re(self, arg, **kwargs):
|
245 |
+
return -I*(self.args[0] - re(self.args[0]))
|
246 |
+
|
247 |
+
def _eval_is_algebraic(self):
|
248 |
+
return self.args[0].is_algebraic
|
249 |
+
|
250 |
+
def _eval_is_zero(self):
|
251 |
+
return self.args[0].is_extended_real
|
252 |
+
|
253 |
+
def _eval_is_finite(self):
|
254 |
+
if self.args[0].is_finite:
|
255 |
+
return True
|
256 |
+
|
257 |
+
def _eval_is_complex(self):
|
258 |
+
if self.args[0].is_finite:
|
259 |
+
return True
|
260 |
+
|
261 |
+
###############################################################################
|
262 |
+
############### SIGN, ABSOLUTE VALUE, ARGUMENT and CONJUGATION ################
|
263 |
+
###############################################################################
|
264 |
+
|
265 |
+
class sign(Function):
|
266 |
+
"""
|
267 |
+
Returns the complex sign of an expression:
|
268 |
+
|
269 |
+
Explanation
|
270 |
+
===========
|
271 |
+
|
272 |
+
If the expression is real the sign will be:
|
273 |
+
|
274 |
+
* $1$ if expression is positive
|
275 |
+
* $0$ if expression is equal to zero
|
276 |
+
* $-1$ if expression is negative
|
277 |
+
|
278 |
+
If the expression is imaginary the sign will be:
|
279 |
+
|
280 |
+
* $I$ if im(expression) is positive
|
281 |
+
* $-I$ if im(expression) is negative
|
282 |
+
|
283 |
+
Otherwise an unevaluated expression will be returned. When evaluated, the
|
284 |
+
result (in general) will be ``cos(arg(expr)) + I*sin(arg(expr))``.
|
285 |
+
|
286 |
+
Examples
|
287 |
+
========
|
288 |
+
|
289 |
+
>>> from sympy import sign, I
|
290 |
+
|
291 |
+
>>> sign(-1)
|
292 |
+
-1
|
293 |
+
>>> sign(0)
|
294 |
+
0
|
295 |
+
>>> sign(-3*I)
|
296 |
+
-I
|
297 |
+
>>> sign(1 + I)
|
298 |
+
sign(1 + I)
|
299 |
+
>>> _.evalf()
|
300 |
+
0.707106781186548 + 0.707106781186548*I
|
301 |
+
|
302 |
+
Parameters
|
303 |
+
==========
|
304 |
+
|
305 |
+
arg : Expr
|
306 |
+
Real or imaginary expression.
|
307 |
+
|
308 |
+
Returns
|
309 |
+
=======
|
310 |
+
|
311 |
+
expr : Expr
|
312 |
+
Complex sign of expression.
|
313 |
+
|
314 |
+
See Also
|
315 |
+
========
|
316 |
+
|
317 |
+
Abs, conjugate
|
318 |
+
"""
|
319 |
+
|
320 |
+
is_complex = True
|
321 |
+
_singularities = True
|
322 |
+
|
323 |
+
def doit(self, **hints):
|
324 |
+
s = super().doit()
|
325 |
+
if s == self and self.args[0].is_zero is False:
|
326 |
+
return self.args[0] / Abs(self.args[0])
|
327 |
+
return s
|
328 |
+
|
329 |
+
@classmethod
|
330 |
+
def eval(cls, arg):
|
331 |
+
# handle what we can
|
332 |
+
if arg.is_Mul:
|
333 |
+
c, args = arg.as_coeff_mul()
|
334 |
+
unk = []
|
335 |
+
s = sign(c)
|
336 |
+
for a in args:
|
337 |
+
if a.is_extended_negative:
|
338 |
+
s = -s
|
339 |
+
elif a.is_extended_positive:
|
340 |
+
pass
|
341 |
+
else:
|
342 |
+
if a.is_imaginary:
|
343 |
+
ai = im(a)
|
344 |
+
if ai.is_comparable: # i.e. a = I*real
|
345 |
+
s *= I
|
346 |
+
if ai.is_extended_negative:
|
347 |
+
# can't use sign(ai) here since ai might not be
|
348 |
+
# a Number
|
349 |
+
s = -s
|
350 |
+
else:
|
351 |
+
unk.append(a)
|
352 |
+
else:
|
353 |
+
unk.append(a)
|
354 |
+
if c is S.One and len(unk) == len(args):
|
355 |
+
return None
|
356 |
+
return s * cls(arg._new_rawargs(*unk))
|
357 |
+
if arg is S.NaN:
|
358 |
+
return S.NaN
|
359 |
+
if arg.is_zero: # it may be an Expr that is zero
|
360 |
+
return S.Zero
|
361 |
+
if arg.is_extended_positive:
|
362 |
+
return S.One
|
363 |
+
if arg.is_extended_negative:
|
364 |
+
return S.NegativeOne
|
365 |
+
if arg.is_Function:
|
366 |
+
if isinstance(arg, sign):
|
367 |
+
return arg
|
368 |
+
if arg.is_imaginary:
|
369 |
+
if arg.is_Pow and arg.exp is S.Half:
|
370 |
+
# we catch this because non-trivial sqrt args are not expanded
|
371 |
+
# e.g. sqrt(1-sqrt(2)) --x--> to I*sqrt(sqrt(2) - 1)
|
372 |
+
return I
|
373 |
+
arg2 = -I * arg
|
374 |
+
if arg2.is_extended_positive:
|
375 |
+
return I
|
376 |
+
if arg2.is_extended_negative:
|
377 |
+
return -I
|
378 |
+
|
379 |
+
def _eval_Abs(self):
|
380 |
+
if fuzzy_not(self.args[0].is_zero):
|
381 |
+
return S.One
|
382 |
+
|
383 |
+
def _eval_conjugate(self):
|
384 |
+
return sign(conjugate(self.args[0]))
|
385 |
+
|
386 |
+
def _eval_derivative(self, x):
|
387 |
+
if self.args[0].is_extended_real:
|
388 |
+
from sympy.functions.special.delta_functions import DiracDelta
|
389 |
+
return 2 * Derivative(self.args[0], x, evaluate=True) \
|
390 |
+
* DiracDelta(self.args[0])
|
391 |
+
elif self.args[0].is_imaginary:
|
392 |
+
from sympy.functions.special.delta_functions import DiracDelta
|
393 |
+
return 2 * Derivative(self.args[0], x, evaluate=True) \
|
394 |
+
* DiracDelta(-I * self.args[0])
|
395 |
+
|
396 |
+
def _eval_is_nonnegative(self):
|
397 |
+
if self.args[0].is_nonnegative:
|
398 |
+
return True
|
399 |
+
|
400 |
+
def _eval_is_nonpositive(self):
|
401 |
+
if self.args[0].is_nonpositive:
|
402 |
+
return True
|
403 |
+
|
404 |
+
def _eval_is_imaginary(self):
|
405 |
+
return self.args[0].is_imaginary
|
406 |
+
|
407 |
+
def _eval_is_integer(self):
|
408 |
+
return self.args[0].is_extended_real
|
409 |
+
|
410 |
+
def _eval_is_zero(self):
|
411 |
+
return self.args[0].is_zero
|
412 |
+
|
413 |
+
def _eval_power(self, other):
|
414 |
+
if (
|
415 |
+
fuzzy_not(self.args[0].is_zero) and
|
416 |
+
other.is_integer and
|
417 |
+
other.is_even
|
418 |
+
):
|
419 |
+
return S.One
|
420 |
+
|
421 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
422 |
+
arg0 = self.args[0]
|
423 |
+
x0 = arg0.subs(x, 0)
|
424 |
+
if x0 != 0:
|
425 |
+
return self.func(x0)
|
426 |
+
if cdir != 0:
|
427 |
+
cdir = arg0.dir(x, cdir)
|
428 |
+
return -S.One if re(cdir) < 0 else S.One
|
429 |
+
|
430 |
+
def _eval_rewrite_as_Piecewise(self, arg, **kwargs):
|
431 |
+
if arg.is_extended_real:
|
432 |
+
return Piecewise((1, arg > 0), (-1, arg < 0), (0, True))
|
433 |
+
|
434 |
+
def _eval_rewrite_as_Heaviside(self, arg, **kwargs):
|
435 |
+
from sympy.functions.special.delta_functions import Heaviside
|
436 |
+
if arg.is_extended_real:
|
437 |
+
return Heaviside(arg) * 2 - 1
|
438 |
+
|
439 |
+
def _eval_rewrite_as_Abs(self, arg, **kwargs):
|
440 |
+
return Piecewise((0, Eq(arg, 0)), (arg / Abs(arg), True))
|
441 |
+
|
442 |
+
def _eval_simplify(self, **kwargs):
|
443 |
+
return self.func(factor_terms(self.args[0])) # XXX include doit?
|
444 |
+
|
445 |
+
|
446 |
+
class Abs(Function):
|
447 |
+
"""
|
448 |
+
Return the absolute value of the argument.
|
449 |
+
|
450 |
+
Explanation
|
451 |
+
===========
|
452 |
+
|
453 |
+
This is an extension of the built-in function ``abs()`` to accept symbolic
|
454 |
+
values. If you pass a SymPy expression to the built-in ``abs()``, it will
|
455 |
+
pass it automatically to ``Abs()``.
|
456 |
+
|
457 |
+
Examples
|
458 |
+
========
|
459 |
+
|
460 |
+
>>> from sympy import Abs, Symbol, S, I
|
461 |
+
>>> Abs(-1)
|
462 |
+
1
|
463 |
+
>>> x = Symbol('x', real=True)
|
464 |
+
>>> Abs(-x)
|
465 |
+
Abs(x)
|
466 |
+
>>> Abs(x**2)
|
467 |
+
x**2
|
468 |
+
>>> abs(-x) # The Python built-in
|
469 |
+
Abs(x)
|
470 |
+
>>> Abs(3*x + 2*I)
|
471 |
+
sqrt(9*x**2 + 4)
|
472 |
+
>>> Abs(8*I)
|
473 |
+
8
|
474 |
+
|
475 |
+
Note that the Python built-in will return either an Expr or int depending on
|
476 |
+
the argument::
|
477 |
+
|
478 |
+
>>> type(abs(-1))
|
479 |
+
<... 'int'>
|
480 |
+
>>> type(abs(S.NegativeOne))
|
481 |
+
<class 'sympy.core.numbers.One'>
|
482 |
+
|
483 |
+
Abs will always return a SymPy object.
|
484 |
+
|
485 |
+
Parameters
|
486 |
+
==========
|
487 |
+
|
488 |
+
arg : Expr
|
489 |
+
Real or complex expression.
|
490 |
+
|
491 |
+
Returns
|
492 |
+
=======
|
493 |
+
|
494 |
+
expr : Expr
|
495 |
+
Absolute value returned can be an expression or integer depending on
|
496 |
+
input arg.
|
497 |
+
|
498 |
+
See Also
|
499 |
+
========
|
500 |
+
|
501 |
+
sign, conjugate
|
502 |
+
"""
|
503 |
+
|
504 |
+
args: tTuple[Expr]
|
505 |
+
|
506 |
+
is_extended_real = True
|
507 |
+
is_extended_negative = False
|
508 |
+
is_extended_nonnegative = True
|
509 |
+
unbranched = True
|
510 |
+
_singularities = True # non-holomorphic
|
511 |
+
|
512 |
+
def fdiff(self, argindex=1):
|
513 |
+
"""
|
514 |
+
Get the first derivative of the argument to Abs().
|
515 |
+
|
516 |
+
"""
|
517 |
+
if argindex == 1:
|
518 |
+
return sign(self.args[0])
|
519 |
+
else:
|
520 |
+
raise ArgumentIndexError(self, argindex)
|
521 |
+
|
522 |
+
@classmethod
|
523 |
+
def eval(cls, arg):
|
524 |
+
from sympy.simplify.simplify import signsimp
|
525 |
+
|
526 |
+
if hasattr(arg, '_eval_Abs'):
|
527 |
+
obj = arg._eval_Abs()
|
528 |
+
if obj is not None:
|
529 |
+
return obj
|
530 |
+
if not isinstance(arg, Expr):
|
531 |
+
raise TypeError("Bad argument type for Abs(): %s" % type(arg))
|
532 |
+
|
533 |
+
# handle what we can
|
534 |
+
arg = signsimp(arg, evaluate=False)
|
535 |
+
n, d = arg.as_numer_denom()
|
536 |
+
if d.free_symbols and not n.free_symbols:
|
537 |
+
return cls(n)/cls(d)
|
538 |
+
|
539 |
+
if arg.is_Mul:
|
540 |
+
known = []
|
541 |
+
unk = []
|
542 |
+
for t in arg.args:
|
543 |
+
if t.is_Pow and t.exp.is_integer and t.exp.is_negative:
|
544 |
+
bnew = cls(t.base)
|
545 |
+
if isinstance(bnew, cls):
|
546 |
+
unk.append(t)
|
547 |
+
else:
|
548 |
+
known.append(Pow(bnew, t.exp))
|
549 |
+
else:
|
550 |
+
tnew = cls(t)
|
551 |
+
if isinstance(tnew, cls):
|
552 |
+
unk.append(t)
|
553 |
+
else:
|
554 |
+
known.append(tnew)
|
555 |
+
known = Mul(*known)
|
556 |
+
unk = cls(Mul(*unk), evaluate=False) if unk else S.One
|
557 |
+
return known*unk
|
558 |
+
if arg is S.NaN:
|
559 |
+
return S.NaN
|
560 |
+
if arg is S.ComplexInfinity:
|
561 |
+
return oo
|
562 |
+
from sympy.functions.elementary.exponential import exp, log
|
563 |
+
|
564 |
+
if arg.is_Pow:
|
565 |
+
base, exponent = arg.as_base_exp()
|
566 |
+
if base.is_extended_real:
|
567 |
+
if exponent.is_integer:
|
568 |
+
if exponent.is_even:
|
569 |
+
return arg
|
570 |
+
if base is S.NegativeOne:
|
571 |
+
return S.One
|
572 |
+
return Abs(base)**exponent
|
573 |
+
if base.is_extended_nonnegative:
|
574 |
+
return base**re(exponent)
|
575 |
+
if base.is_extended_negative:
|
576 |
+
return (-base)**re(exponent)*exp(-pi*im(exponent))
|
577 |
+
return
|
578 |
+
elif not base.has(Symbol): # complex base
|
579 |
+
# express base**exponent as exp(exponent*log(base))
|
580 |
+
a, b = log(base).as_real_imag()
|
581 |
+
z = a + I*b
|
582 |
+
return exp(re(exponent*z))
|
583 |
+
if isinstance(arg, exp):
|
584 |
+
return exp(re(arg.args[0]))
|
585 |
+
if isinstance(arg, AppliedUndef):
|
586 |
+
if arg.is_positive:
|
587 |
+
return arg
|
588 |
+
elif arg.is_negative:
|
589 |
+
return -arg
|
590 |
+
return
|
591 |
+
if arg.is_Add and arg.has(oo, S.NegativeInfinity):
|
592 |
+
if any(a.is_infinite for a in arg.as_real_imag()):
|
593 |
+
return oo
|
594 |
+
if arg.is_zero:
|
595 |
+
return S.Zero
|
596 |
+
if arg.is_extended_nonnegative:
|
597 |
+
return arg
|
598 |
+
if arg.is_extended_nonpositive:
|
599 |
+
return -arg
|
600 |
+
if arg.is_imaginary:
|
601 |
+
arg2 = -I * arg
|
602 |
+
if arg2.is_extended_nonnegative:
|
603 |
+
return arg2
|
604 |
+
if arg.is_extended_real:
|
605 |
+
return
|
606 |
+
# reject result if all new conjugates are just wrappers around
|
607 |
+
# an expression that was already in the arg
|
608 |
+
conj = signsimp(arg.conjugate(), evaluate=False)
|
609 |
+
new_conj = conj.atoms(conjugate) - arg.atoms(conjugate)
|
610 |
+
if new_conj and all(arg.has(i.args[0]) for i in new_conj):
|
611 |
+
return
|
612 |
+
if arg != conj and arg != -conj:
|
613 |
+
ignore = arg.atoms(Abs)
|
614 |
+
abs_free_arg = arg.xreplace({i: Dummy(real=True) for i in ignore})
|
615 |
+
unk = [a for a in abs_free_arg.free_symbols if a.is_extended_real is None]
|
616 |
+
if not unk or not all(conj.has(conjugate(u)) for u in unk):
|
617 |
+
return sqrt(expand_mul(arg*conj))
|
618 |
+
|
619 |
+
def _eval_is_real(self):
|
620 |
+
if self.args[0].is_finite:
|
621 |
+
return True
|
622 |
+
|
623 |
+
def _eval_is_integer(self):
|
624 |
+
if self.args[0].is_extended_real:
|
625 |
+
return self.args[0].is_integer
|
626 |
+
|
627 |
+
def _eval_is_extended_nonzero(self):
|
628 |
+
return fuzzy_not(self._args[0].is_zero)
|
629 |
+
|
630 |
+
def _eval_is_zero(self):
|
631 |
+
return self._args[0].is_zero
|
632 |
+
|
633 |
+
def _eval_is_extended_positive(self):
|
634 |
+
return fuzzy_not(self._args[0].is_zero)
|
635 |
+
|
636 |
+
def _eval_is_rational(self):
|
637 |
+
if self.args[0].is_extended_real:
|
638 |
+
return self.args[0].is_rational
|
639 |
+
|
640 |
+
def _eval_is_even(self):
|
641 |
+
if self.args[0].is_extended_real:
|
642 |
+
return self.args[0].is_even
|
643 |
+
|
644 |
+
def _eval_is_odd(self):
|
645 |
+
if self.args[0].is_extended_real:
|
646 |
+
return self.args[0].is_odd
|
647 |
+
|
648 |
+
def _eval_is_algebraic(self):
|
649 |
+
return self.args[0].is_algebraic
|
650 |
+
|
651 |
+
def _eval_power(self, exponent):
|
652 |
+
if self.args[0].is_extended_real and exponent.is_integer:
|
653 |
+
if exponent.is_even:
|
654 |
+
return self.args[0]**exponent
|
655 |
+
elif exponent is not S.NegativeOne and exponent.is_Integer:
|
656 |
+
return self.args[0]**(exponent - 1)*self
|
657 |
+
return
|
658 |
+
|
659 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
660 |
+
from sympy.functions.elementary.exponential import log
|
661 |
+
direction = self.args[0].leadterm(x)[0]
|
662 |
+
if direction.has(log(x)):
|
663 |
+
direction = direction.subs(log(x), logx)
|
664 |
+
s = self.args[0]._eval_nseries(x, n=n, logx=logx)
|
665 |
+
return (sign(direction)*s).expand()
|
666 |
+
|
667 |
+
def _eval_derivative(self, x):
|
668 |
+
if self.args[0].is_extended_real or self.args[0].is_imaginary:
|
669 |
+
return Derivative(self.args[0], x, evaluate=True) \
|
670 |
+
* sign(conjugate(self.args[0]))
|
671 |
+
rv = (re(self.args[0]) * Derivative(re(self.args[0]), x,
|
672 |
+
evaluate=True) + im(self.args[0]) * Derivative(im(self.args[0]),
|
673 |
+
x, evaluate=True)) / Abs(self.args[0])
|
674 |
+
return rv.rewrite(sign)
|
675 |
+
|
676 |
+
def _eval_rewrite_as_Heaviside(self, arg, **kwargs):
|
677 |
+
# Note this only holds for real arg (since Heaviside is not defined
|
678 |
+
# for complex arguments).
|
679 |
+
from sympy.functions.special.delta_functions import Heaviside
|
680 |
+
if arg.is_extended_real:
|
681 |
+
return arg*(Heaviside(arg) - Heaviside(-arg))
|
682 |
+
|
683 |
+
def _eval_rewrite_as_Piecewise(self, arg, **kwargs):
|
684 |
+
if arg.is_extended_real:
|
685 |
+
return Piecewise((arg, arg >= 0), (-arg, True))
|
686 |
+
elif arg.is_imaginary:
|
687 |
+
return Piecewise((I*arg, I*arg >= 0), (-I*arg, True))
|
688 |
+
|
689 |
+
def _eval_rewrite_as_sign(self, arg, **kwargs):
|
690 |
+
return arg/sign(arg)
|
691 |
+
|
692 |
+
def _eval_rewrite_as_conjugate(self, arg, **kwargs):
|
693 |
+
return sqrt(arg*conjugate(arg))
|
694 |
+
|
695 |
+
|
696 |
+
class arg(Function):
|
697 |
+
r"""
|
698 |
+
Returns the argument (in radians) of a complex number. The argument is
|
699 |
+
evaluated in consistent convention with ``atan2`` where the branch-cut is
|
700 |
+
taken along the negative real axis and ``arg(z)`` is in the interval
|
701 |
+
$(-\pi,\pi]$. For a positive number, the argument is always 0; the
|
702 |
+
argument of a negative number is $\pi$; and the argument of 0
|
703 |
+
is undefined and returns ``nan``. So the ``arg`` function will never nest
|
704 |
+
greater than 3 levels since at the 4th application, the result must be
|
705 |
+
nan; for a real number, nan is returned on the 3rd application.
|
706 |
+
|
707 |
+
Examples
|
708 |
+
========
|
709 |
+
|
710 |
+
>>> from sympy import arg, I, sqrt, Dummy
|
711 |
+
>>> from sympy.abc import x
|
712 |
+
>>> arg(2.0)
|
713 |
+
0
|
714 |
+
>>> arg(I)
|
715 |
+
pi/2
|
716 |
+
>>> arg(sqrt(2) + I*sqrt(2))
|
717 |
+
pi/4
|
718 |
+
>>> arg(sqrt(3)/2 + I/2)
|
719 |
+
pi/6
|
720 |
+
>>> arg(4 + 3*I)
|
721 |
+
atan(3/4)
|
722 |
+
>>> arg(0.8 + 0.6*I)
|
723 |
+
0.643501108793284
|
724 |
+
>>> arg(arg(arg(arg(x))))
|
725 |
+
nan
|
726 |
+
>>> real = Dummy(real=True)
|
727 |
+
>>> arg(arg(arg(real)))
|
728 |
+
nan
|
729 |
+
|
730 |
+
Parameters
|
731 |
+
==========
|
732 |
+
|
733 |
+
arg : Expr
|
734 |
+
Real or complex expression.
|
735 |
+
|
736 |
+
Returns
|
737 |
+
=======
|
738 |
+
|
739 |
+
value : Expr
|
740 |
+
Returns arc tangent of arg measured in radians.
|
741 |
+
|
742 |
+
"""
|
743 |
+
|
744 |
+
is_extended_real = True
|
745 |
+
is_real = True
|
746 |
+
is_finite = True
|
747 |
+
_singularities = True # non-holomorphic
|
748 |
+
|
749 |
+
@classmethod
|
750 |
+
def eval(cls, arg):
|
751 |
+
a = arg
|
752 |
+
for i in range(3):
|
753 |
+
if isinstance(a, cls):
|
754 |
+
a = a.args[0]
|
755 |
+
else:
|
756 |
+
if i == 2 and a.is_extended_real:
|
757 |
+
return S.NaN
|
758 |
+
break
|
759 |
+
else:
|
760 |
+
return S.NaN
|
761 |
+
from sympy.functions.elementary.exponential import exp_polar
|
762 |
+
if isinstance(arg, exp_polar):
|
763 |
+
return periodic_argument(arg, oo)
|
764 |
+
if not arg.is_Atom:
|
765 |
+
c, arg_ = factor_terms(arg).as_coeff_Mul()
|
766 |
+
if arg_.is_Mul:
|
767 |
+
arg_ = Mul(*[a if (sign(a) not in (-1, 1)) else
|
768 |
+
sign(a) for a in arg_.args])
|
769 |
+
arg_ = sign(c)*arg_
|
770 |
+
else:
|
771 |
+
arg_ = arg
|
772 |
+
if any(i.is_extended_positive is None for i in arg_.atoms(AppliedUndef)):
|
773 |
+
return
|
774 |
+
from sympy.functions.elementary.trigonometric import atan2
|
775 |
+
x, y = arg_.as_real_imag()
|
776 |
+
rv = atan2(y, x)
|
777 |
+
if rv.is_number:
|
778 |
+
return rv
|
779 |
+
if arg_ != arg:
|
780 |
+
return cls(arg_, evaluate=False)
|
781 |
+
|
782 |
+
def _eval_derivative(self, t):
|
783 |
+
x, y = self.args[0].as_real_imag()
|
784 |
+
return (x * Derivative(y, t, evaluate=True) - y *
|
785 |
+
Derivative(x, t, evaluate=True)) / (x**2 + y**2)
|
786 |
+
|
787 |
+
def _eval_rewrite_as_atan2(self, arg, **kwargs):
|
788 |
+
from sympy.functions.elementary.trigonometric import atan2
|
789 |
+
x, y = self.args[0].as_real_imag()
|
790 |
+
return atan2(y, x)
|
791 |
+
|
792 |
+
|
793 |
+
class conjugate(Function):
|
794 |
+
"""
|
795 |
+
Returns the *complex conjugate* [1]_ of an argument.
|
796 |
+
In mathematics, the complex conjugate of a complex number
|
797 |
+
is given by changing the sign of the imaginary part.
|
798 |
+
|
799 |
+
Thus, the conjugate of the complex number
|
800 |
+
:math:`a + ib` (where $a$ and $b$ are real numbers) is :math:`a - ib`
|
801 |
+
|
802 |
+
Examples
|
803 |
+
========
|
804 |
+
|
805 |
+
>>> from sympy import conjugate, I
|
806 |
+
>>> conjugate(2)
|
807 |
+
2
|
808 |
+
>>> conjugate(I)
|
809 |
+
-I
|
810 |
+
>>> conjugate(3 + 2*I)
|
811 |
+
3 - 2*I
|
812 |
+
>>> conjugate(5 - I)
|
813 |
+
5 + I
|
814 |
+
|
815 |
+
Parameters
|
816 |
+
==========
|
817 |
+
|
818 |
+
arg : Expr
|
819 |
+
Real or complex expression.
|
820 |
+
|
821 |
+
Returns
|
822 |
+
=======
|
823 |
+
|
824 |
+
arg : Expr
|
825 |
+
Complex conjugate of arg as real, imaginary or mixed expression.
|
826 |
+
|
827 |
+
See Also
|
828 |
+
========
|
829 |
+
|
830 |
+
sign, Abs
|
831 |
+
|
832 |
+
References
|
833 |
+
==========
|
834 |
+
|
835 |
+
.. [1] https://en.wikipedia.org/wiki/Complex_conjugation
|
836 |
+
"""
|
837 |
+
_singularities = True # non-holomorphic
|
838 |
+
|
839 |
+
@classmethod
|
840 |
+
def eval(cls, arg):
|
841 |
+
obj = arg._eval_conjugate()
|
842 |
+
if obj is not None:
|
843 |
+
return obj
|
844 |
+
|
845 |
+
def inverse(self):
|
846 |
+
return conjugate
|
847 |
+
|
848 |
+
def _eval_Abs(self):
|
849 |
+
return Abs(self.args[0], evaluate=True)
|
850 |
+
|
851 |
+
def _eval_adjoint(self):
|
852 |
+
return transpose(self.args[0])
|
853 |
+
|
854 |
+
def _eval_conjugate(self):
|
855 |
+
return self.args[0]
|
856 |
+
|
857 |
+
def _eval_derivative(self, x):
|
858 |
+
if x.is_real:
|
859 |
+
return conjugate(Derivative(self.args[0], x, evaluate=True))
|
860 |
+
elif x.is_imaginary:
|
861 |
+
return -conjugate(Derivative(self.args[0], x, evaluate=True))
|
862 |
+
|
863 |
+
def _eval_transpose(self):
|
864 |
+
return adjoint(self.args[0])
|
865 |
+
|
866 |
+
def _eval_is_algebraic(self):
|
867 |
+
return self.args[0].is_algebraic
|
868 |
+
|
869 |
+
|
870 |
+
class transpose(Function):
|
871 |
+
"""
|
872 |
+
Linear map transposition.
|
873 |
+
|
874 |
+
Examples
|
875 |
+
========
|
876 |
+
|
877 |
+
>>> from sympy import transpose, Matrix, MatrixSymbol
|
878 |
+
>>> A = MatrixSymbol('A', 25, 9)
|
879 |
+
>>> transpose(A)
|
880 |
+
A.T
|
881 |
+
>>> B = MatrixSymbol('B', 9, 22)
|
882 |
+
>>> transpose(B)
|
883 |
+
B.T
|
884 |
+
>>> transpose(A*B)
|
885 |
+
B.T*A.T
|
886 |
+
>>> M = Matrix([[4, 5], [2, 1], [90, 12]])
|
887 |
+
>>> M
|
888 |
+
Matrix([
|
889 |
+
[ 4, 5],
|
890 |
+
[ 2, 1],
|
891 |
+
[90, 12]])
|
892 |
+
>>> transpose(M)
|
893 |
+
Matrix([
|
894 |
+
[4, 2, 90],
|
895 |
+
[5, 1, 12]])
|
896 |
+
|
897 |
+
Parameters
|
898 |
+
==========
|
899 |
+
|
900 |
+
arg : Matrix
|
901 |
+
Matrix or matrix expression to take the transpose of.
|
902 |
+
|
903 |
+
Returns
|
904 |
+
=======
|
905 |
+
|
906 |
+
value : Matrix
|
907 |
+
Transpose of arg.
|
908 |
+
|
909 |
+
"""
|
910 |
+
|
911 |
+
@classmethod
|
912 |
+
def eval(cls, arg):
|
913 |
+
obj = arg._eval_transpose()
|
914 |
+
if obj is not None:
|
915 |
+
return obj
|
916 |
+
|
917 |
+
def _eval_adjoint(self):
|
918 |
+
return conjugate(self.args[0])
|
919 |
+
|
920 |
+
def _eval_conjugate(self):
|
921 |
+
return adjoint(self.args[0])
|
922 |
+
|
923 |
+
def _eval_transpose(self):
|
924 |
+
return self.args[0]
|
925 |
+
|
926 |
+
|
927 |
+
class adjoint(Function):
|
928 |
+
"""
|
929 |
+
Conjugate transpose or Hermite conjugation.
|
930 |
+
|
931 |
+
Examples
|
932 |
+
========
|
933 |
+
|
934 |
+
>>> from sympy import adjoint, MatrixSymbol
|
935 |
+
>>> A = MatrixSymbol('A', 10, 5)
|
936 |
+
>>> adjoint(A)
|
937 |
+
Adjoint(A)
|
938 |
+
|
939 |
+
Parameters
|
940 |
+
==========
|
941 |
+
|
942 |
+
arg : Matrix
|
943 |
+
Matrix or matrix expression to take the adjoint of.
|
944 |
+
|
945 |
+
Returns
|
946 |
+
=======
|
947 |
+
|
948 |
+
value : Matrix
|
949 |
+
Represents the conjugate transpose or Hermite
|
950 |
+
conjugation of arg.
|
951 |
+
|
952 |
+
"""
|
953 |
+
|
954 |
+
@classmethod
|
955 |
+
def eval(cls, arg):
|
956 |
+
obj = arg._eval_adjoint()
|
957 |
+
if obj is not None:
|
958 |
+
return obj
|
959 |
+
obj = arg._eval_transpose()
|
960 |
+
if obj is not None:
|
961 |
+
return conjugate(obj)
|
962 |
+
|
963 |
+
def _eval_adjoint(self):
|
964 |
+
return self.args[0]
|
965 |
+
|
966 |
+
def _eval_conjugate(self):
|
967 |
+
return transpose(self.args[0])
|
968 |
+
|
969 |
+
def _eval_transpose(self):
|
970 |
+
return conjugate(self.args[0])
|
971 |
+
|
972 |
+
def _latex(self, printer, exp=None, *args):
|
973 |
+
arg = printer._print(self.args[0])
|
974 |
+
tex = r'%s^{\dagger}' % arg
|
975 |
+
if exp:
|
976 |
+
tex = r'\left(%s\right)^{%s}' % (tex, exp)
|
977 |
+
return tex
|
978 |
+
|
979 |
+
def _pretty(self, printer, *args):
|
980 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
981 |
+
pform = printer._print(self.args[0], *args)
|
982 |
+
if printer._use_unicode:
|
983 |
+
pform = pform**prettyForm('\N{DAGGER}')
|
984 |
+
else:
|
985 |
+
pform = pform**prettyForm('+')
|
986 |
+
return pform
|
987 |
+
|
988 |
+
###############################################################################
|
989 |
+
############### HANDLING OF POLAR NUMBERS #####################################
|
990 |
+
###############################################################################
|
991 |
+
|
992 |
+
|
993 |
+
class polar_lift(Function):
|
994 |
+
"""
|
995 |
+
Lift argument to the Riemann surface of the logarithm, using the
|
996 |
+
standard branch.
|
997 |
+
|
998 |
+
Examples
|
999 |
+
========
|
1000 |
+
|
1001 |
+
>>> from sympy import Symbol, polar_lift, I
|
1002 |
+
>>> p = Symbol('p', polar=True)
|
1003 |
+
>>> x = Symbol('x')
|
1004 |
+
>>> polar_lift(4)
|
1005 |
+
4*exp_polar(0)
|
1006 |
+
>>> polar_lift(-4)
|
1007 |
+
4*exp_polar(I*pi)
|
1008 |
+
>>> polar_lift(-I)
|
1009 |
+
exp_polar(-I*pi/2)
|
1010 |
+
>>> polar_lift(I + 2)
|
1011 |
+
polar_lift(2 + I)
|
1012 |
+
|
1013 |
+
>>> polar_lift(4*x)
|
1014 |
+
4*polar_lift(x)
|
1015 |
+
>>> polar_lift(4*p)
|
1016 |
+
4*p
|
1017 |
+
|
1018 |
+
Parameters
|
1019 |
+
==========
|
1020 |
+
|
1021 |
+
arg : Expr
|
1022 |
+
Real or complex expression.
|
1023 |
+
|
1024 |
+
See Also
|
1025 |
+
========
|
1026 |
+
|
1027 |
+
sympy.functions.elementary.exponential.exp_polar
|
1028 |
+
periodic_argument
|
1029 |
+
"""
|
1030 |
+
|
1031 |
+
is_polar = True
|
1032 |
+
is_comparable = False # Cannot be evalf'd.
|
1033 |
+
|
1034 |
+
@classmethod
|
1035 |
+
def eval(cls, arg):
|
1036 |
+
from sympy.functions.elementary.complexes import arg as argument
|
1037 |
+
if arg.is_number:
|
1038 |
+
ar = argument(arg)
|
1039 |
+
# In general we want to affirm that something is known,
|
1040 |
+
# e.g. `not ar.has(argument) and not ar.has(atan)`
|
1041 |
+
# but for now we will just be more restrictive and
|
1042 |
+
# see that it has evaluated to one of the known values.
|
1043 |
+
if ar in (0, pi/2, -pi/2, pi):
|
1044 |
+
from sympy.functions.elementary.exponential import exp_polar
|
1045 |
+
return exp_polar(I*ar)*abs(arg)
|
1046 |
+
|
1047 |
+
if arg.is_Mul:
|
1048 |
+
args = arg.args
|
1049 |
+
else:
|
1050 |
+
args = [arg]
|
1051 |
+
included = []
|
1052 |
+
excluded = []
|
1053 |
+
positive = []
|
1054 |
+
for arg in args:
|
1055 |
+
if arg.is_polar:
|
1056 |
+
included += [arg]
|
1057 |
+
elif arg.is_positive:
|
1058 |
+
positive += [arg]
|
1059 |
+
else:
|
1060 |
+
excluded += [arg]
|
1061 |
+
if len(excluded) < len(args):
|
1062 |
+
if excluded:
|
1063 |
+
return Mul(*(included + positive))*polar_lift(Mul(*excluded))
|
1064 |
+
elif included:
|
1065 |
+
return Mul(*(included + positive))
|
1066 |
+
else:
|
1067 |
+
from sympy.functions.elementary.exponential import exp_polar
|
1068 |
+
return Mul(*positive)*exp_polar(0)
|
1069 |
+
|
1070 |
+
def _eval_evalf(self, prec):
|
1071 |
+
""" Careful! any evalf of polar numbers is flaky """
|
1072 |
+
return self.args[0]._eval_evalf(prec)
|
1073 |
+
|
1074 |
+
def _eval_Abs(self):
|
1075 |
+
return Abs(self.args[0], evaluate=True)
|
1076 |
+
|
1077 |
+
|
1078 |
+
class periodic_argument(Function):
|
1079 |
+
r"""
|
1080 |
+
Represent the argument on a quotient of the Riemann surface of the
|
1081 |
+
logarithm. That is, given a period $P$, always return a value in
|
1082 |
+
$(-P/2, P/2]$, by using $\exp(PI) = 1$.
|
1083 |
+
|
1084 |
+
Examples
|
1085 |
+
========
|
1086 |
+
|
1087 |
+
>>> from sympy import exp_polar, periodic_argument
|
1088 |
+
>>> from sympy import I, pi
|
1089 |
+
>>> periodic_argument(exp_polar(10*I*pi), 2*pi)
|
1090 |
+
0
|
1091 |
+
>>> periodic_argument(exp_polar(5*I*pi), 4*pi)
|
1092 |
+
pi
|
1093 |
+
>>> from sympy import exp_polar, periodic_argument
|
1094 |
+
>>> from sympy import I, pi
|
1095 |
+
>>> periodic_argument(exp_polar(5*I*pi), 2*pi)
|
1096 |
+
pi
|
1097 |
+
>>> periodic_argument(exp_polar(5*I*pi), 3*pi)
|
1098 |
+
-pi
|
1099 |
+
>>> periodic_argument(exp_polar(5*I*pi), pi)
|
1100 |
+
0
|
1101 |
+
|
1102 |
+
Parameters
|
1103 |
+
==========
|
1104 |
+
|
1105 |
+
ar : Expr
|
1106 |
+
A polar number.
|
1107 |
+
|
1108 |
+
period : Expr
|
1109 |
+
The period $P$.
|
1110 |
+
|
1111 |
+
See Also
|
1112 |
+
========
|
1113 |
+
|
1114 |
+
sympy.functions.elementary.exponential.exp_polar
|
1115 |
+
polar_lift : Lift argument to the Riemann surface of the logarithm
|
1116 |
+
principal_branch
|
1117 |
+
"""
|
1118 |
+
|
1119 |
+
@classmethod
|
1120 |
+
def _getunbranched(cls, ar):
|
1121 |
+
from sympy.functions.elementary.exponential import exp_polar, log
|
1122 |
+
if ar.is_Mul:
|
1123 |
+
args = ar.args
|
1124 |
+
else:
|
1125 |
+
args = [ar]
|
1126 |
+
unbranched = 0
|
1127 |
+
for a in args:
|
1128 |
+
if not a.is_polar:
|
1129 |
+
unbranched += arg(a)
|
1130 |
+
elif isinstance(a, exp_polar):
|
1131 |
+
unbranched += a.exp.as_real_imag()[1]
|
1132 |
+
elif a.is_Pow:
|
1133 |
+
re, im = a.exp.as_real_imag()
|
1134 |
+
unbranched += re*unbranched_argument(
|
1135 |
+
a.base) + im*log(abs(a.base))
|
1136 |
+
elif isinstance(a, polar_lift):
|
1137 |
+
unbranched += arg(a.args[0])
|
1138 |
+
else:
|
1139 |
+
return None
|
1140 |
+
return unbranched
|
1141 |
+
|
1142 |
+
@classmethod
|
1143 |
+
def eval(cls, ar, period):
|
1144 |
+
# Our strategy is to evaluate the argument on the Riemann surface of the
|
1145 |
+
# logarithm, and then reduce.
|
1146 |
+
# NOTE evidently this means it is a rather bad idea to use this with
|
1147 |
+
# period != 2*pi and non-polar numbers.
|
1148 |
+
if not period.is_extended_positive:
|
1149 |
+
return None
|
1150 |
+
if period == oo and isinstance(ar, principal_branch):
|
1151 |
+
return periodic_argument(*ar.args)
|
1152 |
+
if isinstance(ar, polar_lift) and period >= 2*pi:
|
1153 |
+
return periodic_argument(ar.args[0], period)
|
1154 |
+
if ar.is_Mul:
|
1155 |
+
newargs = [x for x in ar.args if not x.is_positive]
|
1156 |
+
if len(newargs) != len(ar.args):
|
1157 |
+
return periodic_argument(Mul(*newargs), period)
|
1158 |
+
unbranched = cls._getunbranched(ar)
|
1159 |
+
if unbranched is None:
|
1160 |
+
return None
|
1161 |
+
from sympy.functions.elementary.trigonometric import atan, atan2
|
1162 |
+
if unbranched.has(periodic_argument, atan2, atan):
|
1163 |
+
return None
|
1164 |
+
if period == oo:
|
1165 |
+
return unbranched
|
1166 |
+
if period != oo:
|
1167 |
+
from sympy.functions.elementary.integers import ceiling
|
1168 |
+
n = ceiling(unbranched/period - S.Half)*period
|
1169 |
+
if not n.has(ceiling):
|
1170 |
+
return unbranched - n
|
1171 |
+
|
1172 |
+
def _eval_evalf(self, prec):
|
1173 |
+
z, period = self.args
|
1174 |
+
if period == oo:
|
1175 |
+
unbranched = periodic_argument._getunbranched(z)
|
1176 |
+
if unbranched is None:
|
1177 |
+
return self
|
1178 |
+
return unbranched._eval_evalf(prec)
|
1179 |
+
ub = periodic_argument(z, oo)._eval_evalf(prec)
|
1180 |
+
from sympy.functions.elementary.integers import ceiling
|
1181 |
+
return (ub - ceiling(ub/period - S.Half)*period)._eval_evalf(prec)
|
1182 |
+
|
1183 |
+
|
1184 |
+
def unbranched_argument(arg):
|
1185 |
+
'''
|
1186 |
+
Returns periodic argument of arg with period as infinity.
|
1187 |
+
|
1188 |
+
Examples
|
1189 |
+
========
|
1190 |
+
|
1191 |
+
>>> from sympy import exp_polar, unbranched_argument
|
1192 |
+
>>> from sympy import I, pi
|
1193 |
+
>>> unbranched_argument(exp_polar(15*I*pi))
|
1194 |
+
15*pi
|
1195 |
+
>>> unbranched_argument(exp_polar(7*I*pi))
|
1196 |
+
7*pi
|
1197 |
+
|
1198 |
+
See also
|
1199 |
+
========
|
1200 |
+
|
1201 |
+
periodic_argument
|
1202 |
+
'''
|
1203 |
+
return periodic_argument(arg, oo)
|
1204 |
+
|
1205 |
+
|
1206 |
+
class principal_branch(Function):
|
1207 |
+
"""
|
1208 |
+
Represent a polar number reduced to its principal branch on a quotient
|
1209 |
+
of the Riemann surface of the logarithm.
|
1210 |
+
|
1211 |
+
Explanation
|
1212 |
+
===========
|
1213 |
+
|
1214 |
+
This is a function of two arguments. The first argument is a polar
|
1215 |
+
number `z`, and the second one a positive real number or infinity, `p`.
|
1216 |
+
The result is ``z mod exp_polar(I*p)``.
|
1217 |
+
|
1218 |
+
Examples
|
1219 |
+
========
|
1220 |
+
|
1221 |
+
>>> from sympy import exp_polar, principal_branch, oo, I, pi
|
1222 |
+
>>> from sympy.abc import z
|
1223 |
+
>>> principal_branch(z, oo)
|
1224 |
+
z
|
1225 |
+
>>> principal_branch(exp_polar(2*pi*I)*3, 2*pi)
|
1226 |
+
3*exp_polar(0)
|
1227 |
+
>>> principal_branch(exp_polar(2*pi*I)*3*z, 2*pi)
|
1228 |
+
3*principal_branch(z, 2*pi)
|
1229 |
+
|
1230 |
+
Parameters
|
1231 |
+
==========
|
1232 |
+
|
1233 |
+
x : Expr
|
1234 |
+
A polar number.
|
1235 |
+
|
1236 |
+
period : Expr
|
1237 |
+
Positive real number or infinity.
|
1238 |
+
|
1239 |
+
See Also
|
1240 |
+
========
|
1241 |
+
|
1242 |
+
sympy.functions.elementary.exponential.exp_polar
|
1243 |
+
polar_lift : Lift argument to the Riemann surface of the logarithm
|
1244 |
+
periodic_argument
|
1245 |
+
"""
|
1246 |
+
|
1247 |
+
is_polar = True
|
1248 |
+
is_comparable = False # cannot always be evalf'd
|
1249 |
+
|
1250 |
+
@classmethod
|
1251 |
+
def eval(self, x, period):
|
1252 |
+
from sympy.functions.elementary.exponential import exp_polar
|
1253 |
+
if isinstance(x, polar_lift):
|
1254 |
+
return principal_branch(x.args[0], period)
|
1255 |
+
if period == oo:
|
1256 |
+
return x
|
1257 |
+
ub = periodic_argument(x, oo)
|
1258 |
+
barg = periodic_argument(x, period)
|
1259 |
+
if ub != barg and not ub.has(periodic_argument) \
|
1260 |
+
and not barg.has(periodic_argument):
|
1261 |
+
pl = polar_lift(x)
|
1262 |
+
|
1263 |
+
def mr(expr):
|
1264 |
+
if not isinstance(expr, Symbol):
|
1265 |
+
return polar_lift(expr)
|
1266 |
+
return expr
|
1267 |
+
pl = pl.replace(polar_lift, mr)
|
1268 |
+
# Recompute unbranched argument
|
1269 |
+
ub = periodic_argument(pl, oo)
|
1270 |
+
if not pl.has(polar_lift):
|
1271 |
+
if ub != barg:
|
1272 |
+
res = exp_polar(I*(barg - ub))*pl
|
1273 |
+
else:
|
1274 |
+
res = pl
|
1275 |
+
if not res.is_polar and not res.has(exp_polar):
|
1276 |
+
res *= exp_polar(0)
|
1277 |
+
return res
|
1278 |
+
|
1279 |
+
if not x.free_symbols:
|
1280 |
+
c, m = x, ()
|
1281 |
+
else:
|
1282 |
+
c, m = x.as_coeff_mul(*x.free_symbols)
|
1283 |
+
others = []
|
1284 |
+
for y in m:
|
1285 |
+
if y.is_positive:
|
1286 |
+
c *= y
|
1287 |
+
else:
|
1288 |
+
others += [y]
|
1289 |
+
m = tuple(others)
|
1290 |
+
arg = periodic_argument(c, period)
|
1291 |
+
if arg.has(periodic_argument):
|
1292 |
+
return None
|
1293 |
+
if arg.is_number and (unbranched_argument(c) != arg or
|
1294 |
+
(arg == 0 and m != () and c != 1)):
|
1295 |
+
if arg == 0:
|
1296 |
+
return abs(c)*principal_branch(Mul(*m), period)
|
1297 |
+
return principal_branch(exp_polar(I*arg)*Mul(*m), period)*abs(c)
|
1298 |
+
if arg.is_number and ((abs(arg) < period/2) == True or arg == period/2) \
|
1299 |
+
and m == ():
|
1300 |
+
return exp_polar(arg*I)*abs(c)
|
1301 |
+
|
1302 |
+
def _eval_evalf(self, prec):
|
1303 |
+
z, period = self.args
|
1304 |
+
p = periodic_argument(z, period)._eval_evalf(prec)
|
1305 |
+
if abs(p) > pi or p == -pi:
|
1306 |
+
return self # Cannot evalf for this argument.
|
1307 |
+
from sympy.functions.elementary.exponential import exp
|
1308 |
+
return (abs(z)*exp(I*p))._eval_evalf(prec)
|
1309 |
+
|
1310 |
+
|
1311 |
+
def _polarify(eq, lift, pause=False):
|
1312 |
+
from sympy.integrals.integrals import Integral
|
1313 |
+
if eq.is_polar:
|
1314 |
+
return eq
|
1315 |
+
if eq.is_number and not pause:
|
1316 |
+
return polar_lift(eq)
|
1317 |
+
if isinstance(eq, Symbol) and not pause and lift:
|
1318 |
+
return polar_lift(eq)
|
1319 |
+
elif eq.is_Atom:
|
1320 |
+
return eq
|
1321 |
+
elif eq.is_Add:
|
1322 |
+
r = eq.func(*[_polarify(arg, lift, pause=True) for arg in eq.args])
|
1323 |
+
if lift:
|
1324 |
+
return polar_lift(r)
|
1325 |
+
return r
|
1326 |
+
elif eq.is_Pow and eq.base == S.Exp1:
|
1327 |
+
return eq.func(S.Exp1, _polarify(eq.exp, lift, pause=False))
|
1328 |
+
elif eq.is_Function:
|
1329 |
+
return eq.func(*[_polarify(arg, lift, pause=False) for arg in eq.args])
|
1330 |
+
elif isinstance(eq, Integral):
|
1331 |
+
# Don't lift the integration variable
|
1332 |
+
func = _polarify(eq.function, lift, pause=pause)
|
1333 |
+
limits = []
|
1334 |
+
for limit in eq.args[1:]:
|
1335 |
+
var = _polarify(limit[0], lift=False, pause=pause)
|
1336 |
+
rest = _polarify(limit[1:], lift=lift, pause=pause)
|
1337 |
+
limits.append((var,) + rest)
|
1338 |
+
return Integral(*((func,) + tuple(limits)))
|
1339 |
+
else:
|
1340 |
+
return eq.func(*[_polarify(arg, lift, pause=pause)
|
1341 |
+
if isinstance(arg, Expr) else arg for arg in eq.args])
|
1342 |
+
|
1343 |
+
|
1344 |
+
def polarify(eq, subs=True, lift=False):
|
1345 |
+
"""
|
1346 |
+
Turn all numbers in eq into their polar equivalents (under the standard
|
1347 |
+
choice of argument).
|
1348 |
+
|
1349 |
+
Note that no attempt is made to guess a formal convention of adding
|
1350 |
+
polar numbers, expressions like $1 + x$ will generally not be altered.
|
1351 |
+
|
1352 |
+
Note also that this function does not promote ``exp(x)`` to ``exp_polar(x)``.
|
1353 |
+
|
1354 |
+
If ``subs`` is ``True``, all symbols which are not already polar will be
|
1355 |
+
substituted for polar dummies; in this case the function behaves much
|
1356 |
+
like :func:`~.posify`.
|
1357 |
+
|
1358 |
+
If ``lift`` is ``True``, both addition statements and non-polar symbols are
|
1359 |
+
changed to their ``polar_lift()``ed versions.
|
1360 |
+
Note that ``lift=True`` implies ``subs=False``.
|
1361 |
+
|
1362 |
+
Examples
|
1363 |
+
========
|
1364 |
+
|
1365 |
+
>>> from sympy import polarify, sin, I
|
1366 |
+
>>> from sympy.abc import x, y
|
1367 |
+
>>> expr = (-x)**y
|
1368 |
+
>>> expr.expand()
|
1369 |
+
(-x)**y
|
1370 |
+
>>> polarify(expr)
|
1371 |
+
((_x*exp_polar(I*pi))**_y, {_x: x, _y: y})
|
1372 |
+
>>> polarify(expr)[0].expand()
|
1373 |
+
_x**_y*exp_polar(_y*I*pi)
|
1374 |
+
>>> polarify(x, lift=True)
|
1375 |
+
polar_lift(x)
|
1376 |
+
>>> polarify(x*(1+y), lift=True)
|
1377 |
+
polar_lift(x)*polar_lift(y + 1)
|
1378 |
+
|
1379 |
+
Adds are treated carefully:
|
1380 |
+
|
1381 |
+
>>> polarify(1 + sin((1 + I)*x))
|
1382 |
+
(sin(_x*polar_lift(1 + I)) + 1, {_x: x})
|
1383 |
+
"""
|
1384 |
+
if lift:
|
1385 |
+
subs = False
|
1386 |
+
eq = _polarify(sympify(eq), lift)
|
1387 |
+
if not subs:
|
1388 |
+
return eq
|
1389 |
+
reps = {s: Dummy(s.name, polar=True) for s in eq.free_symbols}
|
1390 |
+
eq = eq.subs(reps)
|
1391 |
+
return eq, {r: s for s, r in reps.items()}
|
1392 |
+
|
1393 |
+
|
1394 |
+
def _unpolarify(eq, exponents_only, pause=False):
|
1395 |
+
if not isinstance(eq, Basic) or eq.is_Atom:
|
1396 |
+
return eq
|
1397 |
+
|
1398 |
+
if not pause:
|
1399 |
+
from sympy.functions.elementary.exponential import exp, exp_polar
|
1400 |
+
if isinstance(eq, exp_polar):
|
1401 |
+
return exp(_unpolarify(eq.exp, exponents_only))
|
1402 |
+
if isinstance(eq, principal_branch) and eq.args[1] == 2*pi:
|
1403 |
+
return _unpolarify(eq.args[0], exponents_only)
|
1404 |
+
if (
|
1405 |
+
eq.is_Add or eq.is_Mul or eq.is_Boolean or
|
1406 |
+
eq.is_Relational and (
|
1407 |
+
eq.rel_op in ('==', '!=') and 0 in eq.args or
|
1408 |
+
eq.rel_op not in ('==', '!='))
|
1409 |
+
):
|
1410 |
+
return eq.func(*[_unpolarify(x, exponents_only) for x in eq.args])
|
1411 |
+
if isinstance(eq, polar_lift):
|
1412 |
+
return _unpolarify(eq.args[0], exponents_only)
|
1413 |
+
|
1414 |
+
if eq.is_Pow:
|
1415 |
+
expo = _unpolarify(eq.exp, exponents_only)
|
1416 |
+
base = _unpolarify(eq.base, exponents_only,
|
1417 |
+
not (expo.is_integer and not pause))
|
1418 |
+
return base**expo
|
1419 |
+
|
1420 |
+
if eq.is_Function and getattr(eq.func, 'unbranched', False):
|
1421 |
+
return eq.func(*[_unpolarify(x, exponents_only, exponents_only)
|
1422 |
+
for x in eq.args])
|
1423 |
+
|
1424 |
+
return eq.func(*[_unpolarify(x, exponents_only, True) for x in eq.args])
|
1425 |
+
|
1426 |
+
|
1427 |
+
def unpolarify(eq, subs=None, exponents_only=False):
|
1428 |
+
"""
|
1429 |
+
If `p` denotes the projection from the Riemann surface of the logarithm to
|
1430 |
+
the complex line, return a simplified version `eq'` of `eq` such that
|
1431 |
+
`p(eq') = p(eq)`.
|
1432 |
+
Also apply the substitution subs in the end. (This is a convenience, since
|
1433 |
+
``unpolarify``, in a certain sense, undoes :func:`polarify`.)
|
1434 |
+
|
1435 |
+
Examples
|
1436 |
+
========
|
1437 |
+
|
1438 |
+
>>> from sympy import unpolarify, polar_lift, sin, I
|
1439 |
+
>>> unpolarify(polar_lift(I + 2))
|
1440 |
+
2 + I
|
1441 |
+
>>> unpolarify(sin(polar_lift(I + 7)))
|
1442 |
+
sin(7 + I)
|
1443 |
+
"""
|
1444 |
+
if isinstance(eq, bool):
|
1445 |
+
return eq
|
1446 |
+
|
1447 |
+
eq = sympify(eq)
|
1448 |
+
if subs is not None:
|
1449 |
+
return unpolarify(eq.subs(subs))
|
1450 |
+
changed = True
|
1451 |
+
pause = False
|
1452 |
+
if exponents_only:
|
1453 |
+
pause = True
|
1454 |
+
while changed:
|
1455 |
+
changed = False
|
1456 |
+
res = _unpolarify(eq, exponents_only, pause)
|
1457 |
+
if res != eq:
|
1458 |
+
changed = True
|
1459 |
+
eq = res
|
1460 |
+
if isinstance(res, bool):
|
1461 |
+
return res
|
1462 |
+
# Finally, replacing Exp(0) by 1 is always correct.
|
1463 |
+
# So is polar_lift(0) -> 0.
|
1464 |
+
from sympy.functions.elementary.exponential import exp_polar
|
1465 |
+
return res.subs({exp_polar(0): 1, polar_lift(0): 0})
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/exponential.py
ADDED
@@ -0,0 +1,1291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
from itertools import product
|
2 |
+
from typing import Tuple as tTuple
|
3 |
+
|
4 |
+
from sympy.core.add import Add
|
5 |
+
from sympy.core.cache import cacheit
|
6 |
+
from sympy.core.expr import Expr
|
7 |
+
from sympy.core.function import (Function, ArgumentIndexError, expand_log,
|
8 |
+
expand_mul, FunctionClass, PoleError, expand_multinomial, expand_complex)
|
9 |
+
from sympy.core.logic import fuzzy_and, fuzzy_not, fuzzy_or
|
10 |
+
from sympy.core.mul import Mul
|
11 |
+
from sympy.core.numbers import Integer, Rational, pi, I, ImaginaryUnit
|
12 |
+
from sympy.core.parameters import global_parameters
|
13 |
+
from sympy.core.power import Pow
|
14 |
+
from sympy.core.singleton import S
|
15 |
+
from sympy.core.symbol import Wild, Dummy
|
16 |
+
from sympy.core.sympify import sympify
|
17 |
+
from sympy.functions.combinatorial.factorials import factorial
|
18 |
+
from sympy.functions.elementary.complexes import arg, unpolarify, im, re, Abs
|
19 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
20 |
+
from sympy.ntheory import multiplicity, perfect_power
|
21 |
+
from sympy.ntheory.factor_ import factorint
|
22 |
+
|
23 |
+
# NOTE IMPORTANT
|
24 |
+
# The series expansion code in this file is an important part of the gruntz
|
25 |
+
# algorithm for determining limits. _eval_nseries has to return a generalized
|
26 |
+
# power series with coefficients in C(log(x), log).
|
27 |
+
# In more detail, the result of _eval_nseries(self, x, n) must be
|
28 |
+
# c_0*x**e_0 + ... (finitely many terms)
|
29 |
+
# where e_i are numbers (not necessarily integers) and c_i involve only
|
30 |
+
# numbers, the function log, and log(x). [This also means it must not contain
|
31 |
+
# log(x(1+p)), this *has* to be expanded to log(x)+log(1+p) if x.is_positive and
|
32 |
+
# p.is_positive.]
|
33 |
+
|
34 |
+
|
35 |
+
class ExpBase(Function):
|
36 |
+
|
37 |
+
unbranched = True
|
38 |
+
_singularities = (S.ComplexInfinity,)
|
39 |
+
|
40 |
+
@property
|
41 |
+
def kind(self):
|
42 |
+
return self.exp.kind
|
43 |
+
|
44 |
+
def inverse(self, argindex=1):
|
45 |
+
"""
|
46 |
+
Returns the inverse function of ``exp(x)``.
|
47 |
+
"""
|
48 |
+
return log
|
49 |
+
|
50 |
+
def as_numer_denom(self):
|
51 |
+
"""
|
52 |
+
Returns this with a positive exponent as a 2-tuple (a fraction).
|
53 |
+
|
54 |
+
Examples
|
55 |
+
========
|
56 |
+
|
57 |
+
>>> from sympy import exp
|
58 |
+
>>> from sympy.abc import x
|
59 |
+
>>> exp(-x).as_numer_denom()
|
60 |
+
(1, exp(x))
|
61 |
+
>>> exp(x).as_numer_denom()
|
62 |
+
(exp(x), 1)
|
63 |
+
"""
|
64 |
+
# this should be the same as Pow.as_numer_denom wrt
|
65 |
+
# exponent handling
|
66 |
+
exp = self.exp
|
67 |
+
neg_exp = exp.is_negative
|
68 |
+
if not neg_exp and not (-exp).is_negative:
|
69 |
+
neg_exp = exp.could_extract_minus_sign()
|
70 |
+
if neg_exp:
|
71 |
+
return S.One, self.func(-exp)
|
72 |
+
return self, S.One
|
73 |
+
|
74 |
+
@property
|
75 |
+
def exp(self):
|
76 |
+
"""
|
77 |
+
Returns the exponent of the function.
|
78 |
+
"""
|
79 |
+
return self.args[0]
|
80 |
+
|
81 |
+
def as_base_exp(self):
|
82 |
+
"""
|
83 |
+
Returns the 2-tuple (base, exponent).
|
84 |
+
"""
|
85 |
+
return self.func(1), Mul(*self.args)
|
86 |
+
|
87 |
+
def _eval_adjoint(self):
|
88 |
+
return self.func(self.exp.adjoint())
|
89 |
+
|
90 |
+
def _eval_conjugate(self):
|
91 |
+
return self.func(self.exp.conjugate())
|
92 |
+
|
93 |
+
def _eval_transpose(self):
|
94 |
+
return self.func(self.exp.transpose())
|
95 |
+
|
96 |
+
def _eval_is_finite(self):
|
97 |
+
arg = self.exp
|
98 |
+
if arg.is_infinite:
|
99 |
+
if arg.is_extended_negative:
|
100 |
+
return True
|
101 |
+
if arg.is_extended_positive:
|
102 |
+
return False
|
103 |
+
if arg.is_finite:
|
104 |
+
return True
|
105 |
+
|
106 |
+
def _eval_is_rational(self):
|
107 |
+
s = self.func(*self.args)
|
108 |
+
if s.func == self.func:
|
109 |
+
z = s.exp.is_zero
|
110 |
+
if z:
|
111 |
+
return True
|
112 |
+
elif s.exp.is_rational and fuzzy_not(z):
|
113 |
+
return False
|
114 |
+
else:
|
115 |
+
return s.is_rational
|
116 |
+
|
117 |
+
def _eval_is_zero(self):
|
118 |
+
return self.exp is S.NegativeInfinity
|
119 |
+
|
120 |
+
def _eval_power(self, other):
|
121 |
+
"""exp(arg)**e -> exp(arg*e) if assumptions allow it.
|
122 |
+
"""
|
123 |
+
b, e = self.as_base_exp()
|
124 |
+
return Pow._eval_power(Pow(b, e, evaluate=False), other)
|
125 |
+
|
126 |
+
def _eval_expand_power_exp(self, **hints):
|
127 |
+
from sympy.concrete.products import Product
|
128 |
+
from sympy.concrete.summations import Sum
|
129 |
+
arg = self.args[0]
|
130 |
+
if arg.is_Add and arg.is_commutative:
|
131 |
+
return Mul.fromiter(self.func(x) for x in arg.args)
|
132 |
+
elif isinstance(arg, Sum) and arg.is_commutative:
|
133 |
+
return Product(self.func(arg.function), *arg.limits)
|
134 |
+
return self.func(arg)
|
135 |
+
|
136 |
+
|
137 |
+
class exp_polar(ExpBase):
|
138 |
+
r"""
|
139 |
+
Represent a *polar number* (see g-function Sphinx documentation).
|
140 |
+
|
141 |
+
Explanation
|
142 |
+
===========
|
143 |
+
|
144 |
+
``exp_polar`` represents the function
|
145 |
+
`Exp: \mathbb{C} \rightarrow \mathcal{S}`, sending the complex number
|
146 |
+
`z = a + bi` to the polar number `r = exp(a), \theta = b`. It is one of
|
147 |
+
the main functions to construct polar numbers.
|
148 |
+
|
149 |
+
Examples
|
150 |
+
========
|
151 |
+
|
152 |
+
>>> from sympy import exp_polar, pi, I, exp
|
153 |
+
|
154 |
+
The main difference is that polar numbers do not "wrap around" at `2 \pi`:
|
155 |
+
|
156 |
+
>>> exp(2*pi*I)
|
157 |
+
1
|
158 |
+
>>> exp_polar(2*pi*I)
|
159 |
+
exp_polar(2*I*pi)
|
160 |
+
|
161 |
+
apart from that they behave mostly like classical complex numbers:
|
162 |
+
|
163 |
+
>>> exp_polar(2)*exp_polar(3)
|
164 |
+
exp_polar(5)
|
165 |
+
|
166 |
+
See Also
|
167 |
+
========
|
168 |
+
|
169 |
+
sympy.simplify.powsimp.powsimp
|
170 |
+
polar_lift
|
171 |
+
periodic_argument
|
172 |
+
principal_branch
|
173 |
+
"""
|
174 |
+
|
175 |
+
is_polar = True
|
176 |
+
is_comparable = False # cannot be evalf'd
|
177 |
+
|
178 |
+
def _eval_Abs(self): # Abs is never a polar number
|
179 |
+
return exp(re(self.args[0]))
|
180 |
+
|
181 |
+
def _eval_evalf(self, prec):
|
182 |
+
""" Careful! any evalf of polar numbers is flaky """
|
183 |
+
i = im(self.args[0])
|
184 |
+
try:
|
185 |
+
bad = (i <= -pi or i > pi)
|
186 |
+
except TypeError:
|
187 |
+
bad = True
|
188 |
+
if bad:
|
189 |
+
return self # cannot evalf for this argument
|
190 |
+
res = exp(self.args[0])._eval_evalf(prec)
|
191 |
+
if i > 0 and im(res) < 0:
|
192 |
+
# i ~ pi, but exp(I*i) evaluated to argument slightly bigger than pi
|
193 |
+
return re(res)
|
194 |
+
return res
|
195 |
+
|
196 |
+
def _eval_power(self, other):
|
197 |
+
return self.func(self.args[0]*other)
|
198 |
+
|
199 |
+
def _eval_is_extended_real(self):
|
200 |
+
if self.args[0].is_extended_real:
|
201 |
+
return True
|
202 |
+
|
203 |
+
def as_base_exp(self):
|
204 |
+
# XXX exp_polar(0) is special!
|
205 |
+
if self.args[0] == 0:
|
206 |
+
return self, S.One
|
207 |
+
return ExpBase.as_base_exp(self)
|
208 |
+
|
209 |
+
|
210 |
+
class ExpMeta(FunctionClass):
|
211 |
+
def __instancecheck__(cls, instance):
|
212 |
+
if exp in instance.__class__.__mro__:
|
213 |
+
return True
|
214 |
+
return isinstance(instance, Pow) and instance.base is S.Exp1
|
215 |
+
|
216 |
+
|
217 |
+
class exp(ExpBase, metaclass=ExpMeta):
|
218 |
+
"""
|
219 |
+
The exponential function, :math:`e^x`.
|
220 |
+
|
221 |
+
Examples
|
222 |
+
========
|
223 |
+
|
224 |
+
>>> from sympy import exp, I, pi
|
225 |
+
>>> from sympy.abc import x
|
226 |
+
>>> exp(x)
|
227 |
+
exp(x)
|
228 |
+
>>> exp(x).diff(x)
|
229 |
+
exp(x)
|
230 |
+
>>> exp(I*pi)
|
231 |
+
-1
|
232 |
+
|
233 |
+
Parameters
|
234 |
+
==========
|
235 |
+
|
236 |
+
arg : Expr
|
237 |
+
|
238 |
+
See Also
|
239 |
+
========
|
240 |
+
|
241 |
+
log
|
242 |
+
"""
|
243 |
+
|
244 |
+
def fdiff(self, argindex=1):
|
245 |
+
"""
|
246 |
+
Returns the first derivative of this function.
|
247 |
+
"""
|
248 |
+
if argindex == 1:
|
249 |
+
return self
|
250 |
+
else:
|
251 |
+
raise ArgumentIndexError(self, argindex)
|
252 |
+
|
253 |
+
def _eval_refine(self, assumptions):
|
254 |
+
from sympy.assumptions import ask, Q
|
255 |
+
arg = self.args[0]
|
256 |
+
if arg.is_Mul:
|
257 |
+
Ioo = I*S.Infinity
|
258 |
+
if arg in [Ioo, -Ioo]:
|
259 |
+
return S.NaN
|
260 |
+
|
261 |
+
coeff = arg.as_coefficient(pi*I)
|
262 |
+
if coeff:
|
263 |
+
if ask(Q.integer(2*coeff)):
|
264 |
+
if ask(Q.even(coeff)):
|
265 |
+
return S.One
|
266 |
+
elif ask(Q.odd(coeff)):
|
267 |
+
return S.NegativeOne
|
268 |
+
elif ask(Q.even(coeff + S.Half)):
|
269 |
+
return -I
|
270 |
+
elif ask(Q.odd(coeff + S.Half)):
|
271 |
+
return I
|
272 |
+
|
273 |
+
@classmethod
|
274 |
+
def eval(cls, arg):
|
275 |
+
from sympy.calculus import AccumBounds
|
276 |
+
from sympy.matrices.matrices import MatrixBase
|
277 |
+
from sympy.sets.setexpr import SetExpr
|
278 |
+
from sympy.simplify.simplify import logcombine
|
279 |
+
if isinstance(arg, MatrixBase):
|
280 |
+
return arg.exp()
|
281 |
+
elif global_parameters.exp_is_pow:
|
282 |
+
return Pow(S.Exp1, arg)
|
283 |
+
elif arg.is_Number:
|
284 |
+
if arg is S.NaN:
|
285 |
+
return S.NaN
|
286 |
+
elif arg.is_zero:
|
287 |
+
return S.One
|
288 |
+
elif arg is S.One:
|
289 |
+
return S.Exp1
|
290 |
+
elif arg is S.Infinity:
|
291 |
+
return S.Infinity
|
292 |
+
elif arg is S.NegativeInfinity:
|
293 |
+
return S.Zero
|
294 |
+
elif arg is S.ComplexInfinity:
|
295 |
+
return S.NaN
|
296 |
+
elif isinstance(arg, log):
|
297 |
+
return arg.args[0]
|
298 |
+
elif isinstance(arg, AccumBounds):
|
299 |
+
return AccumBounds(exp(arg.min), exp(arg.max))
|
300 |
+
elif isinstance(arg, SetExpr):
|
301 |
+
return arg._eval_func(cls)
|
302 |
+
elif arg.is_Mul:
|
303 |
+
coeff = arg.as_coefficient(pi*I)
|
304 |
+
if coeff:
|
305 |
+
if (2*coeff).is_integer:
|
306 |
+
if coeff.is_even:
|
307 |
+
return S.One
|
308 |
+
elif coeff.is_odd:
|
309 |
+
return S.NegativeOne
|
310 |
+
elif (coeff + S.Half).is_even:
|
311 |
+
return -I
|
312 |
+
elif (coeff + S.Half).is_odd:
|
313 |
+
return I
|
314 |
+
elif coeff.is_Rational:
|
315 |
+
ncoeff = coeff % 2 # restrict to [0, 2pi)
|
316 |
+
if ncoeff > 1: # restrict to (-pi, pi]
|
317 |
+
ncoeff -= 2
|
318 |
+
if ncoeff != coeff:
|
319 |
+
return cls(ncoeff*pi*I)
|
320 |
+
|
321 |
+
# Warning: code in risch.py will be very sensitive to changes
|
322 |
+
# in this (see DifferentialExtension).
|
323 |
+
|
324 |
+
# look for a single log factor
|
325 |
+
|
326 |
+
coeff, terms = arg.as_coeff_Mul()
|
327 |
+
|
328 |
+
# but it can't be multiplied by oo
|
329 |
+
if coeff in [S.NegativeInfinity, S.Infinity]:
|
330 |
+
if terms.is_number:
|
331 |
+
if coeff is S.NegativeInfinity:
|
332 |
+
terms = -terms
|
333 |
+
if re(terms).is_zero and terms is not S.Zero:
|
334 |
+
return S.NaN
|
335 |
+
if re(terms).is_positive and im(terms) is not S.Zero:
|
336 |
+
return S.ComplexInfinity
|
337 |
+
if re(terms).is_negative:
|
338 |
+
return S.Zero
|
339 |
+
return None
|
340 |
+
|
341 |
+
coeffs, log_term = [coeff], None
|
342 |
+
for term in Mul.make_args(terms):
|
343 |
+
term_ = logcombine(term)
|
344 |
+
if isinstance(term_, log):
|
345 |
+
if log_term is None:
|
346 |
+
log_term = term_.args[0]
|
347 |
+
else:
|
348 |
+
return None
|
349 |
+
elif term.is_comparable:
|
350 |
+
coeffs.append(term)
|
351 |
+
else:
|
352 |
+
return None
|
353 |
+
|
354 |
+
return log_term**Mul(*coeffs) if log_term else None
|
355 |
+
|
356 |
+
elif arg.is_Add:
|
357 |
+
out = []
|
358 |
+
add = []
|
359 |
+
argchanged = False
|
360 |
+
for a in arg.args:
|
361 |
+
if a is S.One:
|
362 |
+
add.append(a)
|
363 |
+
continue
|
364 |
+
newa = cls(a)
|
365 |
+
if isinstance(newa, cls):
|
366 |
+
if newa.args[0] != a:
|
367 |
+
add.append(newa.args[0])
|
368 |
+
argchanged = True
|
369 |
+
else:
|
370 |
+
add.append(a)
|
371 |
+
else:
|
372 |
+
out.append(newa)
|
373 |
+
if out or argchanged:
|
374 |
+
return Mul(*out)*cls(Add(*add), evaluate=False)
|
375 |
+
|
376 |
+
if arg.is_zero:
|
377 |
+
return S.One
|
378 |
+
|
379 |
+
@property
|
380 |
+
def base(self):
|
381 |
+
"""
|
382 |
+
Returns the base of the exponential function.
|
383 |
+
"""
|
384 |
+
return S.Exp1
|
385 |
+
|
386 |
+
@staticmethod
|
387 |
+
@cacheit
|
388 |
+
def taylor_term(n, x, *previous_terms):
|
389 |
+
"""
|
390 |
+
Calculates the next term in the Taylor series expansion.
|
391 |
+
"""
|
392 |
+
if n < 0:
|
393 |
+
return S.Zero
|
394 |
+
if n == 0:
|
395 |
+
return S.One
|
396 |
+
x = sympify(x)
|
397 |
+
if previous_terms:
|
398 |
+
p = previous_terms[-1]
|
399 |
+
if p is not None:
|
400 |
+
return p * x / n
|
401 |
+
return x**n/factorial(n)
|
402 |
+
|
403 |
+
def as_real_imag(self, deep=True, **hints):
|
404 |
+
"""
|
405 |
+
Returns this function as a 2-tuple representing a complex number.
|
406 |
+
|
407 |
+
Examples
|
408 |
+
========
|
409 |
+
|
410 |
+
>>> from sympy import exp, I
|
411 |
+
>>> from sympy.abc import x
|
412 |
+
>>> exp(x).as_real_imag()
|
413 |
+
(exp(re(x))*cos(im(x)), exp(re(x))*sin(im(x)))
|
414 |
+
>>> exp(1).as_real_imag()
|
415 |
+
(E, 0)
|
416 |
+
>>> exp(I).as_real_imag()
|
417 |
+
(cos(1), sin(1))
|
418 |
+
>>> exp(1+I).as_real_imag()
|
419 |
+
(E*cos(1), E*sin(1))
|
420 |
+
|
421 |
+
See Also
|
422 |
+
========
|
423 |
+
|
424 |
+
sympy.functions.elementary.complexes.re
|
425 |
+
sympy.functions.elementary.complexes.im
|
426 |
+
"""
|
427 |
+
from sympy.functions.elementary.trigonometric import cos, sin
|
428 |
+
re, im = self.args[0].as_real_imag()
|
429 |
+
if deep:
|
430 |
+
re = re.expand(deep, **hints)
|
431 |
+
im = im.expand(deep, **hints)
|
432 |
+
cos, sin = cos(im), sin(im)
|
433 |
+
return (exp(re)*cos, exp(re)*sin)
|
434 |
+
|
435 |
+
def _eval_subs(self, old, new):
|
436 |
+
# keep processing of power-like args centralized in Pow
|
437 |
+
if old.is_Pow: # handle (exp(3*log(x))).subs(x**2, z) -> z**(3/2)
|
438 |
+
old = exp(old.exp*log(old.base))
|
439 |
+
elif old is S.Exp1 and new.is_Function:
|
440 |
+
old = exp
|
441 |
+
if isinstance(old, exp) or old is S.Exp1:
|
442 |
+
f = lambda a: Pow(*a.as_base_exp(), evaluate=False) if (
|
443 |
+
a.is_Pow or isinstance(a, exp)) else a
|
444 |
+
return Pow._eval_subs(f(self), f(old), new)
|
445 |
+
|
446 |
+
if old is exp and not new.is_Function:
|
447 |
+
return new**self.exp._subs(old, new)
|
448 |
+
return Function._eval_subs(self, old, new)
|
449 |
+
|
450 |
+
def _eval_is_extended_real(self):
|
451 |
+
if self.args[0].is_extended_real:
|
452 |
+
return True
|
453 |
+
elif self.args[0].is_imaginary:
|
454 |
+
arg2 = -S(2) * I * self.args[0] / pi
|
455 |
+
return arg2.is_even
|
456 |
+
|
457 |
+
def _eval_is_complex(self):
|
458 |
+
def complex_extended_negative(arg):
|
459 |
+
yield arg.is_complex
|
460 |
+
yield arg.is_extended_negative
|
461 |
+
return fuzzy_or(complex_extended_negative(self.args[0]))
|
462 |
+
|
463 |
+
def _eval_is_algebraic(self):
|
464 |
+
if (self.exp / pi / I).is_rational:
|
465 |
+
return True
|
466 |
+
if fuzzy_not(self.exp.is_zero):
|
467 |
+
if self.exp.is_algebraic:
|
468 |
+
return False
|
469 |
+
elif (self.exp / pi).is_rational:
|
470 |
+
return False
|
471 |
+
|
472 |
+
def _eval_is_extended_positive(self):
|
473 |
+
if self.exp.is_extended_real:
|
474 |
+
return self.args[0] is not S.NegativeInfinity
|
475 |
+
elif self.exp.is_imaginary:
|
476 |
+
arg2 = -I * self.args[0] / pi
|
477 |
+
return arg2.is_even
|
478 |
+
|
479 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
480 |
+
# NOTE Please see the comment at the beginning of this file, labelled
|
481 |
+
# IMPORTANT.
|
482 |
+
from sympy.functions.elementary.complexes import sign
|
483 |
+
from sympy.functions.elementary.integers import ceiling
|
484 |
+
from sympy.series.limits import limit
|
485 |
+
from sympy.series.order import Order
|
486 |
+
from sympy.simplify.powsimp import powsimp
|
487 |
+
arg = self.exp
|
488 |
+
arg_series = arg._eval_nseries(x, n=n, logx=logx)
|
489 |
+
if arg_series.is_Order:
|
490 |
+
return 1 + arg_series
|
491 |
+
arg0 = limit(arg_series.removeO(), x, 0)
|
492 |
+
if arg0 is S.NegativeInfinity:
|
493 |
+
return Order(x**n, x)
|
494 |
+
if arg0 is S.Infinity:
|
495 |
+
return self
|
496 |
+
# checking for indecisiveness/ sign terms in arg0
|
497 |
+
if any(isinstance(arg, (sign, ImaginaryUnit)) for arg in arg0.args):
|
498 |
+
return self
|
499 |
+
t = Dummy("t")
|
500 |
+
nterms = n
|
501 |
+
try:
|
502 |
+
cf = Order(arg.as_leading_term(x, logx=logx), x).getn()
|
503 |
+
except (NotImplementedError, PoleError):
|
504 |
+
cf = 0
|
505 |
+
if cf and cf > 0:
|
506 |
+
nterms = ceiling(n/cf)
|
507 |
+
exp_series = exp(t)._taylor(t, nterms)
|
508 |
+
r = exp(arg0)*exp_series.subs(t, arg_series - arg0)
|
509 |
+
rep = {logx: log(x)} if logx is not None else {}
|
510 |
+
if r.subs(rep) == self:
|
511 |
+
return r
|
512 |
+
if cf and cf > 1:
|
513 |
+
r += Order((arg_series - arg0)**n, x)/x**((cf-1)*n)
|
514 |
+
else:
|
515 |
+
r += Order((arg_series - arg0)**n, x)
|
516 |
+
r = r.expand()
|
517 |
+
r = powsimp(r, deep=True, combine='exp')
|
518 |
+
# powsimp may introduce unexpanded (-1)**Rational; see PR #17201
|
519 |
+
simplerat = lambda x: x.is_Rational and x.q in [3, 4, 6]
|
520 |
+
w = Wild('w', properties=[simplerat])
|
521 |
+
r = r.replace(S.NegativeOne**w, expand_complex(S.NegativeOne**w))
|
522 |
+
return r
|
523 |
+
|
524 |
+
def _taylor(self, x, n):
|
525 |
+
l = []
|
526 |
+
g = None
|
527 |
+
for i in range(n):
|
528 |
+
g = self.taylor_term(i, self.args[0], g)
|
529 |
+
g = g.nseries(x, n=n)
|
530 |
+
l.append(g.removeO())
|
531 |
+
return Add(*l)
|
532 |
+
|
533 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
534 |
+
from sympy.calculus.util import AccumBounds
|
535 |
+
arg = self.args[0].cancel().as_leading_term(x, logx=logx)
|
536 |
+
arg0 = arg.subs(x, 0)
|
537 |
+
if arg is S.NaN:
|
538 |
+
return S.NaN
|
539 |
+
if isinstance(arg0, AccumBounds):
|
540 |
+
# This check addresses a corner case involving AccumBounds.
|
541 |
+
# if isinstance(arg, AccumBounds) is True, then arg0 can either be 0,
|
542 |
+
# AccumBounds(-oo, 0) or AccumBounds(-oo, oo).
|
543 |
+
# Check out function: test_issue_18473() in test_exponential.py and
|
544 |
+
# test_limits.py for more information.
|
545 |
+
if re(cdir) < S.Zero:
|
546 |
+
return exp(-arg0)
|
547 |
+
return exp(arg0)
|
548 |
+
if arg0 is S.NaN:
|
549 |
+
arg0 = arg.limit(x, 0)
|
550 |
+
if arg0.is_infinite is False:
|
551 |
+
return exp(arg0)
|
552 |
+
raise PoleError("Cannot expand %s around 0" % (self))
|
553 |
+
|
554 |
+
def _eval_rewrite_as_sin(self, arg, **kwargs):
|
555 |
+
from sympy.functions.elementary.trigonometric import sin
|
556 |
+
return sin(I*arg + pi/2) - I*sin(I*arg)
|
557 |
+
|
558 |
+
def _eval_rewrite_as_cos(self, arg, **kwargs):
|
559 |
+
from sympy.functions.elementary.trigonometric import cos
|
560 |
+
return cos(I*arg) + I*cos(I*arg + pi/2)
|
561 |
+
|
562 |
+
def _eval_rewrite_as_tanh(self, arg, **kwargs):
|
563 |
+
from sympy.functions.elementary.hyperbolic import tanh
|
564 |
+
return (1 + tanh(arg/2))/(1 - tanh(arg/2))
|
565 |
+
|
566 |
+
def _eval_rewrite_as_sqrt(self, arg, **kwargs):
|
567 |
+
from sympy.functions.elementary.trigonometric import sin, cos
|
568 |
+
if arg.is_Mul:
|
569 |
+
coeff = arg.coeff(pi*I)
|
570 |
+
if coeff and coeff.is_number:
|
571 |
+
cosine, sine = cos(pi*coeff), sin(pi*coeff)
|
572 |
+
if not isinstance(cosine, cos) and not isinstance (sine, sin):
|
573 |
+
return cosine + I*sine
|
574 |
+
|
575 |
+
def _eval_rewrite_as_Pow(self, arg, **kwargs):
|
576 |
+
if arg.is_Mul:
|
577 |
+
logs = [a for a in arg.args if isinstance(a, log) and len(a.args) == 1]
|
578 |
+
if logs:
|
579 |
+
return Pow(logs[0].args[0], arg.coeff(logs[0]))
|
580 |
+
|
581 |
+
|
582 |
+
def match_real_imag(expr):
|
583 |
+
r"""
|
584 |
+
Try to match expr with $a + Ib$ for real $a$ and $b$.
|
585 |
+
|
586 |
+
``match_real_imag`` returns a tuple containing the real and imaginary
|
587 |
+
parts of expr or ``(None, None)`` if direct matching is not possible. Contrary
|
588 |
+
to :func:`~.re()`, :func:`~.im()``, and ``as_real_imag()``, this helper will not force things
|
589 |
+
by returning expressions themselves containing ``re()`` or ``im()`` and it
|
590 |
+
does not expand its argument either.
|
591 |
+
|
592 |
+
"""
|
593 |
+
r_, i_ = expr.as_independent(I, as_Add=True)
|
594 |
+
if i_ == 0 and r_.is_real:
|
595 |
+
return (r_, i_)
|
596 |
+
i_ = i_.as_coefficient(I)
|
597 |
+
if i_ and i_.is_real and r_.is_real:
|
598 |
+
return (r_, i_)
|
599 |
+
else:
|
600 |
+
return (None, None) # simpler to check for than None
|
601 |
+
|
602 |
+
|
603 |
+
class log(Function):
|
604 |
+
r"""
|
605 |
+
The natural logarithm function `\ln(x)` or `\log(x)`.
|
606 |
+
|
607 |
+
Explanation
|
608 |
+
===========
|
609 |
+
|
610 |
+
Logarithms are taken with the natural base, `e`. To get
|
611 |
+
a logarithm of a different base ``b``, use ``log(x, b)``,
|
612 |
+
which is essentially short-hand for ``log(x)/log(b)``.
|
613 |
+
|
614 |
+
``log`` represents the principal branch of the natural
|
615 |
+
logarithm. As such it has a branch cut along the negative
|
616 |
+
real axis and returns values having a complex argument in
|
617 |
+
`(-\pi, \pi]`.
|
618 |
+
|
619 |
+
Examples
|
620 |
+
========
|
621 |
+
|
622 |
+
>>> from sympy import log, sqrt, S, I
|
623 |
+
>>> log(8, 2)
|
624 |
+
3
|
625 |
+
>>> log(S(8)/3, 2)
|
626 |
+
-log(3)/log(2) + 3
|
627 |
+
>>> log(-1 + I*sqrt(3))
|
628 |
+
log(2) + 2*I*pi/3
|
629 |
+
|
630 |
+
See Also
|
631 |
+
========
|
632 |
+
|
633 |
+
exp
|
634 |
+
|
635 |
+
"""
|
636 |
+
|
637 |
+
args: tTuple[Expr]
|
638 |
+
|
639 |
+
_singularities = (S.Zero, S.ComplexInfinity)
|
640 |
+
|
641 |
+
def fdiff(self, argindex=1):
|
642 |
+
"""
|
643 |
+
Returns the first derivative of the function.
|
644 |
+
"""
|
645 |
+
if argindex == 1:
|
646 |
+
return 1/self.args[0]
|
647 |
+
else:
|
648 |
+
raise ArgumentIndexError(self, argindex)
|
649 |
+
|
650 |
+
def inverse(self, argindex=1):
|
651 |
+
r"""
|
652 |
+
Returns `e^x`, the inverse function of `\log(x)`.
|
653 |
+
"""
|
654 |
+
return exp
|
655 |
+
|
656 |
+
@classmethod
|
657 |
+
def eval(cls, arg, base=None):
|
658 |
+
from sympy.calculus import AccumBounds
|
659 |
+
from sympy.sets.setexpr import SetExpr
|
660 |
+
|
661 |
+
arg = sympify(arg)
|
662 |
+
|
663 |
+
if base is not None:
|
664 |
+
base = sympify(base)
|
665 |
+
if base == 1:
|
666 |
+
if arg == 1:
|
667 |
+
return S.NaN
|
668 |
+
else:
|
669 |
+
return S.ComplexInfinity
|
670 |
+
try:
|
671 |
+
# handle extraction of powers of the base now
|
672 |
+
# or else expand_log in Mul would have to handle this
|
673 |
+
n = multiplicity(base, arg)
|
674 |
+
if n:
|
675 |
+
return n + log(arg / base**n) / log(base)
|
676 |
+
else:
|
677 |
+
return log(arg)/log(base)
|
678 |
+
except ValueError:
|
679 |
+
pass
|
680 |
+
if base is not S.Exp1:
|
681 |
+
return cls(arg)/cls(base)
|
682 |
+
else:
|
683 |
+
return cls(arg)
|
684 |
+
|
685 |
+
if arg.is_Number:
|
686 |
+
if arg.is_zero:
|
687 |
+
return S.ComplexInfinity
|
688 |
+
elif arg is S.One:
|
689 |
+
return S.Zero
|
690 |
+
elif arg is S.Infinity:
|
691 |
+
return S.Infinity
|
692 |
+
elif arg is S.NegativeInfinity:
|
693 |
+
return S.Infinity
|
694 |
+
elif arg is S.NaN:
|
695 |
+
return S.NaN
|
696 |
+
elif arg.is_Rational and arg.p == 1:
|
697 |
+
return -cls(arg.q)
|
698 |
+
|
699 |
+
if arg.is_Pow and arg.base is S.Exp1 and arg.exp.is_extended_real:
|
700 |
+
return arg.exp
|
701 |
+
if isinstance(arg, exp) and arg.exp.is_extended_real:
|
702 |
+
return arg.exp
|
703 |
+
elif isinstance(arg, exp) and arg.exp.is_number:
|
704 |
+
r_, i_ = match_real_imag(arg.exp)
|
705 |
+
if i_ and i_.is_comparable:
|
706 |
+
i_ %= 2*pi
|
707 |
+
if i_ > pi:
|
708 |
+
i_ -= 2*pi
|
709 |
+
return r_ + expand_mul(i_ * I, deep=False)
|
710 |
+
elif isinstance(arg, exp_polar):
|
711 |
+
return unpolarify(arg.exp)
|
712 |
+
elif isinstance(arg, AccumBounds):
|
713 |
+
if arg.min.is_positive:
|
714 |
+
return AccumBounds(log(arg.min), log(arg.max))
|
715 |
+
elif arg.min.is_zero:
|
716 |
+
return AccumBounds(S.NegativeInfinity, log(arg.max))
|
717 |
+
else:
|
718 |
+
return S.NaN
|
719 |
+
elif isinstance(arg, SetExpr):
|
720 |
+
return arg._eval_func(cls)
|
721 |
+
|
722 |
+
if arg.is_number:
|
723 |
+
if arg.is_negative:
|
724 |
+
return pi * I + cls(-arg)
|
725 |
+
elif arg is S.ComplexInfinity:
|
726 |
+
return S.ComplexInfinity
|
727 |
+
elif arg is S.Exp1:
|
728 |
+
return S.One
|
729 |
+
|
730 |
+
if arg.is_zero:
|
731 |
+
return S.ComplexInfinity
|
732 |
+
|
733 |
+
# don't autoexpand Pow or Mul (see the issue 3351):
|
734 |
+
if not arg.is_Add:
|
735 |
+
coeff = arg.as_coefficient(I)
|
736 |
+
|
737 |
+
if coeff is not None:
|
738 |
+
if coeff is S.Infinity:
|
739 |
+
return S.Infinity
|
740 |
+
elif coeff is S.NegativeInfinity:
|
741 |
+
return S.Infinity
|
742 |
+
elif coeff.is_Rational:
|
743 |
+
if coeff.is_nonnegative:
|
744 |
+
return pi * I * S.Half + cls(coeff)
|
745 |
+
else:
|
746 |
+
return -pi * I * S.Half + cls(-coeff)
|
747 |
+
|
748 |
+
if arg.is_number and arg.is_algebraic:
|
749 |
+
# Match arg = coeff*(r_ + i_*I) with coeff>0, r_ and i_ real.
|
750 |
+
coeff, arg_ = arg.as_independent(I, as_Add=False)
|
751 |
+
if coeff.is_negative:
|
752 |
+
coeff *= -1
|
753 |
+
arg_ *= -1
|
754 |
+
arg_ = expand_mul(arg_, deep=False)
|
755 |
+
r_, i_ = arg_.as_independent(I, as_Add=True)
|
756 |
+
i_ = i_.as_coefficient(I)
|
757 |
+
if coeff.is_real and i_ and i_.is_real and r_.is_real:
|
758 |
+
if r_.is_zero:
|
759 |
+
if i_.is_positive:
|
760 |
+
return pi * I * S.Half + cls(coeff * i_)
|
761 |
+
elif i_.is_negative:
|
762 |
+
return -pi * I * S.Half + cls(coeff * -i_)
|
763 |
+
else:
|
764 |
+
from sympy.simplify import ratsimp
|
765 |
+
# Check for arguments involving rational multiples of pi
|
766 |
+
t = (i_/r_).cancel()
|
767 |
+
t1 = (-t).cancel()
|
768 |
+
atan_table = _log_atan_table()
|
769 |
+
if t in atan_table:
|
770 |
+
modulus = ratsimp(coeff * Abs(arg_))
|
771 |
+
if r_.is_positive:
|
772 |
+
return cls(modulus) + I * atan_table[t]
|
773 |
+
else:
|
774 |
+
return cls(modulus) + I * (atan_table[t] - pi)
|
775 |
+
elif t1 in atan_table:
|
776 |
+
modulus = ratsimp(coeff * Abs(arg_))
|
777 |
+
if r_.is_positive:
|
778 |
+
return cls(modulus) + I * (-atan_table[t1])
|
779 |
+
else:
|
780 |
+
return cls(modulus) + I * (pi - atan_table[t1])
|
781 |
+
|
782 |
+
def as_base_exp(self):
|
783 |
+
"""
|
784 |
+
Returns this function in the form (base, exponent).
|
785 |
+
"""
|
786 |
+
return self, S.One
|
787 |
+
|
788 |
+
@staticmethod
|
789 |
+
@cacheit
|
790 |
+
def taylor_term(n, x, *previous_terms): # of log(1+x)
|
791 |
+
r"""
|
792 |
+
Returns the next term in the Taylor series expansion of `\log(1+x)`.
|
793 |
+
"""
|
794 |
+
from sympy.simplify.powsimp import powsimp
|
795 |
+
if n < 0:
|
796 |
+
return S.Zero
|
797 |
+
x = sympify(x)
|
798 |
+
if n == 0:
|
799 |
+
return x
|
800 |
+
if previous_terms:
|
801 |
+
p = previous_terms[-1]
|
802 |
+
if p is not None:
|
803 |
+
return powsimp((-n) * p * x / (n + 1), deep=True, combine='exp')
|
804 |
+
return (1 - 2*(n % 2)) * x**(n + 1)/(n + 1)
|
805 |
+
|
806 |
+
def _eval_expand_log(self, deep=True, **hints):
|
807 |
+
from sympy.concrete import Sum, Product
|
808 |
+
force = hints.get('force', False)
|
809 |
+
factor = hints.get('factor', False)
|
810 |
+
if (len(self.args) == 2):
|
811 |
+
return expand_log(self.func(*self.args), deep=deep, force=force)
|
812 |
+
arg = self.args[0]
|
813 |
+
if arg.is_Integer:
|
814 |
+
# remove perfect powers
|
815 |
+
p = perfect_power(arg)
|
816 |
+
logarg = None
|
817 |
+
coeff = 1
|
818 |
+
if p is not False:
|
819 |
+
arg, coeff = p
|
820 |
+
logarg = self.func(arg)
|
821 |
+
# expand as product of its prime factors if factor=True
|
822 |
+
if factor:
|
823 |
+
p = factorint(arg)
|
824 |
+
if arg not in p.keys():
|
825 |
+
logarg = sum(n*log(val) for val, n in p.items())
|
826 |
+
if logarg is not None:
|
827 |
+
return coeff*logarg
|
828 |
+
elif arg.is_Rational:
|
829 |
+
return log(arg.p) - log(arg.q)
|
830 |
+
elif arg.is_Mul:
|
831 |
+
expr = []
|
832 |
+
nonpos = []
|
833 |
+
for x in arg.args:
|
834 |
+
if force or x.is_positive or x.is_polar:
|
835 |
+
a = self.func(x)
|
836 |
+
if isinstance(a, log):
|
837 |
+
expr.append(self.func(x)._eval_expand_log(**hints))
|
838 |
+
else:
|
839 |
+
expr.append(a)
|
840 |
+
elif x.is_negative:
|
841 |
+
a = self.func(-x)
|
842 |
+
expr.append(a)
|
843 |
+
nonpos.append(S.NegativeOne)
|
844 |
+
else:
|
845 |
+
nonpos.append(x)
|
846 |
+
return Add(*expr) + log(Mul(*nonpos))
|
847 |
+
elif arg.is_Pow or isinstance(arg, exp):
|
848 |
+
if force or (arg.exp.is_extended_real and (arg.base.is_positive or ((arg.exp+1)
|
849 |
+
.is_positive and (arg.exp-1).is_nonpositive))) or arg.base.is_polar:
|
850 |
+
b = arg.base
|
851 |
+
e = arg.exp
|
852 |
+
a = self.func(b)
|
853 |
+
if isinstance(a, log):
|
854 |
+
return unpolarify(e) * a._eval_expand_log(**hints)
|
855 |
+
else:
|
856 |
+
return unpolarify(e) * a
|
857 |
+
elif isinstance(arg, Product):
|
858 |
+
if force or arg.function.is_positive:
|
859 |
+
return Sum(log(arg.function), *arg.limits)
|
860 |
+
|
861 |
+
return self.func(arg)
|
862 |
+
|
863 |
+
def _eval_simplify(self, **kwargs):
|
864 |
+
from sympy.simplify.simplify import expand_log, simplify, inversecombine
|
865 |
+
if len(self.args) == 2: # it's unevaluated
|
866 |
+
return simplify(self.func(*self.args), **kwargs)
|
867 |
+
|
868 |
+
expr = self.func(simplify(self.args[0], **kwargs))
|
869 |
+
if kwargs['inverse']:
|
870 |
+
expr = inversecombine(expr)
|
871 |
+
expr = expand_log(expr, deep=True)
|
872 |
+
return min([expr, self], key=kwargs['measure'])
|
873 |
+
|
874 |
+
def as_real_imag(self, deep=True, **hints):
|
875 |
+
"""
|
876 |
+
Returns this function as a complex coordinate.
|
877 |
+
|
878 |
+
Examples
|
879 |
+
========
|
880 |
+
|
881 |
+
>>> from sympy import I, log
|
882 |
+
>>> from sympy.abc import x
|
883 |
+
>>> log(x).as_real_imag()
|
884 |
+
(log(Abs(x)), arg(x))
|
885 |
+
>>> log(I).as_real_imag()
|
886 |
+
(0, pi/2)
|
887 |
+
>>> log(1 + I).as_real_imag()
|
888 |
+
(log(sqrt(2)), pi/4)
|
889 |
+
>>> log(I*x).as_real_imag()
|
890 |
+
(log(Abs(x)), arg(I*x))
|
891 |
+
|
892 |
+
"""
|
893 |
+
sarg = self.args[0]
|
894 |
+
if deep:
|
895 |
+
sarg = self.args[0].expand(deep, **hints)
|
896 |
+
sarg_abs = Abs(sarg)
|
897 |
+
if sarg_abs == sarg:
|
898 |
+
return self, S.Zero
|
899 |
+
sarg_arg = arg(sarg)
|
900 |
+
if hints.get('log', False): # Expand the log
|
901 |
+
hints['complex'] = False
|
902 |
+
return (log(sarg_abs).expand(deep, **hints), sarg_arg)
|
903 |
+
else:
|
904 |
+
return log(sarg_abs), sarg_arg
|
905 |
+
|
906 |
+
def _eval_is_rational(self):
|
907 |
+
s = self.func(*self.args)
|
908 |
+
if s.func == self.func:
|
909 |
+
if (self.args[0] - 1).is_zero:
|
910 |
+
return True
|
911 |
+
if s.args[0].is_rational and fuzzy_not((self.args[0] - 1).is_zero):
|
912 |
+
return False
|
913 |
+
else:
|
914 |
+
return s.is_rational
|
915 |
+
|
916 |
+
def _eval_is_algebraic(self):
|
917 |
+
s = self.func(*self.args)
|
918 |
+
if s.func == self.func:
|
919 |
+
if (self.args[0] - 1).is_zero:
|
920 |
+
return True
|
921 |
+
elif fuzzy_not((self.args[0] - 1).is_zero):
|
922 |
+
if self.args[0].is_algebraic:
|
923 |
+
return False
|
924 |
+
else:
|
925 |
+
return s.is_algebraic
|
926 |
+
|
927 |
+
def _eval_is_extended_real(self):
|
928 |
+
return self.args[0].is_extended_positive
|
929 |
+
|
930 |
+
def _eval_is_complex(self):
|
931 |
+
z = self.args[0]
|
932 |
+
return fuzzy_and([z.is_complex, fuzzy_not(z.is_zero)])
|
933 |
+
|
934 |
+
def _eval_is_finite(self):
|
935 |
+
arg = self.args[0]
|
936 |
+
if arg.is_zero:
|
937 |
+
return False
|
938 |
+
return arg.is_finite
|
939 |
+
|
940 |
+
def _eval_is_extended_positive(self):
|
941 |
+
return (self.args[0] - 1).is_extended_positive
|
942 |
+
|
943 |
+
def _eval_is_zero(self):
|
944 |
+
return (self.args[0] - 1).is_zero
|
945 |
+
|
946 |
+
def _eval_is_extended_nonnegative(self):
|
947 |
+
return (self.args[0] - 1).is_extended_nonnegative
|
948 |
+
|
949 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
950 |
+
# NOTE Please see the comment at the beginning of this file, labelled
|
951 |
+
# IMPORTANT.
|
952 |
+
from sympy.series.order import Order
|
953 |
+
from sympy.simplify.simplify import logcombine
|
954 |
+
from sympy.core.symbol import Dummy
|
955 |
+
|
956 |
+
if self.args[0] == x:
|
957 |
+
return log(x) if logx is None else logx
|
958 |
+
arg = self.args[0]
|
959 |
+
t = Dummy('t', positive=True)
|
960 |
+
if cdir == 0:
|
961 |
+
cdir = 1
|
962 |
+
z = arg.subs(x, cdir*t)
|
963 |
+
|
964 |
+
k, l = Wild("k"), Wild("l")
|
965 |
+
r = z.match(k*t**l)
|
966 |
+
if r is not None:
|
967 |
+
k, l = r[k], r[l]
|
968 |
+
if l != 0 and not l.has(t) and not k.has(t):
|
969 |
+
r = l*log(x) if logx is None else l*logx
|
970 |
+
r += log(k) - l*log(cdir) # XXX true regardless of assumptions?
|
971 |
+
return r
|
972 |
+
|
973 |
+
def coeff_exp(term, x):
|
974 |
+
coeff, exp = S.One, S.Zero
|
975 |
+
for factor in Mul.make_args(term):
|
976 |
+
if factor.has(x):
|
977 |
+
base, exp = factor.as_base_exp()
|
978 |
+
if base != x:
|
979 |
+
try:
|
980 |
+
return term.leadterm(x)
|
981 |
+
except ValueError:
|
982 |
+
return term, S.Zero
|
983 |
+
else:
|
984 |
+
coeff *= factor
|
985 |
+
return coeff, exp
|
986 |
+
|
987 |
+
# TODO new and probably slow
|
988 |
+
try:
|
989 |
+
a, b = z.leadterm(t, logx=logx, cdir=1)
|
990 |
+
except (ValueError, NotImplementedError, PoleError):
|
991 |
+
s = z._eval_nseries(t, n=n, logx=logx, cdir=1)
|
992 |
+
while s.is_Order:
|
993 |
+
n += 1
|
994 |
+
s = z._eval_nseries(t, n=n, logx=logx, cdir=1)
|
995 |
+
try:
|
996 |
+
a, b = s.removeO().leadterm(t, cdir=1)
|
997 |
+
except ValueError:
|
998 |
+
a, b = s.removeO().as_leading_term(t, cdir=1), S.Zero
|
999 |
+
|
1000 |
+
p = (z/(a*t**b) - 1)._eval_nseries(t, n=n, logx=logx, cdir=1)
|
1001 |
+
if p.has(exp):
|
1002 |
+
p = logcombine(p)
|
1003 |
+
if isinstance(p, Order):
|
1004 |
+
n = p.getn()
|
1005 |
+
_, d = coeff_exp(p, t)
|
1006 |
+
logx = log(x) if logx is None else logx
|
1007 |
+
|
1008 |
+
if not d.is_positive:
|
1009 |
+
res = log(a) - b*log(cdir) + b*logx
|
1010 |
+
_res = res
|
1011 |
+
logflags = {"deep": True, "log": True, "mul": False, "power_exp": False,
|
1012 |
+
"power_base": False, "multinomial": False, "basic": False, "force": True,
|
1013 |
+
"factor": False}
|
1014 |
+
expr = self.expand(**logflags)
|
1015 |
+
if (not a.could_extract_minus_sign() and
|
1016 |
+
logx.could_extract_minus_sign()):
|
1017 |
+
_res = _res.subs(-logx, -log(x)).expand(**logflags)
|
1018 |
+
else:
|
1019 |
+
_res = _res.subs(logx, log(x)).expand(**logflags)
|
1020 |
+
if _res == expr:
|
1021 |
+
return res
|
1022 |
+
return res + Order(x**n, x)
|
1023 |
+
|
1024 |
+
def mul(d1, d2):
|
1025 |
+
res = {}
|
1026 |
+
for e1, e2 in product(d1, d2):
|
1027 |
+
ex = e1 + e2
|
1028 |
+
if ex < n:
|
1029 |
+
res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
|
1030 |
+
return res
|
1031 |
+
|
1032 |
+
pterms = {}
|
1033 |
+
|
1034 |
+
for term in Add.make_args(p.removeO()):
|
1035 |
+
co1, e1 = coeff_exp(term, t)
|
1036 |
+
pterms[e1] = pterms.get(e1, S.Zero) + co1
|
1037 |
+
|
1038 |
+
k = S.One
|
1039 |
+
terms = {}
|
1040 |
+
pk = pterms
|
1041 |
+
|
1042 |
+
while k*d < n:
|
1043 |
+
coeff = -S.NegativeOne**k/k
|
1044 |
+
for ex in pk:
|
1045 |
+
_ = terms.get(ex, S.Zero) + coeff*pk[ex]
|
1046 |
+
terms[ex] = _.nsimplify()
|
1047 |
+
pk = mul(pk, pterms)
|
1048 |
+
k += S.One
|
1049 |
+
|
1050 |
+
res = log(a) - b*log(cdir) + b*logx
|
1051 |
+
for ex in terms:
|
1052 |
+
res += terms[ex]*t**(ex)
|
1053 |
+
|
1054 |
+
if a.is_negative and im(z) != 0:
|
1055 |
+
from sympy.functions.special.delta_functions import Heaviside
|
1056 |
+
for i, term in enumerate(z.lseries(t)):
|
1057 |
+
if not term.is_real or i == 5:
|
1058 |
+
break
|
1059 |
+
if i < 5:
|
1060 |
+
coeff, _ = term.as_coeff_exponent(t)
|
1061 |
+
res += -2*I*pi*Heaviside(-im(coeff), 0)
|
1062 |
+
|
1063 |
+
res = res.subs(t, x/cdir)
|
1064 |
+
return res + Order(x**n, x)
|
1065 |
+
|
1066 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
1067 |
+
# NOTE
|
1068 |
+
# Refer https://github.com/sympy/sympy/pull/23592 for more information
|
1069 |
+
# on each of the following steps involved in this method.
|
1070 |
+
arg0 = self.args[0].together()
|
1071 |
+
|
1072 |
+
# STEP 1
|
1073 |
+
t = Dummy('t', positive=True)
|
1074 |
+
if cdir == 0:
|
1075 |
+
cdir = 1
|
1076 |
+
z = arg0.subs(x, cdir*t)
|
1077 |
+
|
1078 |
+
# STEP 2
|
1079 |
+
try:
|
1080 |
+
c, e = z.leadterm(t, logx=logx, cdir=1)
|
1081 |
+
except ValueError:
|
1082 |
+
arg = arg0.as_leading_term(x, logx=logx, cdir=cdir)
|
1083 |
+
return log(arg)
|
1084 |
+
if c.has(t):
|
1085 |
+
c = c.subs(t, x/cdir)
|
1086 |
+
if e != 0:
|
1087 |
+
raise PoleError("Cannot expand %s around 0" % (self))
|
1088 |
+
return log(c)
|
1089 |
+
|
1090 |
+
# STEP 3
|
1091 |
+
if c == S.One and e == S.Zero:
|
1092 |
+
return (arg0 - S.One).as_leading_term(x, logx=logx)
|
1093 |
+
|
1094 |
+
# STEP 4
|
1095 |
+
res = log(c) - e*log(cdir)
|
1096 |
+
logx = log(x) if logx is None else logx
|
1097 |
+
res += e*logx
|
1098 |
+
|
1099 |
+
# STEP 5
|
1100 |
+
if c.is_negative and im(z) != 0:
|
1101 |
+
from sympy.functions.special.delta_functions import Heaviside
|
1102 |
+
for i, term in enumerate(z.lseries(t)):
|
1103 |
+
if not term.is_real or i == 5:
|
1104 |
+
break
|
1105 |
+
if i < 5:
|
1106 |
+
coeff, _ = term.as_coeff_exponent(t)
|
1107 |
+
res += -2*I*pi*Heaviside(-im(coeff), 0)
|
1108 |
+
return res
|
1109 |
+
|
1110 |
+
|
1111 |
+
class LambertW(Function):
|
1112 |
+
r"""
|
1113 |
+
The Lambert W function $W(z)$ is defined as the inverse
|
1114 |
+
function of $w \exp(w)$ [1]_.
|
1115 |
+
|
1116 |
+
Explanation
|
1117 |
+
===========
|
1118 |
+
|
1119 |
+
In other words, the value of $W(z)$ is such that $z = W(z) \exp(W(z))$
|
1120 |
+
for any complex number $z$. The Lambert W function is a multivalued
|
1121 |
+
function with infinitely many branches $W_k(z)$, indexed by
|
1122 |
+
$k \in \mathbb{Z}$. Each branch gives a different solution $w$
|
1123 |
+
of the equation $z = w \exp(w)$.
|
1124 |
+
|
1125 |
+
The Lambert W function has two partially real branches: the
|
1126 |
+
principal branch ($k = 0$) is real for real $z > -1/e$, and the
|
1127 |
+
$k = -1$ branch is real for $-1/e < z < 0$. All branches except
|
1128 |
+
$k = 0$ have a logarithmic singularity at $z = 0$.
|
1129 |
+
|
1130 |
+
Examples
|
1131 |
+
========
|
1132 |
+
|
1133 |
+
>>> from sympy import LambertW
|
1134 |
+
>>> LambertW(1.2)
|
1135 |
+
0.635564016364870
|
1136 |
+
>>> LambertW(1.2, -1).n()
|
1137 |
+
-1.34747534407696 - 4.41624341514535*I
|
1138 |
+
>>> LambertW(-1).is_real
|
1139 |
+
False
|
1140 |
+
|
1141 |
+
References
|
1142 |
+
==========
|
1143 |
+
|
1144 |
+
.. [1] https://en.wikipedia.org/wiki/Lambert_W_function
|
1145 |
+
"""
|
1146 |
+
_singularities = (-Pow(S.Exp1, -1, evaluate=False), S.ComplexInfinity)
|
1147 |
+
|
1148 |
+
@classmethod
|
1149 |
+
def eval(cls, x, k=None):
|
1150 |
+
if k == S.Zero:
|
1151 |
+
return cls(x)
|
1152 |
+
elif k is None:
|
1153 |
+
k = S.Zero
|
1154 |
+
|
1155 |
+
if k.is_zero:
|
1156 |
+
if x.is_zero:
|
1157 |
+
return S.Zero
|
1158 |
+
if x is S.Exp1:
|
1159 |
+
return S.One
|
1160 |
+
if x == -1/S.Exp1:
|
1161 |
+
return S.NegativeOne
|
1162 |
+
if x == -log(2)/2:
|
1163 |
+
return -log(2)
|
1164 |
+
if x == 2*log(2):
|
1165 |
+
return log(2)
|
1166 |
+
if x == -pi/2:
|
1167 |
+
return I*pi/2
|
1168 |
+
if x == exp(1 + S.Exp1):
|
1169 |
+
return S.Exp1
|
1170 |
+
if x is S.Infinity:
|
1171 |
+
return S.Infinity
|
1172 |
+
if x.is_zero:
|
1173 |
+
return S.Zero
|
1174 |
+
|
1175 |
+
if fuzzy_not(k.is_zero):
|
1176 |
+
if x.is_zero:
|
1177 |
+
return S.NegativeInfinity
|
1178 |
+
if k is S.NegativeOne:
|
1179 |
+
if x == -pi/2:
|
1180 |
+
return -I*pi/2
|
1181 |
+
elif x == -1/S.Exp1:
|
1182 |
+
return S.NegativeOne
|
1183 |
+
elif x == -2*exp(-2):
|
1184 |
+
return -Integer(2)
|
1185 |
+
|
1186 |
+
def fdiff(self, argindex=1):
|
1187 |
+
"""
|
1188 |
+
Return the first derivative of this function.
|
1189 |
+
"""
|
1190 |
+
x = self.args[0]
|
1191 |
+
|
1192 |
+
if len(self.args) == 1:
|
1193 |
+
if argindex == 1:
|
1194 |
+
return LambertW(x)/(x*(1 + LambertW(x)))
|
1195 |
+
else:
|
1196 |
+
k = self.args[1]
|
1197 |
+
if argindex == 1:
|
1198 |
+
return LambertW(x, k)/(x*(1 + LambertW(x, k)))
|
1199 |
+
|
1200 |
+
raise ArgumentIndexError(self, argindex)
|
1201 |
+
|
1202 |
+
def _eval_is_extended_real(self):
|
1203 |
+
x = self.args[0]
|
1204 |
+
if len(self.args) == 1:
|
1205 |
+
k = S.Zero
|
1206 |
+
else:
|
1207 |
+
k = self.args[1]
|
1208 |
+
if k.is_zero:
|
1209 |
+
if (x + 1/S.Exp1).is_positive:
|
1210 |
+
return True
|
1211 |
+
elif (x + 1/S.Exp1).is_nonpositive:
|
1212 |
+
return False
|
1213 |
+
elif (k + 1).is_zero:
|
1214 |
+
if x.is_negative and (x + 1/S.Exp1).is_positive:
|
1215 |
+
return True
|
1216 |
+
elif x.is_nonpositive or (x + 1/S.Exp1).is_nonnegative:
|
1217 |
+
return False
|
1218 |
+
elif fuzzy_not(k.is_zero) and fuzzy_not((k + 1).is_zero):
|
1219 |
+
if x.is_extended_real:
|
1220 |
+
return False
|
1221 |
+
|
1222 |
+
def _eval_is_finite(self):
|
1223 |
+
return self.args[0].is_finite
|
1224 |
+
|
1225 |
+
def _eval_is_algebraic(self):
|
1226 |
+
s = self.func(*self.args)
|
1227 |
+
if s.func == self.func:
|
1228 |
+
if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic:
|
1229 |
+
return False
|
1230 |
+
else:
|
1231 |
+
return s.is_algebraic
|
1232 |
+
|
1233 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
1234 |
+
if len(self.args) == 1:
|
1235 |
+
arg = self.args[0]
|
1236 |
+
arg0 = arg.subs(x, 0).cancel()
|
1237 |
+
if not arg0.is_zero:
|
1238 |
+
return self.func(arg0)
|
1239 |
+
return arg.as_leading_term(x)
|
1240 |
+
|
1241 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
1242 |
+
if len(self.args) == 1:
|
1243 |
+
from sympy.functions.elementary.integers import ceiling
|
1244 |
+
from sympy.series.order import Order
|
1245 |
+
arg = self.args[0].nseries(x, n=n, logx=logx)
|
1246 |
+
lt = arg.as_leading_term(x, logx=logx)
|
1247 |
+
lte = 1
|
1248 |
+
if lt.is_Pow:
|
1249 |
+
lte = lt.exp
|
1250 |
+
if ceiling(n/lte) >= 1:
|
1251 |
+
s = Add(*[(-S.One)**(k - 1)*Integer(k)**(k - 2)/
|
1252 |
+
factorial(k - 1)*arg**k for k in range(1, ceiling(n/lte))])
|
1253 |
+
s = expand_multinomial(s)
|
1254 |
+
else:
|
1255 |
+
s = S.Zero
|
1256 |
+
|
1257 |
+
return s + Order(x**n, x)
|
1258 |
+
return super()._eval_nseries(x, n, logx)
|
1259 |
+
|
1260 |
+
def _eval_is_zero(self):
|
1261 |
+
x = self.args[0]
|
1262 |
+
if len(self.args) == 1:
|
1263 |
+
return x.is_zero
|
1264 |
+
else:
|
1265 |
+
return fuzzy_and([x.is_zero, self.args[1].is_zero])
|
1266 |
+
|
1267 |
+
|
1268 |
+
@cacheit
|
1269 |
+
def _log_atan_table():
|
1270 |
+
return {
|
1271 |
+
# first quadrant only
|
1272 |
+
sqrt(3): pi / 3,
|
1273 |
+
1: pi / 4,
|
1274 |
+
sqrt(5 - 2 * sqrt(5)): pi / 5,
|
1275 |
+
sqrt(2) * sqrt(5 - sqrt(5)) / (1 + sqrt(5)): pi / 5,
|
1276 |
+
sqrt(5 + 2 * sqrt(5)): pi * Rational(2, 5),
|
1277 |
+
sqrt(2) * sqrt(sqrt(5) + 5) / (-1 + sqrt(5)): pi * Rational(2, 5),
|
1278 |
+
sqrt(3) / 3: pi / 6,
|
1279 |
+
sqrt(2) - 1: pi / 8,
|
1280 |
+
sqrt(2 - sqrt(2)) / sqrt(sqrt(2) + 2): pi / 8,
|
1281 |
+
sqrt(2) + 1: pi * Rational(3, 8),
|
1282 |
+
sqrt(sqrt(2) + 2) / sqrt(2 - sqrt(2)): pi * Rational(3, 8),
|
1283 |
+
sqrt(1 - 2 * sqrt(5) / 5): pi / 10,
|
1284 |
+
(-sqrt(2) + sqrt(10)) / (2 * sqrt(sqrt(5) + 5)): pi / 10,
|
1285 |
+
sqrt(1 + 2 * sqrt(5) / 5): pi * Rational(3, 10),
|
1286 |
+
(sqrt(2) + sqrt(10)) / (2 * sqrt(5 - sqrt(5))): pi * Rational(3, 10),
|
1287 |
+
2 - sqrt(3): pi / 12,
|
1288 |
+
(-1 + sqrt(3)) / (1 + sqrt(3)): pi / 12,
|
1289 |
+
2 + sqrt(3): pi * Rational(5, 12),
|
1290 |
+
(1 + sqrt(3)) / (-1 + sqrt(3)): pi * Rational(5, 12)
|
1291 |
+
}
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/hyperbolic.py
ADDED
@@ -0,0 +1,2203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import S, sympify, cacheit
|
2 |
+
from sympy.core.add import Add
|
3 |
+
from sympy.core.function import Function, ArgumentIndexError
|
4 |
+
from sympy.core.logic import fuzzy_or, fuzzy_and, FuzzyBool
|
5 |
+
from sympy.core.numbers import I, pi, Rational
|
6 |
+
from sympy.core.symbol import Dummy
|
7 |
+
from sympy.functions.combinatorial.factorials import (binomial, factorial,
|
8 |
+
RisingFactorial)
|
9 |
+
from sympy.functions.combinatorial.numbers import bernoulli, euler, nC
|
10 |
+
from sympy.functions.elementary.complexes import Abs, im, re
|
11 |
+
from sympy.functions.elementary.exponential import exp, log, match_real_imag
|
12 |
+
from sympy.functions.elementary.integers import floor
|
13 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
14 |
+
from sympy.functions.elementary.trigonometric import (
|
15 |
+
acos, acot, asin, atan, cos, cot, csc, sec, sin, tan,
|
16 |
+
_imaginary_unit_as_coefficient)
|
17 |
+
from sympy.polys.specialpolys import symmetric_poly
|
18 |
+
|
19 |
+
|
20 |
+
def _rewrite_hyperbolics_as_exp(expr):
|
21 |
+
return expr.xreplace({h: h.rewrite(exp)
|
22 |
+
for h in expr.atoms(HyperbolicFunction)})
|
23 |
+
|
24 |
+
|
25 |
+
@cacheit
|
26 |
+
def _acosh_table():
|
27 |
+
return {
|
28 |
+
I: log(I*(1 + sqrt(2))),
|
29 |
+
-I: log(-I*(1 + sqrt(2))),
|
30 |
+
S.Half: pi/3,
|
31 |
+
Rational(-1, 2): pi*Rational(2, 3),
|
32 |
+
sqrt(2)/2: pi/4,
|
33 |
+
-sqrt(2)/2: pi*Rational(3, 4),
|
34 |
+
1/sqrt(2): pi/4,
|
35 |
+
-1/sqrt(2): pi*Rational(3, 4),
|
36 |
+
sqrt(3)/2: pi/6,
|
37 |
+
-sqrt(3)/2: pi*Rational(5, 6),
|
38 |
+
(sqrt(3) - 1)/sqrt(2**3): pi*Rational(5, 12),
|
39 |
+
-(sqrt(3) - 1)/sqrt(2**3): pi*Rational(7, 12),
|
40 |
+
sqrt(2 + sqrt(2))/2: pi/8,
|
41 |
+
-sqrt(2 + sqrt(2))/2: pi*Rational(7, 8),
|
42 |
+
sqrt(2 - sqrt(2))/2: pi*Rational(3, 8),
|
43 |
+
-sqrt(2 - sqrt(2))/2: pi*Rational(5, 8),
|
44 |
+
(1 + sqrt(3))/(2*sqrt(2)): pi/12,
|
45 |
+
-(1 + sqrt(3))/(2*sqrt(2)): pi*Rational(11, 12),
|
46 |
+
(sqrt(5) + 1)/4: pi/5,
|
47 |
+
-(sqrt(5) + 1)/4: pi*Rational(4, 5)
|
48 |
+
}
|
49 |
+
|
50 |
+
|
51 |
+
@cacheit
|
52 |
+
def _acsch_table():
|
53 |
+
return {
|
54 |
+
I: -pi / 2,
|
55 |
+
I*(sqrt(2) + sqrt(6)): -pi / 12,
|
56 |
+
I*(1 + sqrt(5)): -pi / 10,
|
57 |
+
I*2 / sqrt(2 - sqrt(2)): -pi / 8,
|
58 |
+
I*2: -pi / 6,
|
59 |
+
I*sqrt(2 + 2/sqrt(5)): -pi / 5,
|
60 |
+
I*sqrt(2): -pi / 4,
|
61 |
+
I*(sqrt(5)-1): -3*pi / 10,
|
62 |
+
I*2 / sqrt(3): -pi / 3,
|
63 |
+
I*2 / sqrt(2 + sqrt(2)): -3*pi / 8,
|
64 |
+
I*sqrt(2 - 2/sqrt(5)): -2*pi / 5,
|
65 |
+
I*(sqrt(6) - sqrt(2)): -5*pi / 12,
|
66 |
+
S(2): -I*log((1+sqrt(5))/2),
|
67 |
+
}
|
68 |
+
|
69 |
+
|
70 |
+
@cacheit
|
71 |
+
def _asech_table():
|
72 |
+
return {
|
73 |
+
I: - (pi*I / 2) + log(1 + sqrt(2)),
|
74 |
+
-I: (pi*I / 2) + log(1 + sqrt(2)),
|
75 |
+
(sqrt(6) - sqrt(2)): pi / 12,
|
76 |
+
(sqrt(2) - sqrt(6)): 11*pi / 12,
|
77 |
+
sqrt(2 - 2/sqrt(5)): pi / 10,
|
78 |
+
-sqrt(2 - 2/sqrt(5)): 9*pi / 10,
|
79 |
+
2 / sqrt(2 + sqrt(2)): pi / 8,
|
80 |
+
-2 / sqrt(2 + sqrt(2)): 7*pi / 8,
|
81 |
+
2 / sqrt(3): pi / 6,
|
82 |
+
-2 / sqrt(3): 5*pi / 6,
|
83 |
+
(sqrt(5) - 1): pi / 5,
|
84 |
+
(1 - sqrt(5)): 4*pi / 5,
|
85 |
+
sqrt(2): pi / 4,
|
86 |
+
-sqrt(2): 3*pi / 4,
|
87 |
+
sqrt(2 + 2/sqrt(5)): 3*pi / 10,
|
88 |
+
-sqrt(2 + 2/sqrt(5)): 7*pi / 10,
|
89 |
+
S(2): pi / 3,
|
90 |
+
-S(2): 2*pi / 3,
|
91 |
+
sqrt(2*(2 + sqrt(2))): 3*pi / 8,
|
92 |
+
-sqrt(2*(2 + sqrt(2))): 5*pi / 8,
|
93 |
+
(1 + sqrt(5)): 2*pi / 5,
|
94 |
+
(-1 - sqrt(5)): 3*pi / 5,
|
95 |
+
(sqrt(6) + sqrt(2)): 5*pi / 12,
|
96 |
+
(-sqrt(6) - sqrt(2)): 7*pi / 12,
|
97 |
+
I*S.Infinity: -pi*I / 2,
|
98 |
+
I*S.NegativeInfinity: pi*I / 2,
|
99 |
+
}
|
100 |
+
|
101 |
+
###############################################################################
|
102 |
+
########################### HYPERBOLIC FUNCTIONS ##############################
|
103 |
+
###############################################################################
|
104 |
+
|
105 |
+
|
106 |
+
class HyperbolicFunction(Function):
|
107 |
+
"""
|
108 |
+
Base class for hyperbolic functions.
|
109 |
+
|
110 |
+
See Also
|
111 |
+
========
|
112 |
+
|
113 |
+
sinh, cosh, tanh, coth
|
114 |
+
"""
|
115 |
+
|
116 |
+
unbranched = True
|
117 |
+
|
118 |
+
|
119 |
+
def _peeloff_ipi(arg):
|
120 |
+
r"""
|
121 |
+
Split ARG into two parts, a "rest" and a multiple of $I\pi$.
|
122 |
+
This assumes ARG to be an ``Add``.
|
123 |
+
The multiple of $I\pi$ returned in the second position is always a ``Rational``.
|
124 |
+
|
125 |
+
Examples
|
126 |
+
========
|
127 |
+
|
128 |
+
>>> from sympy.functions.elementary.hyperbolic import _peeloff_ipi as peel
|
129 |
+
>>> from sympy import pi, I
|
130 |
+
>>> from sympy.abc import x, y
|
131 |
+
>>> peel(x + I*pi/2)
|
132 |
+
(x, 1/2)
|
133 |
+
>>> peel(x + I*2*pi/3 + I*pi*y)
|
134 |
+
(x + I*pi*y + I*pi/6, 1/2)
|
135 |
+
"""
|
136 |
+
ipi = pi*I
|
137 |
+
for a in Add.make_args(arg):
|
138 |
+
if a == ipi:
|
139 |
+
K = S.One
|
140 |
+
break
|
141 |
+
elif a.is_Mul:
|
142 |
+
K, p = a.as_two_terms()
|
143 |
+
if p == ipi and K.is_Rational:
|
144 |
+
break
|
145 |
+
else:
|
146 |
+
return arg, S.Zero
|
147 |
+
|
148 |
+
m1 = (K % S.Half)
|
149 |
+
m2 = K - m1
|
150 |
+
return arg - m2*ipi, m2
|
151 |
+
|
152 |
+
|
153 |
+
class sinh(HyperbolicFunction):
|
154 |
+
r"""
|
155 |
+
``sinh(x)`` is the hyperbolic sine of ``x``.
|
156 |
+
|
157 |
+
The hyperbolic sine function is $\frac{e^x - e^{-x}}{2}$.
|
158 |
+
|
159 |
+
Examples
|
160 |
+
========
|
161 |
+
|
162 |
+
>>> from sympy import sinh
|
163 |
+
>>> from sympy.abc import x
|
164 |
+
>>> sinh(x)
|
165 |
+
sinh(x)
|
166 |
+
|
167 |
+
See Also
|
168 |
+
========
|
169 |
+
|
170 |
+
cosh, tanh, asinh
|
171 |
+
"""
|
172 |
+
|
173 |
+
def fdiff(self, argindex=1):
|
174 |
+
"""
|
175 |
+
Returns the first derivative of this function.
|
176 |
+
"""
|
177 |
+
if argindex == 1:
|
178 |
+
return cosh(self.args[0])
|
179 |
+
else:
|
180 |
+
raise ArgumentIndexError(self, argindex)
|
181 |
+
|
182 |
+
def inverse(self, argindex=1):
|
183 |
+
"""
|
184 |
+
Returns the inverse of this function.
|
185 |
+
"""
|
186 |
+
return asinh
|
187 |
+
|
188 |
+
@classmethod
|
189 |
+
def eval(cls, arg):
|
190 |
+
if arg.is_Number:
|
191 |
+
if arg is S.NaN:
|
192 |
+
return S.NaN
|
193 |
+
elif arg is S.Infinity:
|
194 |
+
return S.Infinity
|
195 |
+
elif arg is S.NegativeInfinity:
|
196 |
+
return S.NegativeInfinity
|
197 |
+
elif arg.is_zero:
|
198 |
+
return S.Zero
|
199 |
+
elif arg.is_negative:
|
200 |
+
return -cls(-arg)
|
201 |
+
else:
|
202 |
+
if arg is S.ComplexInfinity:
|
203 |
+
return S.NaN
|
204 |
+
|
205 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
206 |
+
|
207 |
+
if i_coeff is not None:
|
208 |
+
return I * sin(i_coeff)
|
209 |
+
else:
|
210 |
+
if arg.could_extract_minus_sign():
|
211 |
+
return -cls(-arg)
|
212 |
+
|
213 |
+
if arg.is_Add:
|
214 |
+
x, m = _peeloff_ipi(arg)
|
215 |
+
if m:
|
216 |
+
m = m*pi*I
|
217 |
+
return sinh(m)*cosh(x) + cosh(m)*sinh(x)
|
218 |
+
|
219 |
+
if arg.is_zero:
|
220 |
+
return S.Zero
|
221 |
+
|
222 |
+
if arg.func == asinh:
|
223 |
+
return arg.args[0]
|
224 |
+
|
225 |
+
if arg.func == acosh:
|
226 |
+
x = arg.args[0]
|
227 |
+
return sqrt(x - 1) * sqrt(x + 1)
|
228 |
+
|
229 |
+
if arg.func == atanh:
|
230 |
+
x = arg.args[0]
|
231 |
+
return x/sqrt(1 - x**2)
|
232 |
+
|
233 |
+
if arg.func == acoth:
|
234 |
+
x = arg.args[0]
|
235 |
+
return 1/(sqrt(x - 1) * sqrt(x + 1))
|
236 |
+
|
237 |
+
@staticmethod
|
238 |
+
@cacheit
|
239 |
+
def taylor_term(n, x, *previous_terms):
|
240 |
+
"""
|
241 |
+
Returns the next term in the Taylor series expansion.
|
242 |
+
"""
|
243 |
+
if n < 0 or n % 2 == 0:
|
244 |
+
return S.Zero
|
245 |
+
else:
|
246 |
+
x = sympify(x)
|
247 |
+
|
248 |
+
if len(previous_terms) > 2:
|
249 |
+
p = previous_terms[-2]
|
250 |
+
return p * x**2 / (n*(n - 1))
|
251 |
+
else:
|
252 |
+
return x**(n) / factorial(n)
|
253 |
+
|
254 |
+
def _eval_conjugate(self):
|
255 |
+
return self.func(self.args[0].conjugate())
|
256 |
+
|
257 |
+
def as_real_imag(self, deep=True, **hints):
|
258 |
+
"""
|
259 |
+
Returns this function as a complex coordinate.
|
260 |
+
"""
|
261 |
+
if self.args[0].is_extended_real:
|
262 |
+
if deep:
|
263 |
+
hints['complex'] = False
|
264 |
+
return (self.expand(deep, **hints), S.Zero)
|
265 |
+
else:
|
266 |
+
return (self, S.Zero)
|
267 |
+
if deep:
|
268 |
+
re, im = self.args[0].expand(deep, **hints).as_real_imag()
|
269 |
+
else:
|
270 |
+
re, im = self.args[0].as_real_imag()
|
271 |
+
return (sinh(re)*cos(im), cosh(re)*sin(im))
|
272 |
+
|
273 |
+
def _eval_expand_complex(self, deep=True, **hints):
|
274 |
+
re_part, im_part = self.as_real_imag(deep=deep, **hints)
|
275 |
+
return re_part + im_part*I
|
276 |
+
|
277 |
+
def _eval_expand_trig(self, deep=True, **hints):
|
278 |
+
if deep:
|
279 |
+
arg = self.args[0].expand(deep, **hints)
|
280 |
+
else:
|
281 |
+
arg = self.args[0]
|
282 |
+
x = None
|
283 |
+
if arg.is_Add: # TODO, implement more if deep stuff here
|
284 |
+
x, y = arg.as_two_terms()
|
285 |
+
else:
|
286 |
+
coeff, terms = arg.as_coeff_Mul(rational=True)
|
287 |
+
if coeff is not S.One and coeff.is_Integer and terms is not S.One:
|
288 |
+
x = terms
|
289 |
+
y = (coeff - 1)*x
|
290 |
+
if x is not None:
|
291 |
+
return (sinh(x)*cosh(y) + sinh(y)*cosh(x)).expand(trig=True)
|
292 |
+
return sinh(arg)
|
293 |
+
|
294 |
+
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
|
295 |
+
return (exp(arg) - exp(-arg)) / 2
|
296 |
+
|
297 |
+
def _eval_rewrite_as_exp(self, arg, **kwargs):
|
298 |
+
return (exp(arg) - exp(-arg)) / 2
|
299 |
+
|
300 |
+
def _eval_rewrite_as_sin(self, arg, **kwargs):
|
301 |
+
return -I * sin(I * arg)
|
302 |
+
|
303 |
+
def _eval_rewrite_as_csc(self, arg, **kwargs):
|
304 |
+
return -I / csc(I * arg)
|
305 |
+
|
306 |
+
def _eval_rewrite_as_cosh(self, arg, **kwargs):
|
307 |
+
return -I*cosh(arg + pi*I/2)
|
308 |
+
|
309 |
+
def _eval_rewrite_as_tanh(self, arg, **kwargs):
|
310 |
+
tanh_half = tanh(S.Half*arg)
|
311 |
+
return 2*tanh_half/(1 - tanh_half**2)
|
312 |
+
|
313 |
+
def _eval_rewrite_as_coth(self, arg, **kwargs):
|
314 |
+
coth_half = coth(S.Half*arg)
|
315 |
+
return 2*coth_half/(coth_half**2 - 1)
|
316 |
+
|
317 |
+
def _eval_rewrite_as_csch(self, arg, **kwargs):
|
318 |
+
return 1 / csch(arg)
|
319 |
+
|
320 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
321 |
+
arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
|
322 |
+
arg0 = arg.subs(x, 0)
|
323 |
+
|
324 |
+
if arg0 is S.NaN:
|
325 |
+
arg0 = arg.limit(x, 0, dir='-' if cdir.is_negative else '+')
|
326 |
+
if arg0.is_zero:
|
327 |
+
return arg
|
328 |
+
elif arg0.is_finite:
|
329 |
+
return self.func(arg0)
|
330 |
+
else:
|
331 |
+
return self
|
332 |
+
|
333 |
+
def _eval_is_real(self):
|
334 |
+
arg = self.args[0]
|
335 |
+
if arg.is_real:
|
336 |
+
return True
|
337 |
+
|
338 |
+
# if `im` is of the form n*pi
|
339 |
+
# else, check if it is a number
|
340 |
+
re, im = arg.as_real_imag()
|
341 |
+
return (im%pi).is_zero
|
342 |
+
|
343 |
+
def _eval_is_extended_real(self):
|
344 |
+
if self.args[0].is_extended_real:
|
345 |
+
return True
|
346 |
+
|
347 |
+
def _eval_is_positive(self):
|
348 |
+
if self.args[0].is_extended_real:
|
349 |
+
return self.args[0].is_positive
|
350 |
+
|
351 |
+
def _eval_is_negative(self):
|
352 |
+
if self.args[0].is_extended_real:
|
353 |
+
return self.args[0].is_negative
|
354 |
+
|
355 |
+
def _eval_is_finite(self):
|
356 |
+
arg = self.args[0]
|
357 |
+
return arg.is_finite
|
358 |
+
|
359 |
+
def _eval_is_zero(self):
|
360 |
+
rest, ipi_mult = _peeloff_ipi(self.args[0])
|
361 |
+
if rest.is_zero:
|
362 |
+
return ipi_mult.is_integer
|
363 |
+
|
364 |
+
|
365 |
+
class cosh(HyperbolicFunction):
|
366 |
+
r"""
|
367 |
+
``cosh(x)`` is the hyperbolic cosine of ``x``.
|
368 |
+
|
369 |
+
The hyperbolic cosine function is $\frac{e^x + e^{-x}}{2}$.
|
370 |
+
|
371 |
+
Examples
|
372 |
+
========
|
373 |
+
|
374 |
+
>>> from sympy import cosh
|
375 |
+
>>> from sympy.abc import x
|
376 |
+
>>> cosh(x)
|
377 |
+
cosh(x)
|
378 |
+
|
379 |
+
See Also
|
380 |
+
========
|
381 |
+
|
382 |
+
sinh, tanh, acosh
|
383 |
+
"""
|
384 |
+
|
385 |
+
def fdiff(self, argindex=1):
|
386 |
+
if argindex == 1:
|
387 |
+
return sinh(self.args[0])
|
388 |
+
else:
|
389 |
+
raise ArgumentIndexError(self, argindex)
|
390 |
+
|
391 |
+
@classmethod
|
392 |
+
def eval(cls, arg):
|
393 |
+
from sympy.functions.elementary.trigonometric import cos
|
394 |
+
if arg.is_Number:
|
395 |
+
if arg is S.NaN:
|
396 |
+
return S.NaN
|
397 |
+
elif arg is S.Infinity:
|
398 |
+
return S.Infinity
|
399 |
+
elif arg is S.NegativeInfinity:
|
400 |
+
return S.Infinity
|
401 |
+
elif arg.is_zero:
|
402 |
+
return S.One
|
403 |
+
elif arg.is_negative:
|
404 |
+
return cls(-arg)
|
405 |
+
else:
|
406 |
+
if arg is S.ComplexInfinity:
|
407 |
+
return S.NaN
|
408 |
+
|
409 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
410 |
+
|
411 |
+
if i_coeff is not None:
|
412 |
+
return cos(i_coeff)
|
413 |
+
else:
|
414 |
+
if arg.could_extract_minus_sign():
|
415 |
+
return cls(-arg)
|
416 |
+
|
417 |
+
if arg.is_Add:
|
418 |
+
x, m = _peeloff_ipi(arg)
|
419 |
+
if m:
|
420 |
+
m = m*pi*I
|
421 |
+
return cosh(m)*cosh(x) + sinh(m)*sinh(x)
|
422 |
+
|
423 |
+
if arg.is_zero:
|
424 |
+
return S.One
|
425 |
+
|
426 |
+
if arg.func == asinh:
|
427 |
+
return sqrt(1 + arg.args[0]**2)
|
428 |
+
|
429 |
+
if arg.func == acosh:
|
430 |
+
return arg.args[0]
|
431 |
+
|
432 |
+
if arg.func == atanh:
|
433 |
+
return 1/sqrt(1 - arg.args[0]**2)
|
434 |
+
|
435 |
+
if arg.func == acoth:
|
436 |
+
x = arg.args[0]
|
437 |
+
return x/(sqrt(x - 1) * sqrt(x + 1))
|
438 |
+
|
439 |
+
@staticmethod
|
440 |
+
@cacheit
|
441 |
+
def taylor_term(n, x, *previous_terms):
|
442 |
+
if n < 0 or n % 2 == 1:
|
443 |
+
return S.Zero
|
444 |
+
else:
|
445 |
+
x = sympify(x)
|
446 |
+
|
447 |
+
if len(previous_terms) > 2:
|
448 |
+
p = previous_terms[-2]
|
449 |
+
return p * x**2 / (n*(n - 1))
|
450 |
+
else:
|
451 |
+
return x**(n)/factorial(n)
|
452 |
+
|
453 |
+
def _eval_conjugate(self):
|
454 |
+
return self.func(self.args[0].conjugate())
|
455 |
+
|
456 |
+
def as_real_imag(self, deep=True, **hints):
|
457 |
+
if self.args[0].is_extended_real:
|
458 |
+
if deep:
|
459 |
+
hints['complex'] = False
|
460 |
+
return (self.expand(deep, **hints), S.Zero)
|
461 |
+
else:
|
462 |
+
return (self, S.Zero)
|
463 |
+
if deep:
|
464 |
+
re, im = self.args[0].expand(deep, **hints).as_real_imag()
|
465 |
+
else:
|
466 |
+
re, im = self.args[0].as_real_imag()
|
467 |
+
|
468 |
+
return (cosh(re)*cos(im), sinh(re)*sin(im))
|
469 |
+
|
470 |
+
def _eval_expand_complex(self, deep=True, **hints):
|
471 |
+
re_part, im_part = self.as_real_imag(deep=deep, **hints)
|
472 |
+
return re_part + im_part*I
|
473 |
+
|
474 |
+
def _eval_expand_trig(self, deep=True, **hints):
|
475 |
+
if deep:
|
476 |
+
arg = self.args[0].expand(deep, **hints)
|
477 |
+
else:
|
478 |
+
arg = self.args[0]
|
479 |
+
x = None
|
480 |
+
if arg.is_Add: # TODO, implement more if deep stuff here
|
481 |
+
x, y = arg.as_two_terms()
|
482 |
+
else:
|
483 |
+
coeff, terms = arg.as_coeff_Mul(rational=True)
|
484 |
+
if coeff is not S.One and coeff.is_Integer and terms is not S.One:
|
485 |
+
x = terms
|
486 |
+
y = (coeff - 1)*x
|
487 |
+
if x is not None:
|
488 |
+
return (cosh(x)*cosh(y) + sinh(x)*sinh(y)).expand(trig=True)
|
489 |
+
return cosh(arg)
|
490 |
+
|
491 |
+
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
|
492 |
+
return (exp(arg) + exp(-arg)) / 2
|
493 |
+
|
494 |
+
def _eval_rewrite_as_exp(self, arg, **kwargs):
|
495 |
+
return (exp(arg) + exp(-arg)) / 2
|
496 |
+
|
497 |
+
def _eval_rewrite_as_cos(self, arg, **kwargs):
|
498 |
+
return cos(I * arg)
|
499 |
+
|
500 |
+
def _eval_rewrite_as_sec(self, arg, **kwargs):
|
501 |
+
return 1 / sec(I * arg)
|
502 |
+
|
503 |
+
def _eval_rewrite_as_sinh(self, arg, **kwargs):
|
504 |
+
return -I*sinh(arg + pi*I/2)
|
505 |
+
|
506 |
+
def _eval_rewrite_as_tanh(self, arg, **kwargs):
|
507 |
+
tanh_half = tanh(S.Half*arg)**2
|
508 |
+
return (1 + tanh_half)/(1 - tanh_half)
|
509 |
+
|
510 |
+
def _eval_rewrite_as_coth(self, arg, **kwargs):
|
511 |
+
coth_half = coth(S.Half*arg)**2
|
512 |
+
return (coth_half + 1)/(coth_half - 1)
|
513 |
+
|
514 |
+
def _eval_rewrite_as_sech(self, arg, **kwargs):
|
515 |
+
return 1 / sech(arg)
|
516 |
+
|
517 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
518 |
+
arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
|
519 |
+
arg0 = arg.subs(x, 0)
|
520 |
+
|
521 |
+
if arg0 is S.NaN:
|
522 |
+
arg0 = arg.limit(x, 0, dir='-' if cdir.is_negative else '+')
|
523 |
+
if arg0.is_zero:
|
524 |
+
return S.One
|
525 |
+
elif arg0.is_finite:
|
526 |
+
return self.func(arg0)
|
527 |
+
else:
|
528 |
+
return self
|
529 |
+
|
530 |
+
def _eval_is_real(self):
|
531 |
+
arg = self.args[0]
|
532 |
+
|
533 |
+
# `cosh(x)` is real for real OR purely imaginary `x`
|
534 |
+
if arg.is_real or arg.is_imaginary:
|
535 |
+
return True
|
536 |
+
|
537 |
+
# cosh(a+ib) = cos(b)*cosh(a) + i*sin(b)*sinh(a)
|
538 |
+
# the imaginary part can be an expression like n*pi
|
539 |
+
# if not, check if the imaginary part is a number
|
540 |
+
re, im = arg.as_real_imag()
|
541 |
+
return (im%pi).is_zero
|
542 |
+
|
543 |
+
def _eval_is_positive(self):
|
544 |
+
# cosh(x+I*y) = cos(y)*cosh(x) + I*sin(y)*sinh(x)
|
545 |
+
# cosh(z) is positive iff it is real and the real part is positive.
|
546 |
+
# So we need sin(y)*sinh(x) = 0 which gives x=0 or y=n*pi
|
547 |
+
# Case 1 (y=n*pi): cosh(z) = (-1)**n * cosh(x) -> positive for n even
|
548 |
+
# Case 2 (x=0): cosh(z) = cos(y) -> positive when cos(y) is positive
|
549 |
+
z = self.args[0]
|
550 |
+
|
551 |
+
x, y = z.as_real_imag()
|
552 |
+
ymod = y % (2*pi)
|
553 |
+
|
554 |
+
yzero = ymod.is_zero
|
555 |
+
# shortcut if ymod is zero
|
556 |
+
if yzero:
|
557 |
+
return True
|
558 |
+
|
559 |
+
xzero = x.is_zero
|
560 |
+
# shortcut x is not zero
|
561 |
+
if xzero is False:
|
562 |
+
return yzero
|
563 |
+
|
564 |
+
return fuzzy_or([
|
565 |
+
# Case 1:
|
566 |
+
yzero,
|
567 |
+
# Case 2:
|
568 |
+
fuzzy_and([
|
569 |
+
xzero,
|
570 |
+
fuzzy_or([ymod < pi/2, ymod > 3*pi/2])
|
571 |
+
])
|
572 |
+
])
|
573 |
+
|
574 |
+
|
575 |
+
def _eval_is_nonnegative(self):
|
576 |
+
z = self.args[0]
|
577 |
+
|
578 |
+
x, y = z.as_real_imag()
|
579 |
+
ymod = y % (2*pi)
|
580 |
+
|
581 |
+
yzero = ymod.is_zero
|
582 |
+
# shortcut if ymod is zero
|
583 |
+
if yzero:
|
584 |
+
return True
|
585 |
+
|
586 |
+
xzero = x.is_zero
|
587 |
+
# shortcut x is not zero
|
588 |
+
if xzero is False:
|
589 |
+
return yzero
|
590 |
+
|
591 |
+
return fuzzy_or([
|
592 |
+
# Case 1:
|
593 |
+
yzero,
|
594 |
+
# Case 2:
|
595 |
+
fuzzy_and([
|
596 |
+
xzero,
|
597 |
+
fuzzy_or([ymod <= pi/2, ymod >= 3*pi/2])
|
598 |
+
])
|
599 |
+
])
|
600 |
+
|
601 |
+
def _eval_is_finite(self):
|
602 |
+
arg = self.args[0]
|
603 |
+
return arg.is_finite
|
604 |
+
|
605 |
+
def _eval_is_zero(self):
|
606 |
+
rest, ipi_mult = _peeloff_ipi(self.args[0])
|
607 |
+
if ipi_mult and rest.is_zero:
|
608 |
+
return (ipi_mult - S.Half).is_integer
|
609 |
+
|
610 |
+
|
611 |
+
class tanh(HyperbolicFunction):
|
612 |
+
r"""
|
613 |
+
``tanh(x)`` is the hyperbolic tangent of ``x``.
|
614 |
+
|
615 |
+
The hyperbolic tangent function is $\frac{\sinh(x)}{\cosh(x)}$.
|
616 |
+
|
617 |
+
Examples
|
618 |
+
========
|
619 |
+
|
620 |
+
>>> from sympy import tanh
|
621 |
+
>>> from sympy.abc import x
|
622 |
+
>>> tanh(x)
|
623 |
+
tanh(x)
|
624 |
+
|
625 |
+
See Also
|
626 |
+
========
|
627 |
+
|
628 |
+
sinh, cosh, atanh
|
629 |
+
"""
|
630 |
+
|
631 |
+
def fdiff(self, argindex=1):
|
632 |
+
if argindex == 1:
|
633 |
+
return S.One - tanh(self.args[0])**2
|
634 |
+
else:
|
635 |
+
raise ArgumentIndexError(self, argindex)
|
636 |
+
|
637 |
+
def inverse(self, argindex=1):
|
638 |
+
"""
|
639 |
+
Returns the inverse of this function.
|
640 |
+
"""
|
641 |
+
return atanh
|
642 |
+
|
643 |
+
@classmethod
|
644 |
+
def eval(cls, arg):
|
645 |
+
if arg.is_Number:
|
646 |
+
if arg is S.NaN:
|
647 |
+
return S.NaN
|
648 |
+
elif arg is S.Infinity:
|
649 |
+
return S.One
|
650 |
+
elif arg is S.NegativeInfinity:
|
651 |
+
return S.NegativeOne
|
652 |
+
elif arg.is_zero:
|
653 |
+
return S.Zero
|
654 |
+
elif arg.is_negative:
|
655 |
+
return -cls(-arg)
|
656 |
+
else:
|
657 |
+
if arg is S.ComplexInfinity:
|
658 |
+
return S.NaN
|
659 |
+
|
660 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
661 |
+
|
662 |
+
if i_coeff is not None:
|
663 |
+
if i_coeff.could_extract_minus_sign():
|
664 |
+
return -I * tan(-i_coeff)
|
665 |
+
return I * tan(i_coeff)
|
666 |
+
else:
|
667 |
+
if arg.could_extract_minus_sign():
|
668 |
+
return -cls(-arg)
|
669 |
+
|
670 |
+
if arg.is_Add:
|
671 |
+
x, m = _peeloff_ipi(arg)
|
672 |
+
if m:
|
673 |
+
tanhm = tanh(m*pi*I)
|
674 |
+
if tanhm is S.ComplexInfinity:
|
675 |
+
return coth(x)
|
676 |
+
else: # tanhm == 0
|
677 |
+
return tanh(x)
|
678 |
+
|
679 |
+
if arg.is_zero:
|
680 |
+
return S.Zero
|
681 |
+
|
682 |
+
if arg.func == asinh:
|
683 |
+
x = arg.args[0]
|
684 |
+
return x/sqrt(1 + x**2)
|
685 |
+
|
686 |
+
if arg.func == acosh:
|
687 |
+
x = arg.args[0]
|
688 |
+
return sqrt(x - 1) * sqrt(x + 1) / x
|
689 |
+
|
690 |
+
if arg.func == atanh:
|
691 |
+
return arg.args[0]
|
692 |
+
|
693 |
+
if arg.func == acoth:
|
694 |
+
return 1/arg.args[0]
|
695 |
+
|
696 |
+
@staticmethod
|
697 |
+
@cacheit
|
698 |
+
def taylor_term(n, x, *previous_terms):
|
699 |
+
if n < 0 or n % 2 == 0:
|
700 |
+
return S.Zero
|
701 |
+
else:
|
702 |
+
x = sympify(x)
|
703 |
+
|
704 |
+
a = 2**(n + 1)
|
705 |
+
|
706 |
+
B = bernoulli(n + 1)
|
707 |
+
F = factorial(n + 1)
|
708 |
+
|
709 |
+
return a*(a - 1) * B/F * x**n
|
710 |
+
|
711 |
+
def _eval_conjugate(self):
|
712 |
+
return self.func(self.args[0].conjugate())
|
713 |
+
|
714 |
+
def as_real_imag(self, deep=True, **hints):
|
715 |
+
if self.args[0].is_extended_real:
|
716 |
+
if deep:
|
717 |
+
hints['complex'] = False
|
718 |
+
return (self.expand(deep, **hints), S.Zero)
|
719 |
+
else:
|
720 |
+
return (self, S.Zero)
|
721 |
+
if deep:
|
722 |
+
re, im = self.args[0].expand(deep, **hints).as_real_imag()
|
723 |
+
else:
|
724 |
+
re, im = self.args[0].as_real_imag()
|
725 |
+
denom = sinh(re)**2 + cos(im)**2
|
726 |
+
return (sinh(re)*cosh(re)/denom, sin(im)*cos(im)/denom)
|
727 |
+
|
728 |
+
def _eval_expand_trig(self, **hints):
|
729 |
+
arg = self.args[0]
|
730 |
+
if arg.is_Add:
|
731 |
+
n = len(arg.args)
|
732 |
+
TX = [tanh(x, evaluate=False)._eval_expand_trig()
|
733 |
+
for x in arg.args]
|
734 |
+
p = [0, 0] # [den, num]
|
735 |
+
for i in range(n + 1):
|
736 |
+
p[i % 2] += symmetric_poly(i, TX)
|
737 |
+
return p[1]/p[0]
|
738 |
+
elif arg.is_Mul:
|
739 |
+
coeff, terms = arg.as_coeff_Mul()
|
740 |
+
if coeff.is_Integer and coeff > 1:
|
741 |
+
T = tanh(terms)
|
742 |
+
n = [nC(range(coeff), k)*T**k for k in range(1, coeff + 1, 2)]
|
743 |
+
d = [nC(range(coeff), k)*T**k for k in range(0, coeff + 1, 2)]
|
744 |
+
return Add(*n)/Add(*d)
|
745 |
+
return tanh(arg)
|
746 |
+
|
747 |
+
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
|
748 |
+
neg_exp, pos_exp = exp(-arg), exp(arg)
|
749 |
+
return (pos_exp - neg_exp)/(pos_exp + neg_exp)
|
750 |
+
|
751 |
+
def _eval_rewrite_as_exp(self, arg, **kwargs):
|
752 |
+
neg_exp, pos_exp = exp(-arg), exp(arg)
|
753 |
+
return (pos_exp - neg_exp)/(pos_exp + neg_exp)
|
754 |
+
|
755 |
+
def _eval_rewrite_as_tan(self, arg, **kwargs):
|
756 |
+
return -I * tan(I * arg)
|
757 |
+
|
758 |
+
def _eval_rewrite_as_cot(self, arg, **kwargs):
|
759 |
+
return -I / cot(I * arg)
|
760 |
+
|
761 |
+
def _eval_rewrite_as_sinh(self, arg, **kwargs):
|
762 |
+
return I*sinh(arg)/sinh(pi*I/2 - arg)
|
763 |
+
|
764 |
+
def _eval_rewrite_as_cosh(self, arg, **kwargs):
|
765 |
+
return I*cosh(pi*I/2 - arg)/cosh(arg)
|
766 |
+
|
767 |
+
def _eval_rewrite_as_coth(self, arg, **kwargs):
|
768 |
+
return 1/coth(arg)
|
769 |
+
|
770 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
771 |
+
from sympy.series.order import Order
|
772 |
+
arg = self.args[0].as_leading_term(x)
|
773 |
+
|
774 |
+
if x in arg.free_symbols and Order(1, x).contains(arg):
|
775 |
+
return arg
|
776 |
+
else:
|
777 |
+
return self.func(arg)
|
778 |
+
|
779 |
+
def _eval_is_real(self):
|
780 |
+
arg = self.args[0]
|
781 |
+
if arg.is_real:
|
782 |
+
return True
|
783 |
+
|
784 |
+
re, im = arg.as_real_imag()
|
785 |
+
|
786 |
+
# if denom = 0, tanh(arg) = zoo
|
787 |
+
if re == 0 and im % pi == pi/2:
|
788 |
+
return None
|
789 |
+
|
790 |
+
# check if im is of the form n*pi/2 to make sin(2*im) = 0
|
791 |
+
# if not, im could be a number, return False in that case
|
792 |
+
return (im % (pi/2)).is_zero
|
793 |
+
|
794 |
+
def _eval_is_extended_real(self):
|
795 |
+
if self.args[0].is_extended_real:
|
796 |
+
return True
|
797 |
+
|
798 |
+
def _eval_is_positive(self):
|
799 |
+
if self.args[0].is_extended_real:
|
800 |
+
return self.args[0].is_positive
|
801 |
+
|
802 |
+
def _eval_is_negative(self):
|
803 |
+
if self.args[0].is_extended_real:
|
804 |
+
return self.args[0].is_negative
|
805 |
+
|
806 |
+
def _eval_is_finite(self):
|
807 |
+
arg = self.args[0]
|
808 |
+
|
809 |
+
re, im = arg.as_real_imag()
|
810 |
+
denom = cos(im)**2 + sinh(re)**2
|
811 |
+
if denom == 0:
|
812 |
+
return False
|
813 |
+
elif denom.is_number:
|
814 |
+
return True
|
815 |
+
if arg.is_extended_real:
|
816 |
+
return True
|
817 |
+
|
818 |
+
def _eval_is_zero(self):
|
819 |
+
arg = self.args[0]
|
820 |
+
if arg.is_zero:
|
821 |
+
return True
|
822 |
+
|
823 |
+
|
824 |
+
class coth(HyperbolicFunction):
|
825 |
+
r"""
|
826 |
+
``coth(x)`` is the hyperbolic cotangent of ``x``.
|
827 |
+
|
828 |
+
The hyperbolic cotangent function is $\frac{\cosh(x)}{\sinh(x)}$.
|
829 |
+
|
830 |
+
Examples
|
831 |
+
========
|
832 |
+
|
833 |
+
>>> from sympy import coth
|
834 |
+
>>> from sympy.abc import x
|
835 |
+
>>> coth(x)
|
836 |
+
coth(x)
|
837 |
+
|
838 |
+
See Also
|
839 |
+
========
|
840 |
+
|
841 |
+
sinh, cosh, acoth
|
842 |
+
"""
|
843 |
+
|
844 |
+
def fdiff(self, argindex=1):
|
845 |
+
if argindex == 1:
|
846 |
+
return -1/sinh(self.args[0])**2
|
847 |
+
else:
|
848 |
+
raise ArgumentIndexError(self, argindex)
|
849 |
+
|
850 |
+
def inverse(self, argindex=1):
|
851 |
+
"""
|
852 |
+
Returns the inverse of this function.
|
853 |
+
"""
|
854 |
+
return acoth
|
855 |
+
|
856 |
+
@classmethod
|
857 |
+
def eval(cls, arg):
|
858 |
+
if arg.is_Number:
|
859 |
+
if arg is S.NaN:
|
860 |
+
return S.NaN
|
861 |
+
elif arg is S.Infinity:
|
862 |
+
return S.One
|
863 |
+
elif arg is S.NegativeInfinity:
|
864 |
+
return S.NegativeOne
|
865 |
+
elif arg.is_zero:
|
866 |
+
return S.ComplexInfinity
|
867 |
+
elif arg.is_negative:
|
868 |
+
return -cls(-arg)
|
869 |
+
else:
|
870 |
+
if arg is S.ComplexInfinity:
|
871 |
+
return S.NaN
|
872 |
+
|
873 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
874 |
+
|
875 |
+
if i_coeff is not None:
|
876 |
+
if i_coeff.could_extract_minus_sign():
|
877 |
+
return I * cot(-i_coeff)
|
878 |
+
return -I * cot(i_coeff)
|
879 |
+
else:
|
880 |
+
if arg.could_extract_minus_sign():
|
881 |
+
return -cls(-arg)
|
882 |
+
|
883 |
+
if arg.is_Add:
|
884 |
+
x, m = _peeloff_ipi(arg)
|
885 |
+
if m:
|
886 |
+
cothm = coth(m*pi*I)
|
887 |
+
if cothm is S.ComplexInfinity:
|
888 |
+
return coth(x)
|
889 |
+
else: # cothm == 0
|
890 |
+
return tanh(x)
|
891 |
+
|
892 |
+
if arg.is_zero:
|
893 |
+
return S.ComplexInfinity
|
894 |
+
|
895 |
+
if arg.func == asinh:
|
896 |
+
x = arg.args[0]
|
897 |
+
return sqrt(1 + x**2)/x
|
898 |
+
|
899 |
+
if arg.func == acosh:
|
900 |
+
x = arg.args[0]
|
901 |
+
return x/(sqrt(x - 1) * sqrt(x + 1))
|
902 |
+
|
903 |
+
if arg.func == atanh:
|
904 |
+
return 1/arg.args[0]
|
905 |
+
|
906 |
+
if arg.func == acoth:
|
907 |
+
return arg.args[0]
|
908 |
+
|
909 |
+
@staticmethod
|
910 |
+
@cacheit
|
911 |
+
def taylor_term(n, x, *previous_terms):
|
912 |
+
if n == 0:
|
913 |
+
return 1 / sympify(x)
|
914 |
+
elif n < 0 or n % 2 == 0:
|
915 |
+
return S.Zero
|
916 |
+
else:
|
917 |
+
x = sympify(x)
|
918 |
+
|
919 |
+
B = bernoulli(n + 1)
|
920 |
+
F = factorial(n + 1)
|
921 |
+
|
922 |
+
return 2**(n + 1) * B/F * x**n
|
923 |
+
|
924 |
+
def _eval_conjugate(self):
|
925 |
+
return self.func(self.args[0].conjugate())
|
926 |
+
|
927 |
+
def as_real_imag(self, deep=True, **hints):
|
928 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
929 |
+
if self.args[0].is_extended_real:
|
930 |
+
if deep:
|
931 |
+
hints['complex'] = False
|
932 |
+
return (self.expand(deep, **hints), S.Zero)
|
933 |
+
else:
|
934 |
+
return (self, S.Zero)
|
935 |
+
if deep:
|
936 |
+
re, im = self.args[0].expand(deep, **hints).as_real_imag()
|
937 |
+
else:
|
938 |
+
re, im = self.args[0].as_real_imag()
|
939 |
+
denom = sinh(re)**2 + sin(im)**2
|
940 |
+
return (sinh(re)*cosh(re)/denom, -sin(im)*cos(im)/denom)
|
941 |
+
|
942 |
+
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
|
943 |
+
neg_exp, pos_exp = exp(-arg), exp(arg)
|
944 |
+
return (pos_exp + neg_exp)/(pos_exp - neg_exp)
|
945 |
+
|
946 |
+
def _eval_rewrite_as_exp(self, arg, **kwargs):
|
947 |
+
neg_exp, pos_exp = exp(-arg), exp(arg)
|
948 |
+
return (pos_exp + neg_exp)/(pos_exp - neg_exp)
|
949 |
+
|
950 |
+
def _eval_rewrite_as_sinh(self, arg, **kwargs):
|
951 |
+
return -I*sinh(pi*I/2 - arg)/sinh(arg)
|
952 |
+
|
953 |
+
def _eval_rewrite_as_cosh(self, arg, **kwargs):
|
954 |
+
return -I*cosh(arg)/cosh(pi*I/2 - arg)
|
955 |
+
|
956 |
+
def _eval_rewrite_as_tanh(self, arg, **kwargs):
|
957 |
+
return 1/tanh(arg)
|
958 |
+
|
959 |
+
def _eval_is_positive(self):
|
960 |
+
if self.args[0].is_extended_real:
|
961 |
+
return self.args[0].is_positive
|
962 |
+
|
963 |
+
def _eval_is_negative(self):
|
964 |
+
if self.args[0].is_extended_real:
|
965 |
+
return self.args[0].is_negative
|
966 |
+
|
967 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
968 |
+
from sympy.series.order import Order
|
969 |
+
arg = self.args[0].as_leading_term(x)
|
970 |
+
|
971 |
+
if x in arg.free_symbols and Order(1, x).contains(arg):
|
972 |
+
return 1/arg
|
973 |
+
else:
|
974 |
+
return self.func(arg)
|
975 |
+
|
976 |
+
def _eval_expand_trig(self, **hints):
|
977 |
+
arg = self.args[0]
|
978 |
+
if arg.is_Add:
|
979 |
+
CX = [coth(x, evaluate=False)._eval_expand_trig() for x in arg.args]
|
980 |
+
p = [[], []]
|
981 |
+
n = len(arg.args)
|
982 |
+
for i in range(n, -1, -1):
|
983 |
+
p[(n - i) % 2].append(symmetric_poly(i, CX))
|
984 |
+
return Add(*p[0])/Add(*p[1])
|
985 |
+
elif arg.is_Mul:
|
986 |
+
coeff, x = arg.as_coeff_Mul(rational=True)
|
987 |
+
if coeff.is_Integer and coeff > 1:
|
988 |
+
c = coth(x, evaluate=False)
|
989 |
+
p = [[], []]
|
990 |
+
for i in range(coeff, -1, -1):
|
991 |
+
p[(coeff - i) % 2].append(binomial(coeff, i)*c**i)
|
992 |
+
return Add(*p[0])/Add(*p[1])
|
993 |
+
return coth(arg)
|
994 |
+
|
995 |
+
|
996 |
+
class ReciprocalHyperbolicFunction(HyperbolicFunction):
|
997 |
+
"""Base class for reciprocal functions of hyperbolic functions. """
|
998 |
+
|
999 |
+
#To be defined in class
|
1000 |
+
_reciprocal_of = None
|
1001 |
+
_is_even: FuzzyBool = None
|
1002 |
+
_is_odd: FuzzyBool = None
|
1003 |
+
|
1004 |
+
@classmethod
|
1005 |
+
def eval(cls, arg):
|
1006 |
+
if arg.could_extract_minus_sign():
|
1007 |
+
if cls._is_even:
|
1008 |
+
return cls(-arg)
|
1009 |
+
if cls._is_odd:
|
1010 |
+
return -cls(-arg)
|
1011 |
+
|
1012 |
+
t = cls._reciprocal_of.eval(arg)
|
1013 |
+
if hasattr(arg, 'inverse') and arg.inverse() == cls:
|
1014 |
+
return arg.args[0]
|
1015 |
+
return 1/t if t is not None else t
|
1016 |
+
|
1017 |
+
def _call_reciprocal(self, method_name, *args, **kwargs):
|
1018 |
+
# Calls method_name on _reciprocal_of
|
1019 |
+
o = self._reciprocal_of(self.args[0])
|
1020 |
+
return getattr(o, method_name)(*args, **kwargs)
|
1021 |
+
|
1022 |
+
def _calculate_reciprocal(self, method_name, *args, **kwargs):
|
1023 |
+
# If calling method_name on _reciprocal_of returns a value != None
|
1024 |
+
# then return the reciprocal of that value
|
1025 |
+
t = self._call_reciprocal(method_name, *args, **kwargs)
|
1026 |
+
return 1/t if t is not None else t
|
1027 |
+
|
1028 |
+
def _rewrite_reciprocal(self, method_name, arg):
|
1029 |
+
# Special handling for rewrite functions. If reciprocal rewrite returns
|
1030 |
+
# unmodified expression, then return None
|
1031 |
+
t = self._call_reciprocal(method_name, arg)
|
1032 |
+
if t is not None and t != self._reciprocal_of(arg):
|
1033 |
+
return 1/t
|
1034 |
+
|
1035 |
+
def _eval_rewrite_as_exp(self, arg, **kwargs):
|
1036 |
+
return self._rewrite_reciprocal("_eval_rewrite_as_exp", arg)
|
1037 |
+
|
1038 |
+
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
|
1039 |
+
return self._rewrite_reciprocal("_eval_rewrite_as_tractable", arg)
|
1040 |
+
|
1041 |
+
def _eval_rewrite_as_tanh(self, arg, **kwargs):
|
1042 |
+
return self._rewrite_reciprocal("_eval_rewrite_as_tanh", arg)
|
1043 |
+
|
1044 |
+
def _eval_rewrite_as_coth(self, arg, **kwargs):
|
1045 |
+
return self._rewrite_reciprocal("_eval_rewrite_as_coth", arg)
|
1046 |
+
|
1047 |
+
def as_real_imag(self, deep = True, **hints):
|
1048 |
+
return (1 / self._reciprocal_of(self.args[0])).as_real_imag(deep, **hints)
|
1049 |
+
|
1050 |
+
def _eval_conjugate(self):
|
1051 |
+
return self.func(self.args[0].conjugate())
|
1052 |
+
|
1053 |
+
def _eval_expand_complex(self, deep=True, **hints):
|
1054 |
+
re_part, im_part = self.as_real_imag(deep=True, **hints)
|
1055 |
+
return re_part + I*im_part
|
1056 |
+
|
1057 |
+
def _eval_expand_trig(self, **hints):
|
1058 |
+
return self._calculate_reciprocal("_eval_expand_trig", **hints)
|
1059 |
+
|
1060 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
1061 |
+
return (1/self._reciprocal_of(self.args[0]))._eval_as_leading_term(x)
|
1062 |
+
|
1063 |
+
def _eval_is_extended_real(self):
|
1064 |
+
return self._reciprocal_of(self.args[0]).is_extended_real
|
1065 |
+
|
1066 |
+
def _eval_is_finite(self):
|
1067 |
+
return (1/self._reciprocal_of(self.args[0])).is_finite
|
1068 |
+
|
1069 |
+
|
1070 |
+
class csch(ReciprocalHyperbolicFunction):
|
1071 |
+
r"""
|
1072 |
+
``csch(x)`` is the hyperbolic cosecant of ``x``.
|
1073 |
+
|
1074 |
+
The hyperbolic cosecant function is $\frac{2}{e^x - e^{-x}}$
|
1075 |
+
|
1076 |
+
Examples
|
1077 |
+
========
|
1078 |
+
|
1079 |
+
>>> from sympy import csch
|
1080 |
+
>>> from sympy.abc import x
|
1081 |
+
>>> csch(x)
|
1082 |
+
csch(x)
|
1083 |
+
|
1084 |
+
See Also
|
1085 |
+
========
|
1086 |
+
|
1087 |
+
sinh, cosh, tanh, sech, asinh, acosh
|
1088 |
+
"""
|
1089 |
+
|
1090 |
+
_reciprocal_of = sinh
|
1091 |
+
_is_odd = True
|
1092 |
+
|
1093 |
+
def fdiff(self, argindex=1):
|
1094 |
+
"""
|
1095 |
+
Returns the first derivative of this function
|
1096 |
+
"""
|
1097 |
+
if argindex == 1:
|
1098 |
+
return -coth(self.args[0]) * csch(self.args[0])
|
1099 |
+
else:
|
1100 |
+
raise ArgumentIndexError(self, argindex)
|
1101 |
+
|
1102 |
+
@staticmethod
|
1103 |
+
@cacheit
|
1104 |
+
def taylor_term(n, x, *previous_terms):
|
1105 |
+
"""
|
1106 |
+
Returns the next term in the Taylor series expansion
|
1107 |
+
"""
|
1108 |
+
if n == 0:
|
1109 |
+
return 1/sympify(x)
|
1110 |
+
elif n < 0 or n % 2 == 0:
|
1111 |
+
return S.Zero
|
1112 |
+
else:
|
1113 |
+
x = sympify(x)
|
1114 |
+
|
1115 |
+
B = bernoulli(n + 1)
|
1116 |
+
F = factorial(n + 1)
|
1117 |
+
|
1118 |
+
return 2 * (1 - 2**n) * B/F * x**n
|
1119 |
+
|
1120 |
+
def _eval_rewrite_as_sin(self, arg, **kwargs):
|
1121 |
+
return I / sin(I * arg)
|
1122 |
+
|
1123 |
+
def _eval_rewrite_as_csc(self, arg, **kwargs):
|
1124 |
+
return I * csc(I * arg)
|
1125 |
+
|
1126 |
+
def _eval_rewrite_as_cosh(self, arg, **kwargs):
|
1127 |
+
return I / cosh(arg + I * pi / 2)
|
1128 |
+
|
1129 |
+
def _eval_rewrite_as_sinh(self, arg, **kwargs):
|
1130 |
+
return 1 / sinh(arg)
|
1131 |
+
|
1132 |
+
def _eval_is_positive(self):
|
1133 |
+
if self.args[0].is_extended_real:
|
1134 |
+
return self.args[0].is_positive
|
1135 |
+
|
1136 |
+
def _eval_is_negative(self):
|
1137 |
+
if self.args[0].is_extended_real:
|
1138 |
+
return self.args[0].is_negative
|
1139 |
+
|
1140 |
+
|
1141 |
+
class sech(ReciprocalHyperbolicFunction):
|
1142 |
+
r"""
|
1143 |
+
``sech(x)`` is the hyperbolic secant of ``x``.
|
1144 |
+
|
1145 |
+
The hyperbolic secant function is $\frac{2}{e^x + e^{-x}}$
|
1146 |
+
|
1147 |
+
Examples
|
1148 |
+
========
|
1149 |
+
|
1150 |
+
>>> from sympy import sech
|
1151 |
+
>>> from sympy.abc import x
|
1152 |
+
>>> sech(x)
|
1153 |
+
sech(x)
|
1154 |
+
|
1155 |
+
See Also
|
1156 |
+
========
|
1157 |
+
|
1158 |
+
sinh, cosh, tanh, coth, csch, asinh, acosh
|
1159 |
+
"""
|
1160 |
+
|
1161 |
+
_reciprocal_of = cosh
|
1162 |
+
_is_even = True
|
1163 |
+
|
1164 |
+
def fdiff(self, argindex=1):
|
1165 |
+
if argindex == 1:
|
1166 |
+
return - tanh(self.args[0])*sech(self.args[0])
|
1167 |
+
else:
|
1168 |
+
raise ArgumentIndexError(self, argindex)
|
1169 |
+
|
1170 |
+
@staticmethod
|
1171 |
+
@cacheit
|
1172 |
+
def taylor_term(n, x, *previous_terms):
|
1173 |
+
if n < 0 or n % 2 == 1:
|
1174 |
+
return S.Zero
|
1175 |
+
else:
|
1176 |
+
x = sympify(x)
|
1177 |
+
return euler(n) / factorial(n) * x**(n)
|
1178 |
+
|
1179 |
+
def _eval_rewrite_as_cos(self, arg, **kwargs):
|
1180 |
+
return 1 / cos(I * arg)
|
1181 |
+
|
1182 |
+
def _eval_rewrite_as_sec(self, arg, **kwargs):
|
1183 |
+
return sec(I * arg)
|
1184 |
+
|
1185 |
+
def _eval_rewrite_as_sinh(self, arg, **kwargs):
|
1186 |
+
return I / sinh(arg + I * pi /2)
|
1187 |
+
|
1188 |
+
def _eval_rewrite_as_cosh(self, arg, **kwargs):
|
1189 |
+
return 1 / cosh(arg)
|
1190 |
+
|
1191 |
+
def _eval_is_positive(self):
|
1192 |
+
if self.args[0].is_extended_real:
|
1193 |
+
return True
|
1194 |
+
|
1195 |
+
|
1196 |
+
###############################################################################
|
1197 |
+
############################# HYPERBOLIC INVERSES #############################
|
1198 |
+
###############################################################################
|
1199 |
+
|
1200 |
+
class InverseHyperbolicFunction(Function):
|
1201 |
+
"""Base class for inverse hyperbolic functions."""
|
1202 |
+
|
1203 |
+
pass
|
1204 |
+
|
1205 |
+
|
1206 |
+
class asinh(InverseHyperbolicFunction):
|
1207 |
+
"""
|
1208 |
+
``asinh(x)`` is the inverse hyperbolic sine of ``x``.
|
1209 |
+
|
1210 |
+
The inverse hyperbolic sine function.
|
1211 |
+
|
1212 |
+
Examples
|
1213 |
+
========
|
1214 |
+
|
1215 |
+
>>> from sympy import asinh
|
1216 |
+
>>> from sympy.abc import x
|
1217 |
+
>>> asinh(x).diff(x)
|
1218 |
+
1/sqrt(x**2 + 1)
|
1219 |
+
>>> asinh(1)
|
1220 |
+
log(1 + sqrt(2))
|
1221 |
+
|
1222 |
+
See Also
|
1223 |
+
========
|
1224 |
+
|
1225 |
+
acosh, atanh, sinh
|
1226 |
+
"""
|
1227 |
+
|
1228 |
+
def fdiff(self, argindex=1):
|
1229 |
+
if argindex == 1:
|
1230 |
+
return 1/sqrt(self.args[0]**2 + 1)
|
1231 |
+
else:
|
1232 |
+
raise ArgumentIndexError(self, argindex)
|
1233 |
+
|
1234 |
+
@classmethod
|
1235 |
+
def eval(cls, arg):
|
1236 |
+
if arg.is_Number:
|
1237 |
+
if arg is S.NaN:
|
1238 |
+
return S.NaN
|
1239 |
+
elif arg is S.Infinity:
|
1240 |
+
return S.Infinity
|
1241 |
+
elif arg is S.NegativeInfinity:
|
1242 |
+
return S.NegativeInfinity
|
1243 |
+
elif arg.is_zero:
|
1244 |
+
return S.Zero
|
1245 |
+
elif arg is S.One:
|
1246 |
+
return log(sqrt(2) + 1)
|
1247 |
+
elif arg is S.NegativeOne:
|
1248 |
+
return log(sqrt(2) - 1)
|
1249 |
+
elif arg.is_negative:
|
1250 |
+
return -cls(-arg)
|
1251 |
+
else:
|
1252 |
+
if arg is S.ComplexInfinity:
|
1253 |
+
return S.ComplexInfinity
|
1254 |
+
|
1255 |
+
if arg.is_zero:
|
1256 |
+
return S.Zero
|
1257 |
+
|
1258 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
1259 |
+
|
1260 |
+
if i_coeff is not None:
|
1261 |
+
return I * asin(i_coeff)
|
1262 |
+
else:
|
1263 |
+
if arg.could_extract_minus_sign():
|
1264 |
+
return -cls(-arg)
|
1265 |
+
|
1266 |
+
if isinstance(arg, sinh) and arg.args[0].is_number:
|
1267 |
+
z = arg.args[0]
|
1268 |
+
if z.is_real:
|
1269 |
+
return z
|
1270 |
+
r, i = match_real_imag(z)
|
1271 |
+
if r is not None and i is not None:
|
1272 |
+
f = floor((i + pi/2)/pi)
|
1273 |
+
m = z - I*pi*f
|
1274 |
+
even = f.is_even
|
1275 |
+
if even is True:
|
1276 |
+
return m
|
1277 |
+
elif even is False:
|
1278 |
+
return -m
|
1279 |
+
|
1280 |
+
@staticmethod
|
1281 |
+
@cacheit
|
1282 |
+
def taylor_term(n, x, *previous_terms):
|
1283 |
+
if n < 0 or n % 2 == 0:
|
1284 |
+
return S.Zero
|
1285 |
+
else:
|
1286 |
+
x = sympify(x)
|
1287 |
+
if len(previous_terms) >= 2 and n > 2:
|
1288 |
+
p = previous_terms[-2]
|
1289 |
+
return -p * (n - 2)**2/(n*(n - 1)) * x**2
|
1290 |
+
else:
|
1291 |
+
k = (n - 1) // 2
|
1292 |
+
R = RisingFactorial(S.Half, k)
|
1293 |
+
F = factorial(k)
|
1294 |
+
return S.NegativeOne**k * R / F * x**n / n
|
1295 |
+
|
1296 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0): # asinh
|
1297 |
+
arg = self.args[0]
|
1298 |
+
x0 = arg.subs(x, 0).cancel()
|
1299 |
+
if x0.is_zero:
|
1300 |
+
return arg.as_leading_term(x)
|
1301 |
+
# Handling branch points
|
1302 |
+
if x0 in (-I, I, S.ComplexInfinity):
|
1303 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
1304 |
+
# Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo)
|
1305 |
+
if (1 + x0**2).is_negative:
|
1306 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
1307 |
+
if re(ndir).is_positive:
|
1308 |
+
if im(x0).is_negative:
|
1309 |
+
return -self.func(x0) - I*pi
|
1310 |
+
elif re(ndir).is_negative:
|
1311 |
+
if im(x0).is_positive:
|
1312 |
+
return -self.func(x0) + I*pi
|
1313 |
+
else:
|
1314 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
1315 |
+
return self.func(x0)
|
1316 |
+
|
1317 |
+
def _eval_nseries(self, x, n, logx, cdir=0): # asinh
|
1318 |
+
arg = self.args[0]
|
1319 |
+
arg0 = arg.subs(x, 0)
|
1320 |
+
|
1321 |
+
# Handling branch points
|
1322 |
+
if arg0 in (I, -I):
|
1323 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
1324 |
+
|
1325 |
+
res = Function._eval_nseries(self, x, n=n, logx=logx)
|
1326 |
+
if arg0 is S.ComplexInfinity:
|
1327 |
+
return res
|
1328 |
+
|
1329 |
+
# Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo)
|
1330 |
+
if (1 + arg0**2).is_negative:
|
1331 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
1332 |
+
if re(ndir).is_positive:
|
1333 |
+
if im(arg0).is_negative:
|
1334 |
+
return -res - I*pi
|
1335 |
+
elif re(ndir).is_negative:
|
1336 |
+
if im(arg0).is_positive:
|
1337 |
+
return -res + I*pi
|
1338 |
+
else:
|
1339 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
1340 |
+
return res
|
1341 |
+
|
1342 |
+
def _eval_rewrite_as_log(self, x, **kwargs):
|
1343 |
+
return log(x + sqrt(x**2 + 1))
|
1344 |
+
|
1345 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
1346 |
+
|
1347 |
+
def _eval_rewrite_as_atanh(self, x, **kwargs):
|
1348 |
+
return atanh(x/sqrt(1 + x**2))
|
1349 |
+
|
1350 |
+
def _eval_rewrite_as_acosh(self, x, **kwargs):
|
1351 |
+
ix = I*x
|
1352 |
+
return I*(sqrt(1 - ix)/sqrt(ix - 1) * acosh(ix) - pi/2)
|
1353 |
+
|
1354 |
+
def _eval_rewrite_as_asin(self, x, **kwargs):
|
1355 |
+
return -I * asin(I * x)
|
1356 |
+
|
1357 |
+
def _eval_rewrite_as_acos(self, x, **kwargs):
|
1358 |
+
return I * acos(I * x) - I*pi/2
|
1359 |
+
|
1360 |
+
def inverse(self, argindex=1):
|
1361 |
+
"""
|
1362 |
+
Returns the inverse of this function.
|
1363 |
+
"""
|
1364 |
+
return sinh
|
1365 |
+
|
1366 |
+
def _eval_is_zero(self):
|
1367 |
+
return self.args[0].is_zero
|
1368 |
+
|
1369 |
+
|
1370 |
+
class acosh(InverseHyperbolicFunction):
|
1371 |
+
"""
|
1372 |
+
``acosh(x)`` is the inverse hyperbolic cosine of ``x``.
|
1373 |
+
|
1374 |
+
The inverse hyperbolic cosine function.
|
1375 |
+
|
1376 |
+
Examples
|
1377 |
+
========
|
1378 |
+
|
1379 |
+
>>> from sympy import acosh
|
1380 |
+
>>> from sympy.abc import x
|
1381 |
+
>>> acosh(x).diff(x)
|
1382 |
+
1/(sqrt(x - 1)*sqrt(x + 1))
|
1383 |
+
>>> acosh(1)
|
1384 |
+
0
|
1385 |
+
|
1386 |
+
See Also
|
1387 |
+
========
|
1388 |
+
|
1389 |
+
asinh, atanh, cosh
|
1390 |
+
"""
|
1391 |
+
|
1392 |
+
def fdiff(self, argindex=1):
|
1393 |
+
if argindex == 1:
|
1394 |
+
arg = self.args[0]
|
1395 |
+
return 1/(sqrt(arg - 1)*sqrt(arg + 1))
|
1396 |
+
else:
|
1397 |
+
raise ArgumentIndexError(self, argindex)
|
1398 |
+
|
1399 |
+
@classmethod
|
1400 |
+
def eval(cls, arg):
|
1401 |
+
if arg.is_Number:
|
1402 |
+
if arg is S.NaN:
|
1403 |
+
return S.NaN
|
1404 |
+
elif arg is S.Infinity:
|
1405 |
+
return S.Infinity
|
1406 |
+
elif arg is S.NegativeInfinity:
|
1407 |
+
return S.Infinity
|
1408 |
+
elif arg.is_zero:
|
1409 |
+
return pi*I / 2
|
1410 |
+
elif arg is S.One:
|
1411 |
+
return S.Zero
|
1412 |
+
elif arg is S.NegativeOne:
|
1413 |
+
return pi*I
|
1414 |
+
|
1415 |
+
if arg.is_number:
|
1416 |
+
cst_table = _acosh_table()
|
1417 |
+
|
1418 |
+
if arg in cst_table:
|
1419 |
+
if arg.is_extended_real:
|
1420 |
+
return cst_table[arg]*I
|
1421 |
+
return cst_table[arg]
|
1422 |
+
|
1423 |
+
if arg is S.ComplexInfinity:
|
1424 |
+
return S.ComplexInfinity
|
1425 |
+
if arg == I*S.Infinity:
|
1426 |
+
return S.Infinity + I*pi/2
|
1427 |
+
if arg == -I*S.Infinity:
|
1428 |
+
return S.Infinity - I*pi/2
|
1429 |
+
|
1430 |
+
if arg.is_zero:
|
1431 |
+
return pi*I*S.Half
|
1432 |
+
|
1433 |
+
if isinstance(arg, cosh) and arg.args[0].is_number:
|
1434 |
+
z = arg.args[0]
|
1435 |
+
if z.is_real:
|
1436 |
+
return Abs(z)
|
1437 |
+
r, i = match_real_imag(z)
|
1438 |
+
if r is not None and i is not None:
|
1439 |
+
f = floor(i/pi)
|
1440 |
+
m = z - I*pi*f
|
1441 |
+
even = f.is_even
|
1442 |
+
if even is True:
|
1443 |
+
if r.is_nonnegative:
|
1444 |
+
return m
|
1445 |
+
elif r.is_negative:
|
1446 |
+
return -m
|
1447 |
+
elif even is False:
|
1448 |
+
m -= I*pi
|
1449 |
+
if r.is_nonpositive:
|
1450 |
+
return -m
|
1451 |
+
elif r.is_positive:
|
1452 |
+
return m
|
1453 |
+
|
1454 |
+
@staticmethod
|
1455 |
+
@cacheit
|
1456 |
+
def taylor_term(n, x, *previous_terms):
|
1457 |
+
if n == 0:
|
1458 |
+
return I*pi/2
|
1459 |
+
elif n < 0 or n % 2 == 0:
|
1460 |
+
return S.Zero
|
1461 |
+
else:
|
1462 |
+
x = sympify(x)
|
1463 |
+
if len(previous_terms) >= 2 and n > 2:
|
1464 |
+
p = previous_terms[-2]
|
1465 |
+
return p * (n - 2)**2/(n*(n - 1)) * x**2
|
1466 |
+
else:
|
1467 |
+
k = (n - 1) // 2
|
1468 |
+
R = RisingFactorial(S.Half, k)
|
1469 |
+
F = factorial(k)
|
1470 |
+
return -R / F * I * x**n / n
|
1471 |
+
|
1472 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0): # acosh
|
1473 |
+
arg = self.args[0]
|
1474 |
+
x0 = arg.subs(x, 0).cancel()
|
1475 |
+
# Handling branch points
|
1476 |
+
if x0 in (-S.One, S.Zero, S.One, S.ComplexInfinity):
|
1477 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
1478 |
+
# Handling points lying on branch cuts (-oo, 1)
|
1479 |
+
if (x0 - 1).is_negative:
|
1480 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
1481 |
+
if im(ndir).is_negative:
|
1482 |
+
if (x0 + 1).is_negative:
|
1483 |
+
return self.func(x0) - 2*I*pi
|
1484 |
+
return -self.func(x0)
|
1485 |
+
elif not im(ndir).is_positive:
|
1486 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
1487 |
+
return self.func(x0)
|
1488 |
+
|
1489 |
+
def _eval_nseries(self, x, n, logx, cdir=0): # acosh
|
1490 |
+
arg = self.args[0]
|
1491 |
+
arg0 = arg.subs(x, 0)
|
1492 |
+
|
1493 |
+
# Handling branch points
|
1494 |
+
if arg0 in (S.One, S.NegativeOne):
|
1495 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
1496 |
+
|
1497 |
+
res = Function._eval_nseries(self, x, n=n, logx=logx)
|
1498 |
+
if arg0 is S.ComplexInfinity:
|
1499 |
+
return res
|
1500 |
+
|
1501 |
+
# Handling points lying on branch cuts (-oo, 1)
|
1502 |
+
if (arg0 - 1).is_negative:
|
1503 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
1504 |
+
if im(ndir).is_negative:
|
1505 |
+
if (arg0 + 1).is_negative:
|
1506 |
+
return res - 2*I*pi
|
1507 |
+
return -res
|
1508 |
+
elif not im(ndir).is_positive:
|
1509 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
1510 |
+
return res
|
1511 |
+
|
1512 |
+
def _eval_rewrite_as_log(self, x, **kwargs):
|
1513 |
+
return log(x + sqrt(x + 1) * sqrt(x - 1))
|
1514 |
+
|
1515 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
1516 |
+
|
1517 |
+
def _eval_rewrite_as_acos(self, x, **kwargs):
|
1518 |
+
return sqrt(x - 1)/sqrt(1 - x) * acos(x)
|
1519 |
+
|
1520 |
+
def _eval_rewrite_as_asin(self, x, **kwargs):
|
1521 |
+
return sqrt(x - 1)/sqrt(1 - x) * (pi/2 - asin(x))
|
1522 |
+
|
1523 |
+
def _eval_rewrite_as_asinh(self, x, **kwargs):
|
1524 |
+
return sqrt(x - 1)/sqrt(1 - x) * (pi/2 + I*asinh(I*x))
|
1525 |
+
|
1526 |
+
def _eval_rewrite_as_atanh(self, x, **kwargs):
|
1527 |
+
sxm1 = sqrt(x - 1)
|
1528 |
+
s1mx = sqrt(1 - x)
|
1529 |
+
sx2m1 = sqrt(x**2 - 1)
|
1530 |
+
return (pi/2*sxm1/s1mx*(1 - x * sqrt(1/x**2)) +
|
1531 |
+
sxm1*sqrt(x + 1)/sx2m1 * atanh(sx2m1/x))
|
1532 |
+
|
1533 |
+
def inverse(self, argindex=1):
|
1534 |
+
"""
|
1535 |
+
Returns the inverse of this function.
|
1536 |
+
"""
|
1537 |
+
return cosh
|
1538 |
+
|
1539 |
+
def _eval_is_zero(self):
|
1540 |
+
if (self.args[0] - 1).is_zero:
|
1541 |
+
return True
|
1542 |
+
|
1543 |
+
|
1544 |
+
class atanh(InverseHyperbolicFunction):
|
1545 |
+
"""
|
1546 |
+
``atanh(x)`` is the inverse hyperbolic tangent of ``x``.
|
1547 |
+
|
1548 |
+
The inverse hyperbolic tangent function.
|
1549 |
+
|
1550 |
+
Examples
|
1551 |
+
========
|
1552 |
+
|
1553 |
+
>>> from sympy import atanh
|
1554 |
+
>>> from sympy.abc import x
|
1555 |
+
>>> atanh(x).diff(x)
|
1556 |
+
1/(1 - x**2)
|
1557 |
+
|
1558 |
+
See Also
|
1559 |
+
========
|
1560 |
+
|
1561 |
+
asinh, acosh, tanh
|
1562 |
+
"""
|
1563 |
+
|
1564 |
+
def fdiff(self, argindex=1):
|
1565 |
+
if argindex == 1:
|
1566 |
+
return 1/(1 - self.args[0]**2)
|
1567 |
+
else:
|
1568 |
+
raise ArgumentIndexError(self, argindex)
|
1569 |
+
|
1570 |
+
@classmethod
|
1571 |
+
def eval(cls, arg):
|
1572 |
+
if arg.is_Number:
|
1573 |
+
if arg is S.NaN:
|
1574 |
+
return S.NaN
|
1575 |
+
elif arg.is_zero:
|
1576 |
+
return S.Zero
|
1577 |
+
elif arg is S.One:
|
1578 |
+
return S.Infinity
|
1579 |
+
elif arg is S.NegativeOne:
|
1580 |
+
return S.NegativeInfinity
|
1581 |
+
elif arg is S.Infinity:
|
1582 |
+
return -I * atan(arg)
|
1583 |
+
elif arg is S.NegativeInfinity:
|
1584 |
+
return I * atan(-arg)
|
1585 |
+
elif arg.is_negative:
|
1586 |
+
return -cls(-arg)
|
1587 |
+
else:
|
1588 |
+
if arg is S.ComplexInfinity:
|
1589 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
1590 |
+
return I*AccumBounds(-pi/2, pi/2)
|
1591 |
+
|
1592 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
1593 |
+
|
1594 |
+
if i_coeff is not None:
|
1595 |
+
return I * atan(i_coeff)
|
1596 |
+
else:
|
1597 |
+
if arg.could_extract_minus_sign():
|
1598 |
+
return -cls(-arg)
|
1599 |
+
|
1600 |
+
if arg.is_zero:
|
1601 |
+
return S.Zero
|
1602 |
+
|
1603 |
+
if isinstance(arg, tanh) and arg.args[0].is_number:
|
1604 |
+
z = arg.args[0]
|
1605 |
+
if z.is_real:
|
1606 |
+
return z
|
1607 |
+
r, i = match_real_imag(z)
|
1608 |
+
if r is not None and i is not None:
|
1609 |
+
f = floor(2*i/pi)
|
1610 |
+
even = f.is_even
|
1611 |
+
m = z - I*f*pi/2
|
1612 |
+
if even is True:
|
1613 |
+
return m
|
1614 |
+
elif even is False:
|
1615 |
+
return m - I*pi/2
|
1616 |
+
|
1617 |
+
@staticmethod
|
1618 |
+
@cacheit
|
1619 |
+
def taylor_term(n, x, *previous_terms):
|
1620 |
+
if n < 0 or n % 2 == 0:
|
1621 |
+
return S.Zero
|
1622 |
+
else:
|
1623 |
+
x = sympify(x)
|
1624 |
+
return x**n / n
|
1625 |
+
|
1626 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0): # atanh
|
1627 |
+
arg = self.args[0]
|
1628 |
+
x0 = arg.subs(x, 0).cancel()
|
1629 |
+
if x0.is_zero:
|
1630 |
+
return arg.as_leading_term(x)
|
1631 |
+
# Handling branch points
|
1632 |
+
if x0 in (-S.One, S.One, S.ComplexInfinity):
|
1633 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
1634 |
+
# Handling points lying on branch cuts (-oo, -1] U [1, oo)
|
1635 |
+
if (1 - x0**2).is_negative:
|
1636 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
1637 |
+
if im(ndir).is_negative:
|
1638 |
+
if x0.is_negative:
|
1639 |
+
return self.func(x0) - I*pi
|
1640 |
+
elif im(ndir).is_positive:
|
1641 |
+
if x0.is_positive:
|
1642 |
+
return self.func(x0) + I*pi
|
1643 |
+
else:
|
1644 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
1645 |
+
return self.func(x0)
|
1646 |
+
|
1647 |
+
def _eval_nseries(self, x, n, logx, cdir=0): # atanh
|
1648 |
+
arg = self.args[0]
|
1649 |
+
arg0 = arg.subs(x, 0)
|
1650 |
+
|
1651 |
+
# Handling branch points
|
1652 |
+
if arg0 in (S.One, S.NegativeOne):
|
1653 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
1654 |
+
|
1655 |
+
res = Function._eval_nseries(self, x, n=n, logx=logx)
|
1656 |
+
if arg0 is S.ComplexInfinity:
|
1657 |
+
return res
|
1658 |
+
|
1659 |
+
# Handling points lying on branch cuts (-oo, -1] U [1, oo)
|
1660 |
+
if (1 - arg0**2).is_negative:
|
1661 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
1662 |
+
if im(ndir).is_negative:
|
1663 |
+
if arg0.is_negative:
|
1664 |
+
return res - I*pi
|
1665 |
+
elif im(ndir).is_positive:
|
1666 |
+
if arg0.is_positive:
|
1667 |
+
return res + I*pi
|
1668 |
+
else:
|
1669 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
1670 |
+
return res
|
1671 |
+
|
1672 |
+
def _eval_rewrite_as_log(self, x, **kwargs):
|
1673 |
+
return (log(1 + x) - log(1 - x)) / 2
|
1674 |
+
|
1675 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
1676 |
+
|
1677 |
+
def _eval_rewrite_as_asinh(self, x, **kwargs):
|
1678 |
+
f = sqrt(1/(x**2 - 1))
|
1679 |
+
return (pi*x/(2*sqrt(-x**2)) -
|
1680 |
+
sqrt(-x)*sqrt(1 - x**2)/sqrt(x)*f*asinh(f))
|
1681 |
+
|
1682 |
+
def _eval_is_zero(self):
|
1683 |
+
if self.args[0].is_zero:
|
1684 |
+
return True
|
1685 |
+
|
1686 |
+
def _eval_is_imaginary(self):
|
1687 |
+
return self.args[0].is_imaginary
|
1688 |
+
|
1689 |
+
def inverse(self, argindex=1):
|
1690 |
+
"""
|
1691 |
+
Returns the inverse of this function.
|
1692 |
+
"""
|
1693 |
+
return tanh
|
1694 |
+
|
1695 |
+
|
1696 |
+
class acoth(InverseHyperbolicFunction):
|
1697 |
+
"""
|
1698 |
+
``acoth(x)`` is the inverse hyperbolic cotangent of ``x``.
|
1699 |
+
|
1700 |
+
The inverse hyperbolic cotangent function.
|
1701 |
+
|
1702 |
+
Examples
|
1703 |
+
========
|
1704 |
+
|
1705 |
+
>>> from sympy import acoth
|
1706 |
+
>>> from sympy.abc import x
|
1707 |
+
>>> acoth(x).diff(x)
|
1708 |
+
1/(1 - x**2)
|
1709 |
+
|
1710 |
+
See Also
|
1711 |
+
========
|
1712 |
+
|
1713 |
+
asinh, acosh, coth
|
1714 |
+
"""
|
1715 |
+
|
1716 |
+
def fdiff(self, argindex=1):
|
1717 |
+
if argindex == 1:
|
1718 |
+
return 1/(1 - self.args[0]**2)
|
1719 |
+
else:
|
1720 |
+
raise ArgumentIndexError(self, argindex)
|
1721 |
+
|
1722 |
+
@classmethod
|
1723 |
+
def eval(cls, arg):
|
1724 |
+
if arg.is_Number:
|
1725 |
+
if arg is S.NaN:
|
1726 |
+
return S.NaN
|
1727 |
+
elif arg is S.Infinity:
|
1728 |
+
return S.Zero
|
1729 |
+
elif arg is S.NegativeInfinity:
|
1730 |
+
return S.Zero
|
1731 |
+
elif arg.is_zero:
|
1732 |
+
return pi*I / 2
|
1733 |
+
elif arg is S.One:
|
1734 |
+
return S.Infinity
|
1735 |
+
elif arg is S.NegativeOne:
|
1736 |
+
return S.NegativeInfinity
|
1737 |
+
elif arg.is_negative:
|
1738 |
+
return -cls(-arg)
|
1739 |
+
else:
|
1740 |
+
if arg is S.ComplexInfinity:
|
1741 |
+
return S.Zero
|
1742 |
+
|
1743 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
1744 |
+
|
1745 |
+
if i_coeff is not None:
|
1746 |
+
return -I * acot(i_coeff)
|
1747 |
+
else:
|
1748 |
+
if arg.could_extract_minus_sign():
|
1749 |
+
return -cls(-arg)
|
1750 |
+
|
1751 |
+
if arg.is_zero:
|
1752 |
+
return pi*I*S.Half
|
1753 |
+
|
1754 |
+
@staticmethod
|
1755 |
+
@cacheit
|
1756 |
+
def taylor_term(n, x, *previous_terms):
|
1757 |
+
if n == 0:
|
1758 |
+
return -I*pi/2
|
1759 |
+
elif n < 0 or n % 2 == 0:
|
1760 |
+
return S.Zero
|
1761 |
+
else:
|
1762 |
+
x = sympify(x)
|
1763 |
+
return x**n / n
|
1764 |
+
|
1765 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0): # acoth
|
1766 |
+
arg = self.args[0]
|
1767 |
+
x0 = arg.subs(x, 0).cancel()
|
1768 |
+
if x0 is S.ComplexInfinity:
|
1769 |
+
return (1/arg).as_leading_term(x)
|
1770 |
+
# Handling branch points
|
1771 |
+
if x0 in (-S.One, S.One, S.Zero):
|
1772 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
1773 |
+
# Handling points lying on branch cuts [-1, 1]
|
1774 |
+
if x0.is_real and (1 - x0**2).is_positive:
|
1775 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
1776 |
+
if im(ndir).is_negative:
|
1777 |
+
if x0.is_positive:
|
1778 |
+
return self.func(x0) + I*pi
|
1779 |
+
elif im(ndir).is_positive:
|
1780 |
+
if x0.is_negative:
|
1781 |
+
return self.func(x0) - I*pi
|
1782 |
+
else:
|
1783 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
1784 |
+
return self.func(x0)
|
1785 |
+
|
1786 |
+
def _eval_nseries(self, x, n, logx, cdir=0): # acoth
|
1787 |
+
arg = self.args[0]
|
1788 |
+
arg0 = arg.subs(x, 0)
|
1789 |
+
|
1790 |
+
# Handling branch points
|
1791 |
+
if arg0 in (S.One, S.NegativeOne):
|
1792 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
1793 |
+
|
1794 |
+
res = Function._eval_nseries(self, x, n=n, logx=logx)
|
1795 |
+
if arg0 is S.ComplexInfinity:
|
1796 |
+
return res
|
1797 |
+
|
1798 |
+
# Handling points lying on branch cuts [-1, 1]
|
1799 |
+
if arg0.is_real and (1 - arg0**2).is_positive:
|
1800 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
1801 |
+
if im(ndir).is_negative:
|
1802 |
+
if arg0.is_positive:
|
1803 |
+
return res + I*pi
|
1804 |
+
elif im(ndir).is_positive:
|
1805 |
+
if arg0.is_negative:
|
1806 |
+
return res - I*pi
|
1807 |
+
else:
|
1808 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
1809 |
+
return res
|
1810 |
+
|
1811 |
+
def _eval_rewrite_as_log(self, x, **kwargs):
|
1812 |
+
return (log(1 + 1/x) - log(1 - 1/x)) / 2
|
1813 |
+
|
1814 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
1815 |
+
|
1816 |
+
def _eval_rewrite_as_atanh(self, x, **kwargs):
|
1817 |
+
return atanh(1/x)
|
1818 |
+
|
1819 |
+
def _eval_rewrite_as_asinh(self, x, **kwargs):
|
1820 |
+
return (pi*I/2*(sqrt((x - 1)/x)*sqrt(x/(x - 1)) - sqrt(1 + 1/x)*sqrt(x/(x + 1))) +
|
1821 |
+
x*sqrt(1/x**2)*asinh(sqrt(1/(x**2 - 1))))
|
1822 |
+
|
1823 |
+
def inverse(self, argindex=1):
|
1824 |
+
"""
|
1825 |
+
Returns the inverse of this function.
|
1826 |
+
"""
|
1827 |
+
return coth
|
1828 |
+
|
1829 |
+
|
1830 |
+
class asech(InverseHyperbolicFunction):
|
1831 |
+
"""
|
1832 |
+
``asech(x)`` is the inverse hyperbolic secant of ``x``.
|
1833 |
+
|
1834 |
+
The inverse hyperbolic secant function.
|
1835 |
+
|
1836 |
+
Examples
|
1837 |
+
========
|
1838 |
+
|
1839 |
+
>>> from sympy import asech, sqrt, S
|
1840 |
+
>>> from sympy.abc import x
|
1841 |
+
>>> asech(x).diff(x)
|
1842 |
+
-1/(x*sqrt(1 - x**2))
|
1843 |
+
>>> asech(1).diff(x)
|
1844 |
+
0
|
1845 |
+
>>> asech(1)
|
1846 |
+
0
|
1847 |
+
>>> asech(S(2))
|
1848 |
+
I*pi/3
|
1849 |
+
>>> asech(-sqrt(2))
|
1850 |
+
3*I*pi/4
|
1851 |
+
>>> asech((sqrt(6) - sqrt(2)))
|
1852 |
+
I*pi/12
|
1853 |
+
|
1854 |
+
See Also
|
1855 |
+
========
|
1856 |
+
|
1857 |
+
asinh, atanh, cosh, acoth
|
1858 |
+
|
1859 |
+
References
|
1860 |
+
==========
|
1861 |
+
|
1862 |
+
.. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
|
1863 |
+
.. [2] https://dlmf.nist.gov/4.37
|
1864 |
+
.. [3] https://functions.wolfram.com/ElementaryFunctions/ArcSech/
|
1865 |
+
|
1866 |
+
"""
|
1867 |
+
|
1868 |
+
def fdiff(self, argindex=1):
|
1869 |
+
if argindex == 1:
|
1870 |
+
z = self.args[0]
|
1871 |
+
return -1/(z*sqrt(1 - z**2))
|
1872 |
+
else:
|
1873 |
+
raise ArgumentIndexError(self, argindex)
|
1874 |
+
|
1875 |
+
@classmethod
|
1876 |
+
def eval(cls, arg):
|
1877 |
+
if arg.is_Number:
|
1878 |
+
if arg is S.NaN:
|
1879 |
+
return S.NaN
|
1880 |
+
elif arg is S.Infinity:
|
1881 |
+
return pi*I / 2
|
1882 |
+
elif arg is S.NegativeInfinity:
|
1883 |
+
return pi*I / 2
|
1884 |
+
elif arg.is_zero:
|
1885 |
+
return S.Infinity
|
1886 |
+
elif arg is S.One:
|
1887 |
+
return S.Zero
|
1888 |
+
elif arg is S.NegativeOne:
|
1889 |
+
return pi*I
|
1890 |
+
|
1891 |
+
if arg.is_number:
|
1892 |
+
cst_table = _asech_table()
|
1893 |
+
|
1894 |
+
if arg in cst_table:
|
1895 |
+
if arg.is_extended_real:
|
1896 |
+
return cst_table[arg]*I
|
1897 |
+
return cst_table[arg]
|
1898 |
+
|
1899 |
+
if arg is S.ComplexInfinity:
|
1900 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
1901 |
+
return I*AccumBounds(-pi/2, pi/2)
|
1902 |
+
|
1903 |
+
if arg.is_zero:
|
1904 |
+
return S.Infinity
|
1905 |
+
|
1906 |
+
@staticmethod
|
1907 |
+
@cacheit
|
1908 |
+
def taylor_term(n, x, *previous_terms):
|
1909 |
+
if n == 0:
|
1910 |
+
return log(2 / x)
|
1911 |
+
elif n < 0 or n % 2 == 1:
|
1912 |
+
return S.Zero
|
1913 |
+
else:
|
1914 |
+
x = sympify(x)
|
1915 |
+
if len(previous_terms) > 2 and n > 2:
|
1916 |
+
p = previous_terms[-2]
|
1917 |
+
return p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2)
|
1918 |
+
else:
|
1919 |
+
k = n // 2
|
1920 |
+
R = RisingFactorial(S.Half, k) * n
|
1921 |
+
F = factorial(k) * n // 2 * n // 2
|
1922 |
+
return -1 * R / F * x**n / 4
|
1923 |
+
|
1924 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0): # asech
|
1925 |
+
arg = self.args[0]
|
1926 |
+
x0 = arg.subs(x, 0).cancel()
|
1927 |
+
# Handling branch points
|
1928 |
+
if x0 in (-S.One, S.Zero, S.One, S.ComplexInfinity):
|
1929 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
1930 |
+
# Handling points lying on branch cuts (-oo, 0] U (1, oo)
|
1931 |
+
if x0.is_negative or (1 - x0).is_negative:
|
1932 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
1933 |
+
if im(ndir).is_positive:
|
1934 |
+
if x0.is_positive or (x0 + 1).is_negative:
|
1935 |
+
return -self.func(x0)
|
1936 |
+
return self.func(x0) - 2*I*pi
|
1937 |
+
elif not im(ndir).is_negative:
|
1938 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
1939 |
+
return self.func(x0)
|
1940 |
+
|
1941 |
+
def _eval_nseries(self, x, n, logx, cdir=0): # asech
|
1942 |
+
from sympy.series.order import O
|
1943 |
+
arg = self.args[0]
|
1944 |
+
arg0 = arg.subs(x, 0)
|
1945 |
+
|
1946 |
+
# Handling branch points
|
1947 |
+
if arg0 is S.One:
|
1948 |
+
t = Dummy('t', positive=True)
|
1949 |
+
ser = asech(S.One - t**2).rewrite(log).nseries(t, 0, 2*n)
|
1950 |
+
arg1 = S.One - self.args[0]
|
1951 |
+
f = arg1.as_leading_term(x)
|
1952 |
+
g = (arg1 - f)/ f
|
1953 |
+
if not g.is_meromorphic(x, 0): # cannot be expanded
|
1954 |
+
return O(1) if n == 0 else O(sqrt(x))
|
1955 |
+
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
|
1956 |
+
res = (res1.removeO()*sqrt(f)).expand()
|
1957 |
+
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
|
1958 |
+
|
1959 |
+
if arg0 is S.NegativeOne:
|
1960 |
+
t = Dummy('t', positive=True)
|
1961 |
+
ser = asech(S.NegativeOne + t**2).rewrite(log).nseries(t, 0, 2*n)
|
1962 |
+
arg1 = S.One + self.args[0]
|
1963 |
+
f = arg1.as_leading_term(x)
|
1964 |
+
g = (arg1 - f)/ f
|
1965 |
+
if not g.is_meromorphic(x, 0): # cannot be expanded
|
1966 |
+
return O(1) if n == 0 else I*pi + O(sqrt(x))
|
1967 |
+
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
|
1968 |
+
res = (res1.removeO()*sqrt(f)).expand()
|
1969 |
+
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
|
1970 |
+
|
1971 |
+
res = Function._eval_nseries(self, x, n=n, logx=logx)
|
1972 |
+
if arg0 is S.ComplexInfinity:
|
1973 |
+
return res
|
1974 |
+
|
1975 |
+
# Handling points lying on branch cuts (-oo, 0] U (1, oo)
|
1976 |
+
if arg0.is_negative or (1 - arg0).is_negative:
|
1977 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
1978 |
+
if im(ndir).is_positive:
|
1979 |
+
if arg0.is_positive or (arg0 + 1).is_negative:
|
1980 |
+
return -res
|
1981 |
+
return res - 2*I*pi
|
1982 |
+
elif not im(ndir).is_negative:
|
1983 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
1984 |
+
return res
|
1985 |
+
|
1986 |
+
def inverse(self, argindex=1):
|
1987 |
+
"""
|
1988 |
+
Returns the inverse of this function.
|
1989 |
+
"""
|
1990 |
+
return sech
|
1991 |
+
|
1992 |
+
def _eval_rewrite_as_log(self, arg, **kwargs):
|
1993 |
+
return log(1/arg + sqrt(1/arg - 1) * sqrt(1/arg + 1))
|
1994 |
+
|
1995 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
1996 |
+
|
1997 |
+
def _eval_rewrite_as_acosh(self, arg, **kwargs):
|
1998 |
+
return acosh(1/arg)
|
1999 |
+
|
2000 |
+
def _eval_rewrite_as_asinh(self, arg, **kwargs):
|
2001 |
+
return sqrt(1/arg - 1)/sqrt(1 - 1/arg)*(I*asinh(I/arg)
|
2002 |
+
+ pi*S.Half)
|
2003 |
+
|
2004 |
+
def _eval_rewrite_as_atanh(self, x, **kwargs):
|
2005 |
+
return (I*pi*(1 - sqrt(x)*sqrt(1/x) - I/2*sqrt(-x)/sqrt(x) - I/2*sqrt(x**2)/sqrt(-x**2))
|
2006 |
+
+ sqrt(1/(x + 1))*sqrt(x + 1)*atanh(sqrt(1 - x**2)))
|
2007 |
+
|
2008 |
+
def _eval_rewrite_as_acsch(self, x, **kwargs):
|
2009 |
+
return sqrt(1/x - 1)/sqrt(1 - 1/x)*(pi/2 - I*acsch(I*x))
|
2010 |
+
|
2011 |
+
|
2012 |
+
class acsch(InverseHyperbolicFunction):
|
2013 |
+
"""
|
2014 |
+
``acsch(x)`` is the inverse hyperbolic cosecant of ``x``.
|
2015 |
+
|
2016 |
+
The inverse hyperbolic cosecant function.
|
2017 |
+
|
2018 |
+
Examples
|
2019 |
+
========
|
2020 |
+
|
2021 |
+
>>> from sympy import acsch, sqrt, I
|
2022 |
+
>>> from sympy.abc import x
|
2023 |
+
>>> acsch(x).diff(x)
|
2024 |
+
-1/(x**2*sqrt(1 + x**(-2)))
|
2025 |
+
>>> acsch(1).diff(x)
|
2026 |
+
0
|
2027 |
+
>>> acsch(1)
|
2028 |
+
log(1 + sqrt(2))
|
2029 |
+
>>> acsch(I)
|
2030 |
+
-I*pi/2
|
2031 |
+
>>> acsch(-2*I)
|
2032 |
+
I*pi/6
|
2033 |
+
>>> acsch(I*(sqrt(6) - sqrt(2)))
|
2034 |
+
-5*I*pi/12
|
2035 |
+
|
2036 |
+
See Also
|
2037 |
+
========
|
2038 |
+
|
2039 |
+
asinh
|
2040 |
+
|
2041 |
+
References
|
2042 |
+
==========
|
2043 |
+
|
2044 |
+
.. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
|
2045 |
+
.. [2] https://dlmf.nist.gov/4.37
|
2046 |
+
.. [3] https://functions.wolfram.com/ElementaryFunctions/ArcCsch/
|
2047 |
+
|
2048 |
+
"""
|
2049 |
+
|
2050 |
+
def fdiff(self, argindex=1):
|
2051 |
+
if argindex == 1:
|
2052 |
+
z = self.args[0]
|
2053 |
+
return -1/(z**2*sqrt(1 + 1/z**2))
|
2054 |
+
else:
|
2055 |
+
raise ArgumentIndexError(self, argindex)
|
2056 |
+
|
2057 |
+
@classmethod
|
2058 |
+
def eval(cls, arg):
|
2059 |
+
if arg.is_Number:
|
2060 |
+
if arg is S.NaN:
|
2061 |
+
return S.NaN
|
2062 |
+
elif arg is S.Infinity:
|
2063 |
+
return S.Zero
|
2064 |
+
elif arg is S.NegativeInfinity:
|
2065 |
+
return S.Zero
|
2066 |
+
elif arg.is_zero:
|
2067 |
+
return S.ComplexInfinity
|
2068 |
+
elif arg is S.One:
|
2069 |
+
return log(1 + sqrt(2))
|
2070 |
+
elif arg is S.NegativeOne:
|
2071 |
+
return - log(1 + sqrt(2))
|
2072 |
+
|
2073 |
+
if arg.is_number:
|
2074 |
+
cst_table = _acsch_table()
|
2075 |
+
|
2076 |
+
if arg in cst_table:
|
2077 |
+
return cst_table[arg]*I
|
2078 |
+
|
2079 |
+
if arg is S.ComplexInfinity:
|
2080 |
+
return S.Zero
|
2081 |
+
|
2082 |
+
if arg.is_infinite:
|
2083 |
+
return S.Zero
|
2084 |
+
|
2085 |
+
if arg.is_zero:
|
2086 |
+
return S.ComplexInfinity
|
2087 |
+
|
2088 |
+
if arg.could_extract_minus_sign():
|
2089 |
+
return -cls(-arg)
|
2090 |
+
|
2091 |
+
@staticmethod
|
2092 |
+
@cacheit
|
2093 |
+
def taylor_term(n, x, *previous_terms):
|
2094 |
+
if n == 0:
|
2095 |
+
return log(2 / x)
|
2096 |
+
elif n < 0 or n % 2 == 1:
|
2097 |
+
return S.Zero
|
2098 |
+
else:
|
2099 |
+
x = sympify(x)
|
2100 |
+
if len(previous_terms) > 2 and n > 2:
|
2101 |
+
p = previous_terms[-2]
|
2102 |
+
return -p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2)
|
2103 |
+
else:
|
2104 |
+
k = n // 2
|
2105 |
+
R = RisingFactorial(S.Half, k) * n
|
2106 |
+
F = factorial(k) * n // 2 * n // 2
|
2107 |
+
return S.NegativeOne**(k +1) * R / F * x**n / 4
|
2108 |
+
|
2109 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0): # acsch
|
2110 |
+
arg = self.args[0]
|
2111 |
+
x0 = arg.subs(x, 0).cancel()
|
2112 |
+
# Handling branch points
|
2113 |
+
if x0 in (-I, I, S.Zero):
|
2114 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
2115 |
+
if x0 is S.ComplexInfinity:
|
2116 |
+
return (1/arg).as_leading_term(x)
|
2117 |
+
# Handling points lying on branch cuts (-I, I)
|
2118 |
+
if x0.is_imaginary and (1 + x0**2).is_positive:
|
2119 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
2120 |
+
if re(ndir).is_positive:
|
2121 |
+
if im(x0).is_positive:
|
2122 |
+
return -self.func(x0) - I*pi
|
2123 |
+
elif re(ndir).is_negative:
|
2124 |
+
if im(x0).is_negative:
|
2125 |
+
return -self.func(x0) + I*pi
|
2126 |
+
else:
|
2127 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
2128 |
+
return self.func(x0)
|
2129 |
+
|
2130 |
+
def _eval_nseries(self, x, n, logx, cdir=0): # acsch
|
2131 |
+
from sympy.series.order import O
|
2132 |
+
arg = self.args[0]
|
2133 |
+
arg0 = arg.subs(x, 0)
|
2134 |
+
|
2135 |
+
# Handling branch points
|
2136 |
+
if arg0 is I:
|
2137 |
+
t = Dummy('t', positive=True)
|
2138 |
+
ser = acsch(I + t**2).rewrite(log).nseries(t, 0, 2*n)
|
2139 |
+
arg1 = -I + self.args[0]
|
2140 |
+
f = arg1.as_leading_term(x)
|
2141 |
+
g = (arg1 - f)/ f
|
2142 |
+
if not g.is_meromorphic(x, 0): # cannot be expanded
|
2143 |
+
return O(1) if n == 0 else -I*pi/2 + O(sqrt(x))
|
2144 |
+
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
|
2145 |
+
res = (res1.removeO()*sqrt(f)).expand()
|
2146 |
+
res = ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
|
2147 |
+
return res
|
2148 |
+
|
2149 |
+
if arg0 == S.NegativeOne*I:
|
2150 |
+
t = Dummy('t', positive=True)
|
2151 |
+
ser = acsch(-I + t**2).rewrite(log).nseries(t, 0, 2*n)
|
2152 |
+
arg1 = I + self.args[0]
|
2153 |
+
f = arg1.as_leading_term(x)
|
2154 |
+
g = (arg1 - f)/ f
|
2155 |
+
if not g.is_meromorphic(x, 0): # cannot be expanded
|
2156 |
+
return O(1) if n == 0 else I*pi/2 + O(sqrt(x))
|
2157 |
+
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
|
2158 |
+
res = (res1.removeO()*sqrt(f)).expand()
|
2159 |
+
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
|
2160 |
+
|
2161 |
+
res = Function._eval_nseries(self, x, n=n, logx=logx)
|
2162 |
+
if arg0 is S.ComplexInfinity:
|
2163 |
+
return res
|
2164 |
+
|
2165 |
+
# Handling points lying on branch cuts (-I, I)
|
2166 |
+
if arg0.is_imaginary and (1 + arg0**2).is_positive:
|
2167 |
+
ndir = self.args[0].dir(x, cdir if cdir else 1)
|
2168 |
+
if re(ndir).is_positive:
|
2169 |
+
if im(arg0).is_positive:
|
2170 |
+
return -res - I*pi
|
2171 |
+
elif re(ndir).is_negative:
|
2172 |
+
if im(arg0).is_negative:
|
2173 |
+
return -res + I*pi
|
2174 |
+
else:
|
2175 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
2176 |
+
return res
|
2177 |
+
|
2178 |
+
def inverse(self, argindex=1):
|
2179 |
+
"""
|
2180 |
+
Returns the inverse of this function.
|
2181 |
+
"""
|
2182 |
+
return csch
|
2183 |
+
|
2184 |
+
def _eval_rewrite_as_log(self, arg, **kwargs):
|
2185 |
+
return log(1/arg + sqrt(1/arg**2 + 1))
|
2186 |
+
|
2187 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
2188 |
+
|
2189 |
+
def _eval_rewrite_as_asinh(self, arg, **kwargs):
|
2190 |
+
return asinh(1/arg)
|
2191 |
+
|
2192 |
+
def _eval_rewrite_as_acosh(self, arg, **kwargs):
|
2193 |
+
return I*(sqrt(1 - I/arg)/sqrt(I/arg - 1)*
|
2194 |
+
acosh(I/arg) - pi*S.Half)
|
2195 |
+
|
2196 |
+
def _eval_rewrite_as_atanh(self, arg, **kwargs):
|
2197 |
+
arg2 = arg**2
|
2198 |
+
arg2p1 = arg2 + 1
|
2199 |
+
return sqrt(-arg2)/arg*(pi*S.Half -
|
2200 |
+
sqrt(-arg2p1**2)/arg2p1*atanh(sqrt(arg2p1)))
|
2201 |
+
|
2202 |
+
def _eval_is_zero(self):
|
2203 |
+
return self.args[0].is_infinite
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/integers.py
ADDED
@@ -0,0 +1,625 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
|
3 |
+
from sympy.core.basic import Basic
|
4 |
+
from sympy.core.expr import Expr
|
5 |
+
|
6 |
+
from sympy.core import Add, S
|
7 |
+
from sympy.core.evalf import get_integer_part, PrecisionExhausted
|
8 |
+
from sympy.core.function import Function
|
9 |
+
from sympy.core.logic import fuzzy_or
|
10 |
+
from sympy.core.numbers import Integer
|
11 |
+
from sympy.core.relational import Gt, Lt, Ge, Le, Relational, is_eq
|
12 |
+
from sympy.core.symbol import Symbol
|
13 |
+
from sympy.core.sympify import _sympify
|
14 |
+
from sympy.functions.elementary.complexes import im, re
|
15 |
+
from sympy.multipledispatch import dispatch
|
16 |
+
|
17 |
+
###############################################################################
|
18 |
+
######################### FLOOR and CEILING FUNCTIONS #########################
|
19 |
+
###############################################################################
|
20 |
+
|
21 |
+
|
22 |
+
class RoundFunction(Function):
|
23 |
+
"""Abstract base class for rounding functions."""
|
24 |
+
|
25 |
+
args: tTuple[Expr]
|
26 |
+
|
27 |
+
@classmethod
|
28 |
+
def eval(cls, arg):
|
29 |
+
v = cls._eval_number(arg)
|
30 |
+
if v is not None:
|
31 |
+
return v
|
32 |
+
|
33 |
+
if arg.is_integer or arg.is_finite is False:
|
34 |
+
return arg
|
35 |
+
if arg.is_imaginary or (S.ImaginaryUnit*arg).is_real:
|
36 |
+
i = im(arg)
|
37 |
+
if not i.has(S.ImaginaryUnit):
|
38 |
+
return cls(i)*S.ImaginaryUnit
|
39 |
+
return cls(arg, evaluate=False)
|
40 |
+
|
41 |
+
# Integral, numerical, symbolic part
|
42 |
+
ipart = npart = spart = S.Zero
|
43 |
+
|
44 |
+
# Extract integral (or complex integral) terms
|
45 |
+
terms = Add.make_args(arg)
|
46 |
+
|
47 |
+
for t in terms:
|
48 |
+
if t.is_integer or (t.is_imaginary and im(t).is_integer):
|
49 |
+
ipart += t
|
50 |
+
elif t.has(Symbol):
|
51 |
+
spart += t
|
52 |
+
else:
|
53 |
+
npart += t
|
54 |
+
|
55 |
+
if not (npart or spart):
|
56 |
+
return ipart
|
57 |
+
|
58 |
+
# Evaluate npart numerically if independent of spart
|
59 |
+
if npart and (
|
60 |
+
not spart or
|
61 |
+
npart.is_real and (spart.is_imaginary or (S.ImaginaryUnit*spart).is_real) or
|
62 |
+
npart.is_imaginary and spart.is_real):
|
63 |
+
try:
|
64 |
+
r, i = get_integer_part(
|
65 |
+
npart, cls._dir, {}, return_ints=True)
|
66 |
+
ipart += Integer(r) + Integer(i)*S.ImaginaryUnit
|
67 |
+
npart = S.Zero
|
68 |
+
except (PrecisionExhausted, NotImplementedError):
|
69 |
+
pass
|
70 |
+
|
71 |
+
spart += npart
|
72 |
+
if not spart:
|
73 |
+
return ipart
|
74 |
+
elif spart.is_imaginary or (S.ImaginaryUnit*spart).is_real:
|
75 |
+
return ipart + cls(im(spart), evaluate=False)*S.ImaginaryUnit
|
76 |
+
elif isinstance(spart, (floor, ceiling)):
|
77 |
+
return ipart + spart
|
78 |
+
else:
|
79 |
+
return ipart + cls(spart, evaluate=False)
|
80 |
+
|
81 |
+
@classmethod
|
82 |
+
def _eval_number(cls, arg):
|
83 |
+
raise NotImplementedError()
|
84 |
+
|
85 |
+
def _eval_is_finite(self):
|
86 |
+
return self.args[0].is_finite
|
87 |
+
|
88 |
+
def _eval_is_real(self):
|
89 |
+
return self.args[0].is_real
|
90 |
+
|
91 |
+
def _eval_is_integer(self):
|
92 |
+
return self.args[0].is_real
|
93 |
+
|
94 |
+
|
95 |
+
class floor(RoundFunction):
|
96 |
+
"""
|
97 |
+
Floor is a univariate function which returns the largest integer
|
98 |
+
value not greater than its argument. This implementation
|
99 |
+
generalizes floor to complex numbers by taking the floor of the
|
100 |
+
real and imaginary parts separately.
|
101 |
+
|
102 |
+
Examples
|
103 |
+
========
|
104 |
+
|
105 |
+
>>> from sympy import floor, E, I, S, Float, Rational
|
106 |
+
>>> floor(17)
|
107 |
+
17
|
108 |
+
>>> floor(Rational(23, 10))
|
109 |
+
2
|
110 |
+
>>> floor(2*E)
|
111 |
+
5
|
112 |
+
>>> floor(-Float(0.567))
|
113 |
+
-1
|
114 |
+
>>> floor(-I/2)
|
115 |
+
-I
|
116 |
+
>>> floor(S(5)/2 + 5*I/2)
|
117 |
+
2 + 2*I
|
118 |
+
|
119 |
+
See Also
|
120 |
+
========
|
121 |
+
|
122 |
+
sympy.functions.elementary.integers.ceiling
|
123 |
+
|
124 |
+
References
|
125 |
+
==========
|
126 |
+
|
127 |
+
.. [1] "Concrete mathematics" by Graham, pp. 87
|
128 |
+
.. [2] https://mathworld.wolfram.com/FloorFunction.html
|
129 |
+
|
130 |
+
"""
|
131 |
+
_dir = -1
|
132 |
+
|
133 |
+
@classmethod
|
134 |
+
def _eval_number(cls, arg):
|
135 |
+
if arg.is_Number:
|
136 |
+
return arg.floor()
|
137 |
+
elif any(isinstance(i, j)
|
138 |
+
for i in (arg, -arg) for j in (floor, ceiling)):
|
139 |
+
return arg
|
140 |
+
if arg.is_NumberSymbol:
|
141 |
+
return arg.approximation_interval(Integer)[0]
|
142 |
+
|
143 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
144 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
145 |
+
arg = self.args[0]
|
146 |
+
arg0 = arg.subs(x, 0)
|
147 |
+
r = self.subs(x, 0)
|
148 |
+
if arg0 is S.NaN or isinstance(arg0, AccumBounds):
|
149 |
+
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
|
150 |
+
r = floor(arg0)
|
151 |
+
if arg0.is_finite:
|
152 |
+
if arg0 == r:
|
153 |
+
ndir = arg.dir(x, cdir=cdir)
|
154 |
+
return r - 1 if ndir.is_negative else r
|
155 |
+
else:
|
156 |
+
return r
|
157 |
+
return arg.as_leading_term(x, logx=logx, cdir=cdir)
|
158 |
+
|
159 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
160 |
+
arg = self.args[0]
|
161 |
+
arg0 = arg.subs(x, 0)
|
162 |
+
r = self.subs(x, 0)
|
163 |
+
if arg0 is S.NaN:
|
164 |
+
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
|
165 |
+
r = floor(arg0)
|
166 |
+
if arg0.is_infinite:
|
167 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
168 |
+
from sympy.series.order import Order
|
169 |
+
s = arg._eval_nseries(x, n, logx, cdir)
|
170 |
+
o = Order(1, (x, 0)) if n <= 0 else AccumBounds(-1, 0)
|
171 |
+
return s + o
|
172 |
+
if arg0 == r:
|
173 |
+
ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1)
|
174 |
+
return r - 1 if ndir.is_negative else r
|
175 |
+
else:
|
176 |
+
return r
|
177 |
+
|
178 |
+
def _eval_is_negative(self):
|
179 |
+
return self.args[0].is_negative
|
180 |
+
|
181 |
+
def _eval_is_nonnegative(self):
|
182 |
+
return self.args[0].is_nonnegative
|
183 |
+
|
184 |
+
def _eval_rewrite_as_ceiling(self, arg, **kwargs):
|
185 |
+
return -ceiling(-arg)
|
186 |
+
|
187 |
+
def _eval_rewrite_as_frac(self, arg, **kwargs):
|
188 |
+
return arg - frac(arg)
|
189 |
+
|
190 |
+
def __le__(self, other):
|
191 |
+
other = S(other)
|
192 |
+
if self.args[0].is_real:
|
193 |
+
if other.is_integer:
|
194 |
+
return self.args[0] < other + 1
|
195 |
+
if other.is_number and other.is_real:
|
196 |
+
return self.args[0] < ceiling(other)
|
197 |
+
if self.args[0] == other and other.is_real:
|
198 |
+
return S.true
|
199 |
+
if other is S.Infinity and self.is_finite:
|
200 |
+
return S.true
|
201 |
+
|
202 |
+
return Le(self, other, evaluate=False)
|
203 |
+
|
204 |
+
def __ge__(self, other):
|
205 |
+
other = S(other)
|
206 |
+
if self.args[0].is_real:
|
207 |
+
if other.is_integer:
|
208 |
+
return self.args[0] >= other
|
209 |
+
if other.is_number and other.is_real:
|
210 |
+
return self.args[0] >= ceiling(other)
|
211 |
+
if self.args[0] == other and other.is_real:
|
212 |
+
return S.false
|
213 |
+
if other is S.NegativeInfinity and self.is_finite:
|
214 |
+
return S.true
|
215 |
+
|
216 |
+
return Ge(self, other, evaluate=False)
|
217 |
+
|
218 |
+
def __gt__(self, other):
|
219 |
+
other = S(other)
|
220 |
+
if self.args[0].is_real:
|
221 |
+
if other.is_integer:
|
222 |
+
return self.args[0] >= other + 1
|
223 |
+
if other.is_number and other.is_real:
|
224 |
+
return self.args[0] >= ceiling(other)
|
225 |
+
if self.args[0] == other and other.is_real:
|
226 |
+
return S.false
|
227 |
+
if other is S.NegativeInfinity and self.is_finite:
|
228 |
+
return S.true
|
229 |
+
|
230 |
+
return Gt(self, other, evaluate=False)
|
231 |
+
|
232 |
+
def __lt__(self, other):
|
233 |
+
other = S(other)
|
234 |
+
if self.args[0].is_real:
|
235 |
+
if other.is_integer:
|
236 |
+
return self.args[0] < other
|
237 |
+
if other.is_number and other.is_real:
|
238 |
+
return self.args[0] < ceiling(other)
|
239 |
+
if self.args[0] == other and other.is_real:
|
240 |
+
return S.false
|
241 |
+
if other is S.Infinity and self.is_finite:
|
242 |
+
return S.true
|
243 |
+
|
244 |
+
return Lt(self, other, evaluate=False)
|
245 |
+
|
246 |
+
|
247 |
+
@dispatch(floor, Expr)
|
248 |
+
def _eval_is_eq(lhs, rhs): # noqa:F811
|
249 |
+
return is_eq(lhs.rewrite(ceiling), rhs) or \
|
250 |
+
is_eq(lhs.rewrite(frac),rhs)
|
251 |
+
|
252 |
+
|
253 |
+
class ceiling(RoundFunction):
|
254 |
+
"""
|
255 |
+
Ceiling is a univariate function which returns the smallest integer
|
256 |
+
value not less than its argument. This implementation
|
257 |
+
generalizes ceiling to complex numbers by taking the ceiling of the
|
258 |
+
real and imaginary parts separately.
|
259 |
+
|
260 |
+
Examples
|
261 |
+
========
|
262 |
+
|
263 |
+
>>> from sympy import ceiling, E, I, S, Float, Rational
|
264 |
+
>>> ceiling(17)
|
265 |
+
17
|
266 |
+
>>> ceiling(Rational(23, 10))
|
267 |
+
3
|
268 |
+
>>> ceiling(2*E)
|
269 |
+
6
|
270 |
+
>>> ceiling(-Float(0.567))
|
271 |
+
0
|
272 |
+
>>> ceiling(I/2)
|
273 |
+
I
|
274 |
+
>>> ceiling(S(5)/2 + 5*I/2)
|
275 |
+
3 + 3*I
|
276 |
+
|
277 |
+
See Also
|
278 |
+
========
|
279 |
+
|
280 |
+
sympy.functions.elementary.integers.floor
|
281 |
+
|
282 |
+
References
|
283 |
+
==========
|
284 |
+
|
285 |
+
.. [1] "Concrete mathematics" by Graham, pp. 87
|
286 |
+
.. [2] https://mathworld.wolfram.com/CeilingFunction.html
|
287 |
+
|
288 |
+
"""
|
289 |
+
_dir = 1
|
290 |
+
|
291 |
+
@classmethod
|
292 |
+
def _eval_number(cls, arg):
|
293 |
+
if arg.is_Number:
|
294 |
+
return arg.ceiling()
|
295 |
+
elif any(isinstance(i, j)
|
296 |
+
for i in (arg, -arg) for j in (floor, ceiling)):
|
297 |
+
return arg
|
298 |
+
if arg.is_NumberSymbol:
|
299 |
+
return arg.approximation_interval(Integer)[1]
|
300 |
+
|
301 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
302 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
303 |
+
arg = self.args[0]
|
304 |
+
arg0 = arg.subs(x, 0)
|
305 |
+
r = self.subs(x, 0)
|
306 |
+
if arg0 is S.NaN or isinstance(arg0, AccumBounds):
|
307 |
+
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
|
308 |
+
r = ceiling(arg0)
|
309 |
+
if arg0.is_finite:
|
310 |
+
if arg0 == r:
|
311 |
+
ndir = arg.dir(x, cdir=cdir)
|
312 |
+
return r if ndir.is_negative else r + 1
|
313 |
+
else:
|
314 |
+
return r
|
315 |
+
return arg.as_leading_term(x, logx=logx, cdir=cdir)
|
316 |
+
|
317 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
318 |
+
arg = self.args[0]
|
319 |
+
arg0 = arg.subs(x, 0)
|
320 |
+
r = self.subs(x, 0)
|
321 |
+
if arg0 is S.NaN:
|
322 |
+
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
|
323 |
+
r = ceiling(arg0)
|
324 |
+
if arg0.is_infinite:
|
325 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
326 |
+
from sympy.series.order import Order
|
327 |
+
s = arg._eval_nseries(x, n, logx, cdir)
|
328 |
+
o = Order(1, (x, 0)) if n <= 0 else AccumBounds(0, 1)
|
329 |
+
return s + o
|
330 |
+
if arg0 == r:
|
331 |
+
ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1)
|
332 |
+
return r if ndir.is_negative else r + 1
|
333 |
+
else:
|
334 |
+
return r
|
335 |
+
|
336 |
+
def _eval_rewrite_as_floor(self, arg, **kwargs):
|
337 |
+
return -floor(-arg)
|
338 |
+
|
339 |
+
def _eval_rewrite_as_frac(self, arg, **kwargs):
|
340 |
+
return arg + frac(-arg)
|
341 |
+
|
342 |
+
def _eval_is_positive(self):
|
343 |
+
return self.args[0].is_positive
|
344 |
+
|
345 |
+
def _eval_is_nonpositive(self):
|
346 |
+
return self.args[0].is_nonpositive
|
347 |
+
|
348 |
+
def __lt__(self, other):
|
349 |
+
other = S(other)
|
350 |
+
if self.args[0].is_real:
|
351 |
+
if other.is_integer:
|
352 |
+
return self.args[0] <= other - 1
|
353 |
+
if other.is_number and other.is_real:
|
354 |
+
return self.args[0] <= floor(other)
|
355 |
+
if self.args[0] == other and other.is_real:
|
356 |
+
return S.false
|
357 |
+
if other is S.Infinity and self.is_finite:
|
358 |
+
return S.true
|
359 |
+
|
360 |
+
return Lt(self, other, evaluate=False)
|
361 |
+
|
362 |
+
def __gt__(self, other):
|
363 |
+
other = S(other)
|
364 |
+
if self.args[0].is_real:
|
365 |
+
if other.is_integer:
|
366 |
+
return self.args[0] > other
|
367 |
+
if other.is_number and other.is_real:
|
368 |
+
return self.args[0] > floor(other)
|
369 |
+
if self.args[0] == other and other.is_real:
|
370 |
+
return S.false
|
371 |
+
if other is S.NegativeInfinity and self.is_finite:
|
372 |
+
return S.true
|
373 |
+
|
374 |
+
return Gt(self, other, evaluate=False)
|
375 |
+
|
376 |
+
def __ge__(self, other):
|
377 |
+
other = S(other)
|
378 |
+
if self.args[0].is_real:
|
379 |
+
if other.is_integer:
|
380 |
+
return self.args[0] > other - 1
|
381 |
+
if other.is_number and other.is_real:
|
382 |
+
return self.args[0] > floor(other)
|
383 |
+
if self.args[0] == other and other.is_real:
|
384 |
+
return S.true
|
385 |
+
if other is S.NegativeInfinity and self.is_finite:
|
386 |
+
return S.true
|
387 |
+
|
388 |
+
return Ge(self, other, evaluate=False)
|
389 |
+
|
390 |
+
def __le__(self, other):
|
391 |
+
other = S(other)
|
392 |
+
if self.args[0].is_real:
|
393 |
+
if other.is_integer:
|
394 |
+
return self.args[0] <= other
|
395 |
+
if other.is_number and other.is_real:
|
396 |
+
return self.args[0] <= floor(other)
|
397 |
+
if self.args[0] == other and other.is_real:
|
398 |
+
return S.false
|
399 |
+
if other is S.Infinity and self.is_finite:
|
400 |
+
return S.true
|
401 |
+
|
402 |
+
return Le(self, other, evaluate=False)
|
403 |
+
|
404 |
+
|
405 |
+
@dispatch(ceiling, Basic) # type:ignore
|
406 |
+
def _eval_is_eq(lhs, rhs): # noqa:F811
|
407 |
+
return is_eq(lhs.rewrite(floor), rhs) or is_eq(lhs.rewrite(frac),rhs)
|
408 |
+
|
409 |
+
|
410 |
+
class frac(Function):
|
411 |
+
r"""Represents the fractional part of x
|
412 |
+
|
413 |
+
For real numbers it is defined [1]_ as
|
414 |
+
|
415 |
+
.. math::
|
416 |
+
x - \left\lfloor{x}\right\rfloor
|
417 |
+
|
418 |
+
Examples
|
419 |
+
========
|
420 |
+
|
421 |
+
>>> from sympy import Symbol, frac, Rational, floor, I
|
422 |
+
>>> frac(Rational(4, 3))
|
423 |
+
1/3
|
424 |
+
>>> frac(-Rational(4, 3))
|
425 |
+
2/3
|
426 |
+
|
427 |
+
returns zero for integer arguments
|
428 |
+
|
429 |
+
>>> n = Symbol('n', integer=True)
|
430 |
+
>>> frac(n)
|
431 |
+
0
|
432 |
+
|
433 |
+
rewrite as floor
|
434 |
+
|
435 |
+
>>> x = Symbol('x')
|
436 |
+
>>> frac(x).rewrite(floor)
|
437 |
+
x - floor(x)
|
438 |
+
|
439 |
+
for complex arguments
|
440 |
+
|
441 |
+
>>> r = Symbol('r', real=True)
|
442 |
+
>>> t = Symbol('t', real=True)
|
443 |
+
>>> frac(t + I*r)
|
444 |
+
I*frac(r) + frac(t)
|
445 |
+
|
446 |
+
See Also
|
447 |
+
========
|
448 |
+
|
449 |
+
sympy.functions.elementary.integers.floor
|
450 |
+
sympy.functions.elementary.integers.ceiling
|
451 |
+
|
452 |
+
References
|
453 |
+
===========
|
454 |
+
|
455 |
+
.. [1] https://en.wikipedia.org/wiki/Fractional_part
|
456 |
+
.. [2] https://mathworld.wolfram.com/FractionalPart.html
|
457 |
+
|
458 |
+
"""
|
459 |
+
@classmethod
|
460 |
+
def eval(cls, arg):
|
461 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
462 |
+
|
463 |
+
def _eval(arg):
|
464 |
+
if arg in (S.Infinity, S.NegativeInfinity):
|
465 |
+
return AccumBounds(0, 1)
|
466 |
+
if arg.is_integer:
|
467 |
+
return S.Zero
|
468 |
+
if arg.is_number:
|
469 |
+
if arg is S.NaN:
|
470 |
+
return S.NaN
|
471 |
+
elif arg is S.ComplexInfinity:
|
472 |
+
return S.NaN
|
473 |
+
else:
|
474 |
+
return arg - floor(arg)
|
475 |
+
return cls(arg, evaluate=False)
|
476 |
+
|
477 |
+
terms = Add.make_args(arg)
|
478 |
+
real, imag = S.Zero, S.Zero
|
479 |
+
for t in terms:
|
480 |
+
# Two checks are needed for complex arguments
|
481 |
+
# see issue-7649 for details
|
482 |
+
if t.is_imaginary or (S.ImaginaryUnit*t).is_real:
|
483 |
+
i = im(t)
|
484 |
+
if not i.has(S.ImaginaryUnit):
|
485 |
+
imag += i
|
486 |
+
else:
|
487 |
+
real += t
|
488 |
+
else:
|
489 |
+
real += t
|
490 |
+
|
491 |
+
real = _eval(real)
|
492 |
+
imag = _eval(imag)
|
493 |
+
return real + S.ImaginaryUnit*imag
|
494 |
+
|
495 |
+
def _eval_rewrite_as_floor(self, arg, **kwargs):
|
496 |
+
return arg - floor(arg)
|
497 |
+
|
498 |
+
def _eval_rewrite_as_ceiling(self, arg, **kwargs):
|
499 |
+
return arg + ceiling(-arg)
|
500 |
+
|
501 |
+
def _eval_is_finite(self):
|
502 |
+
return True
|
503 |
+
|
504 |
+
def _eval_is_real(self):
|
505 |
+
return self.args[0].is_extended_real
|
506 |
+
|
507 |
+
def _eval_is_imaginary(self):
|
508 |
+
return self.args[0].is_imaginary
|
509 |
+
|
510 |
+
def _eval_is_integer(self):
|
511 |
+
return self.args[0].is_integer
|
512 |
+
|
513 |
+
def _eval_is_zero(self):
|
514 |
+
return fuzzy_or([self.args[0].is_zero, self.args[0].is_integer])
|
515 |
+
|
516 |
+
def _eval_is_negative(self):
|
517 |
+
return False
|
518 |
+
|
519 |
+
def __ge__(self, other):
|
520 |
+
if self.is_extended_real:
|
521 |
+
other = _sympify(other)
|
522 |
+
# Check if other <= 0
|
523 |
+
if other.is_extended_nonpositive:
|
524 |
+
return S.true
|
525 |
+
# Check if other >= 1
|
526 |
+
res = self._value_one_or_more(other)
|
527 |
+
if res is not None:
|
528 |
+
return not(res)
|
529 |
+
return Ge(self, other, evaluate=False)
|
530 |
+
|
531 |
+
def __gt__(self, other):
|
532 |
+
if self.is_extended_real:
|
533 |
+
other = _sympify(other)
|
534 |
+
# Check if other < 0
|
535 |
+
res = self._value_one_or_more(other)
|
536 |
+
if res is not None:
|
537 |
+
return not(res)
|
538 |
+
# Check if other >= 1
|
539 |
+
if other.is_extended_negative:
|
540 |
+
return S.true
|
541 |
+
return Gt(self, other, evaluate=False)
|
542 |
+
|
543 |
+
def __le__(self, other):
|
544 |
+
if self.is_extended_real:
|
545 |
+
other = _sympify(other)
|
546 |
+
# Check if other < 0
|
547 |
+
if other.is_extended_negative:
|
548 |
+
return S.false
|
549 |
+
# Check if other >= 1
|
550 |
+
res = self._value_one_or_more(other)
|
551 |
+
if res is not None:
|
552 |
+
return res
|
553 |
+
return Le(self, other, evaluate=False)
|
554 |
+
|
555 |
+
def __lt__(self, other):
|
556 |
+
if self.is_extended_real:
|
557 |
+
other = _sympify(other)
|
558 |
+
# Check if other <= 0
|
559 |
+
if other.is_extended_nonpositive:
|
560 |
+
return S.false
|
561 |
+
# Check if other >= 1
|
562 |
+
res = self._value_one_or_more(other)
|
563 |
+
if res is not None:
|
564 |
+
return res
|
565 |
+
return Lt(self, other, evaluate=False)
|
566 |
+
|
567 |
+
def _value_one_or_more(self, other):
|
568 |
+
if other.is_extended_real:
|
569 |
+
if other.is_number:
|
570 |
+
res = other >= 1
|
571 |
+
if res and not isinstance(res, Relational):
|
572 |
+
return S.true
|
573 |
+
if other.is_integer and other.is_positive:
|
574 |
+
return S.true
|
575 |
+
|
576 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
577 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
578 |
+
arg = self.args[0]
|
579 |
+
arg0 = arg.subs(x, 0)
|
580 |
+
r = self.subs(x, 0)
|
581 |
+
|
582 |
+
if arg0.is_finite:
|
583 |
+
if r.is_zero:
|
584 |
+
ndir = arg.dir(x, cdir=cdir)
|
585 |
+
if ndir.is_negative:
|
586 |
+
return S.One
|
587 |
+
return (arg - arg0).as_leading_term(x, logx=logx, cdir=cdir)
|
588 |
+
else:
|
589 |
+
return r
|
590 |
+
elif arg0 in (S.ComplexInfinity, S.Infinity, S.NegativeInfinity):
|
591 |
+
return AccumBounds(0, 1)
|
592 |
+
return arg.as_leading_term(x, logx=logx, cdir=cdir)
|
593 |
+
|
594 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
595 |
+
from sympy.series.order import Order
|
596 |
+
arg = self.args[0]
|
597 |
+
arg0 = arg.subs(x, 0)
|
598 |
+
r = self.subs(x, 0)
|
599 |
+
|
600 |
+
if arg0.is_infinite:
|
601 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
602 |
+
o = Order(1, (x, 0)) if n <= 0 else AccumBounds(0, 1) + Order(x**n, (x, 0))
|
603 |
+
return o
|
604 |
+
else:
|
605 |
+
res = (arg - arg0)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
606 |
+
if r.is_zero:
|
607 |
+
ndir = arg.dir(x, cdir=cdir)
|
608 |
+
res += S.One if ndir.is_negative else S.Zero
|
609 |
+
else:
|
610 |
+
res += r
|
611 |
+
return res
|
612 |
+
|
613 |
+
|
614 |
+
@dispatch(frac, Basic) # type:ignore
|
615 |
+
def _eval_is_eq(lhs, rhs): # noqa:F811
|
616 |
+
if (lhs.rewrite(floor) == rhs) or \
|
617 |
+
(lhs.rewrite(ceiling) == rhs):
|
618 |
+
return True
|
619 |
+
# Check if other < 0
|
620 |
+
if rhs.is_extended_negative:
|
621 |
+
return False
|
622 |
+
# Check if other >= 1
|
623 |
+
res = lhs._value_one_or_more(rhs)
|
624 |
+
if res is not None:
|
625 |
+
return False
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/miscellaneous.py
ADDED
@@ -0,0 +1,915 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import Function, S, sympify, NumberKind
|
2 |
+
from sympy.utilities.iterables import sift
|
3 |
+
from sympy.core.add import Add
|
4 |
+
from sympy.core.containers import Tuple
|
5 |
+
from sympy.core.operations import LatticeOp, ShortCircuit
|
6 |
+
from sympy.core.function import (Application, Lambda,
|
7 |
+
ArgumentIndexError)
|
8 |
+
from sympy.core.expr import Expr
|
9 |
+
from sympy.core.exprtools import factor_terms
|
10 |
+
from sympy.core.mod import Mod
|
11 |
+
from sympy.core.mul import Mul
|
12 |
+
from sympy.core.numbers import Rational
|
13 |
+
from sympy.core.power import Pow
|
14 |
+
from sympy.core.relational import Eq, Relational
|
15 |
+
from sympy.core.singleton import Singleton
|
16 |
+
from sympy.core.sorting import ordered
|
17 |
+
from sympy.core.symbol import Dummy
|
18 |
+
from sympy.core.rules import Transform
|
19 |
+
from sympy.core.logic import fuzzy_and, fuzzy_or, _torf
|
20 |
+
from sympy.core.traversal import walk
|
21 |
+
from sympy.core.numbers import Integer
|
22 |
+
from sympy.logic.boolalg import And, Or
|
23 |
+
|
24 |
+
|
25 |
+
def _minmax_as_Piecewise(op, *args):
|
26 |
+
# helper for Min/Max rewrite as Piecewise
|
27 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
28 |
+
ec = []
|
29 |
+
for i, a in enumerate(args):
|
30 |
+
c = [Relational(a, args[j], op) for j in range(i + 1, len(args))]
|
31 |
+
ec.append((a, And(*c)))
|
32 |
+
return Piecewise(*ec)
|
33 |
+
|
34 |
+
|
35 |
+
class IdentityFunction(Lambda, metaclass=Singleton):
|
36 |
+
"""
|
37 |
+
The identity function
|
38 |
+
|
39 |
+
Examples
|
40 |
+
========
|
41 |
+
|
42 |
+
>>> from sympy import Id, Symbol
|
43 |
+
>>> x = Symbol('x')
|
44 |
+
>>> Id(x)
|
45 |
+
x
|
46 |
+
|
47 |
+
"""
|
48 |
+
|
49 |
+
_symbol = Dummy('x')
|
50 |
+
|
51 |
+
@property
|
52 |
+
def signature(self):
|
53 |
+
return Tuple(self._symbol)
|
54 |
+
|
55 |
+
@property
|
56 |
+
def expr(self):
|
57 |
+
return self._symbol
|
58 |
+
|
59 |
+
|
60 |
+
Id = S.IdentityFunction
|
61 |
+
|
62 |
+
###############################################################################
|
63 |
+
############################# ROOT and SQUARE ROOT FUNCTION ###################
|
64 |
+
###############################################################################
|
65 |
+
|
66 |
+
|
67 |
+
def sqrt(arg, evaluate=None):
|
68 |
+
"""Returns the principal square root.
|
69 |
+
|
70 |
+
Parameters
|
71 |
+
==========
|
72 |
+
|
73 |
+
evaluate : bool, optional
|
74 |
+
The parameter determines if the expression should be evaluated.
|
75 |
+
If ``None``, its value is taken from
|
76 |
+
``global_parameters.evaluate``.
|
77 |
+
|
78 |
+
Examples
|
79 |
+
========
|
80 |
+
|
81 |
+
>>> from sympy import sqrt, Symbol, S
|
82 |
+
>>> x = Symbol('x')
|
83 |
+
|
84 |
+
>>> sqrt(x)
|
85 |
+
sqrt(x)
|
86 |
+
|
87 |
+
>>> sqrt(x)**2
|
88 |
+
x
|
89 |
+
|
90 |
+
Note that sqrt(x**2) does not simplify to x.
|
91 |
+
|
92 |
+
>>> sqrt(x**2)
|
93 |
+
sqrt(x**2)
|
94 |
+
|
95 |
+
This is because the two are not equal to each other in general.
|
96 |
+
For example, consider x == -1:
|
97 |
+
|
98 |
+
>>> from sympy import Eq
|
99 |
+
>>> Eq(sqrt(x**2), x).subs(x, -1)
|
100 |
+
False
|
101 |
+
|
102 |
+
This is because sqrt computes the principal square root, so the square may
|
103 |
+
put the argument in a different branch. This identity does hold if x is
|
104 |
+
positive:
|
105 |
+
|
106 |
+
>>> y = Symbol('y', positive=True)
|
107 |
+
>>> sqrt(y**2)
|
108 |
+
y
|
109 |
+
|
110 |
+
You can force this simplification by using the powdenest() function with
|
111 |
+
the force option set to True:
|
112 |
+
|
113 |
+
>>> from sympy import powdenest
|
114 |
+
>>> sqrt(x**2)
|
115 |
+
sqrt(x**2)
|
116 |
+
>>> powdenest(sqrt(x**2), force=True)
|
117 |
+
x
|
118 |
+
|
119 |
+
To get both branches of the square root you can use the rootof function:
|
120 |
+
|
121 |
+
>>> from sympy import rootof
|
122 |
+
|
123 |
+
>>> [rootof(x**2-3,i) for i in (0,1)]
|
124 |
+
[-sqrt(3), sqrt(3)]
|
125 |
+
|
126 |
+
Although ``sqrt`` is printed, there is no ``sqrt`` function so looking for
|
127 |
+
``sqrt`` in an expression will fail:
|
128 |
+
|
129 |
+
>>> from sympy.utilities.misc import func_name
|
130 |
+
>>> func_name(sqrt(x))
|
131 |
+
'Pow'
|
132 |
+
>>> sqrt(x).has(sqrt)
|
133 |
+
False
|
134 |
+
|
135 |
+
To find ``sqrt`` look for ``Pow`` with an exponent of ``1/2``:
|
136 |
+
|
137 |
+
>>> (x + 1/sqrt(x)).find(lambda i: i.is_Pow and abs(i.exp) is S.Half)
|
138 |
+
{1/sqrt(x)}
|
139 |
+
|
140 |
+
See Also
|
141 |
+
========
|
142 |
+
|
143 |
+
sympy.polys.rootoftools.rootof, root, real_root
|
144 |
+
|
145 |
+
References
|
146 |
+
==========
|
147 |
+
|
148 |
+
.. [1] https://en.wikipedia.org/wiki/Square_root
|
149 |
+
.. [2] https://en.wikipedia.org/wiki/Principal_value
|
150 |
+
"""
|
151 |
+
# arg = sympify(arg) is handled by Pow
|
152 |
+
return Pow(arg, S.Half, evaluate=evaluate)
|
153 |
+
|
154 |
+
|
155 |
+
def cbrt(arg, evaluate=None):
|
156 |
+
"""Returns the principal cube root.
|
157 |
+
|
158 |
+
Parameters
|
159 |
+
==========
|
160 |
+
|
161 |
+
evaluate : bool, optional
|
162 |
+
The parameter determines if the expression should be evaluated.
|
163 |
+
If ``None``, its value is taken from
|
164 |
+
``global_parameters.evaluate``.
|
165 |
+
|
166 |
+
Examples
|
167 |
+
========
|
168 |
+
|
169 |
+
>>> from sympy import cbrt, Symbol
|
170 |
+
>>> x = Symbol('x')
|
171 |
+
|
172 |
+
>>> cbrt(x)
|
173 |
+
x**(1/3)
|
174 |
+
|
175 |
+
>>> cbrt(x)**3
|
176 |
+
x
|
177 |
+
|
178 |
+
Note that cbrt(x**3) does not simplify to x.
|
179 |
+
|
180 |
+
>>> cbrt(x**3)
|
181 |
+
(x**3)**(1/3)
|
182 |
+
|
183 |
+
This is because the two are not equal to each other in general.
|
184 |
+
For example, consider `x == -1`:
|
185 |
+
|
186 |
+
>>> from sympy import Eq
|
187 |
+
>>> Eq(cbrt(x**3), x).subs(x, -1)
|
188 |
+
False
|
189 |
+
|
190 |
+
This is because cbrt computes the principal cube root, this
|
191 |
+
identity does hold if `x` is positive:
|
192 |
+
|
193 |
+
>>> y = Symbol('y', positive=True)
|
194 |
+
>>> cbrt(y**3)
|
195 |
+
y
|
196 |
+
|
197 |
+
See Also
|
198 |
+
========
|
199 |
+
|
200 |
+
sympy.polys.rootoftools.rootof, root, real_root
|
201 |
+
|
202 |
+
References
|
203 |
+
==========
|
204 |
+
|
205 |
+
.. [1] https://en.wikipedia.org/wiki/Cube_root
|
206 |
+
.. [2] https://en.wikipedia.org/wiki/Principal_value
|
207 |
+
|
208 |
+
"""
|
209 |
+
return Pow(arg, Rational(1, 3), evaluate=evaluate)
|
210 |
+
|
211 |
+
|
212 |
+
def root(arg, n, k=0, evaluate=None):
|
213 |
+
r"""Returns the *k*-th *n*-th root of ``arg``.
|
214 |
+
|
215 |
+
Parameters
|
216 |
+
==========
|
217 |
+
|
218 |
+
k : int, optional
|
219 |
+
Should be an integer in $\{0, 1, ..., n-1\}$.
|
220 |
+
Defaults to the principal root if $0$.
|
221 |
+
|
222 |
+
evaluate : bool, optional
|
223 |
+
The parameter determines if the expression should be evaluated.
|
224 |
+
If ``None``, its value is taken from
|
225 |
+
``global_parameters.evaluate``.
|
226 |
+
|
227 |
+
Examples
|
228 |
+
========
|
229 |
+
|
230 |
+
>>> from sympy import root, Rational
|
231 |
+
>>> from sympy.abc import x, n
|
232 |
+
|
233 |
+
>>> root(x, 2)
|
234 |
+
sqrt(x)
|
235 |
+
|
236 |
+
>>> root(x, 3)
|
237 |
+
x**(1/3)
|
238 |
+
|
239 |
+
>>> root(x, n)
|
240 |
+
x**(1/n)
|
241 |
+
|
242 |
+
>>> root(x, -Rational(2, 3))
|
243 |
+
x**(-3/2)
|
244 |
+
|
245 |
+
To get the k-th n-th root, specify k:
|
246 |
+
|
247 |
+
>>> root(-2, 3, 2)
|
248 |
+
-(-1)**(2/3)*2**(1/3)
|
249 |
+
|
250 |
+
To get all n n-th roots you can use the rootof function.
|
251 |
+
The following examples show the roots of unity for n
|
252 |
+
equal 2, 3 and 4:
|
253 |
+
|
254 |
+
>>> from sympy import rootof
|
255 |
+
|
256 |
+
>>> [rootof(x**2 - 1, i) for i in range(2)]
|
257 |
+
[-1, 1]
|
258 |
+
|
259 |
+
>>> [rootof(x**3 - 1,i) for i in range(3)]
|
260 |
+
[1, -1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2]
|
261 |
+
|
262 |
+
>>> [rootof(x**4 - 1,i) for i in range(4)]
|
263 |
+
[-1, 1, -I, I]
|
264 |
+
|
265 |
+
SymPy, like other symbolic algebra systems, returns the
|
266 |
+
complex root of negative numbers. This is the principal
|
267 |
+
root and differs from the text-book result that one might
|
268 |
+
be expecting. For example, the cube root of -8 does not
|
269 |
+
come back as -2:
|
270 |
+
|
271 |
+
>>> root(-8, 3)
|
272 |
+
2*(-1)**(1/3)
|
273 |
+
|
274 |
+
The real_root function can be used to either make the principal
|
275 |
+
result real (or simply to return the real root directly):
|
276 |
+
|
277 |
+
>>> from sympy import real_root
|
278 |
+
>>> real_root(_)
|
279 |
+
-2
|
280 |
+
>>> real_root(-32, 5)
|
281 |
+
-2
|
282 |
+
|
283 |
+
Alternatively, the n//2-th n-th root of a negative number can be
|
284 |
+
computed with root:
|
285 |
+
|
286 |
+
>>> root(-32, 5, 5//2)
|
287 |
+
-2
|
288 |
+
|
289 |
+
See Also
|
290 |
+
========
|
291 |
+
|
292 |
+
sympy.polys.rootoftools.rootof
|
293 |
+
sympy.core.power.integer_nthroot
|
294 |
+
sqrt, real_root
|
295 |
+
|
296 |
+
References
|
297 |
+
==========
|
298 |
+
|
299 |
+
.. [1] https://en.wikipedia.org/wiki/Square_root
|
300 |
+
.. [2] https://en.wikipedia.org/wiki/Real_root
|
301 |
+
.. [3] https://en.wikipedia.org/wiki/Root_of_unity
|
302 |
+
.. [4] https://en.wikipedia.org/wiki/Principal_value
|
303 |
+
.. [5] https://mathworld.wolfram.com/CubeRoot.html
|
304 |
+
|
305 |
+
"""
|
306 |
+
n = sympify(n)
|
307 |
+
if k:
|
308 |
+
return Mul(Pow(arg, S.One/n, evaluate=evaluate), S.NegativeOne**(2*k/n), evaluate=evaluate)
|
309 |
+
return Pow(arg, 1/n, evaluate=evaluate)
|
310 |
+
|
311 |
+
|
312 |
+
def real_root(arg, n=None, evaluate=None):
|
313 |
+
r"""Return the real *n*'th-root of *arg* if possible.
|
314 |
+
|
315 |
+
Parameters
|
316 |
+
==========
|
317 |
+
|
318 |
+
n : int or None, optional
|
319 |
+
If *n* is ``None``, then all instances of
|
320 |
+
$(-n)^{1/\text{odd}}$ will be changed to $-n^{1/\text{odd}}$.
|
321 |
+
This will only create a real root of a principal root.
|
322 |
+
The presence of other factors may cause the result to not be
|
323 |
+
real.
|
324 |
+
|
325 |
+
evaluate : bool, optional
|
326 |
+
The parameter determines if the expression should be evaluated.
|
327 |
+
If ``None``, its value is taken from
|
328 |
+
``global_parameters.evaluate``.
|
329 |
+
|
330 |
+
Examples
|
331 |
+
========
|
332 |
+
|
333 |
+
>>> from sympy import root, real_root
|
334 |
+
|
335 |
+
>>> real_root(-8, 3)
|
336 |
+
-2
|
337 |
+
>>> root(-8, 3)
|
338 |
+
2*(-1)**(1/3)
|
339 |
+
>>> real_root(_)
|
340 |
+
-2
|
341 |
+
|
342 |
+
If one creates a non-principal root and applies real_root, the
|
343 |
+
result will not be real (so use with caution):
|
344 |
+
|
345 |
+
>>> root(-8, 3, 2)
|
346 |
+
-2*(-1)**(2/3)
|
347 |
+
>>> real_root(_)
|
348 |
+
-2*(-1)**(2/3)
|
349 |
+
|
350 |
+
See Also
|
351 |
+
========
|
352 |
+
|
353 |
+
sympy.polys.rootoftools.rootof
|
354 |
+
sympy.core.power.integer_nthroot
|
355 |
+
root, sqrt
|
356 |
+
"""
|
357 |
+
from sympy.functions.elementary.complexes import Abs, im, sign
|
358 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
359 |
+
if n is not None:
|
360 |
+
return Piecewise(
|
361 |
+
(root(arg, n, evaluate=evaluate), Or(Eq(n, S.One), Eq(n, S.NegativeOne))),
|
362 |
+
(Mul(sign(arg), root(Abs(arg), n, evaluate=evaluate), evaluate=evaluate),
|
363 |
+
And(Eq(im(arg), S.Zero), Eq(Mod(n, 2), S.One))),
|
364 |
+
(root(arg, n, evaluate=evaluate), True))
|
365 |
+
rv = sympify(arg)
|
366 |
+
n1pow = Transform(lambda x: -(-x.base)**x.exp,
|
367 |
+
lambda x:
|
368 |
+
x.is_Pow and
|
369 |
+
x.base.is_negative and
|
370 |
+
x.exp.is_Rational and
|
371 |
+
x.exp.p == 1 and x.exp.q % 2)
|
372 |
+
return rv.xreplace(n1pow)
|
373 |
+
|
374 |
+
###############################################################################
|
375 |
+
############################# MINIMUM and MAXIMUM #############################
|
376 |
+
###############################################################################
|
377 |
+
|
378 |
+
|
379 |
+
class MinMaxBase(Expr, LatticeOp):
|
380 |
+
def __new__(cls, *args, **assumptions):
|
381 |
+
from sympy.core.parameters import global_parameters
|
382 |
+
evaluate = assumptions.pop('evaluate', global_parameters.evaluate)
|
383 |
+
args = (sympify(arg) for arg in args)
|
384 |
+
|
385 |
+
# first standard filter, for cls.zero and cls.identity
|
386 |
+
# also reshape Max(a, Max(b, c)) to Max(a, b, c)
|
387 |
+
|
388 |
+
if evaluate:
|
389 |
+
try:
|
390 |
+
args = frozenset(cls._new_args_filter(args))
|
391 |
+
except ShortCircuit:
|
392 |
+
return cls.zero
|
393 |
+
# remove redundant args that are easily identified
|
394 |
+
args = cls._collapse_arguments(args, **assumptions)
|
395 |
+
# find local zeros
|
396 |
+
args = cls._find_localzeros(args, **assumptions)
|
397 |
+
args = frozenset(args)
|
398 |
+
|
399 |
+
if not args:
|
400 |
+
return cls.identity
|
401 |
+
|
402 |
+
if len(args) == 1:
|
403 |
+
return list(args).pop()
|
404 |
+
|
405 |
+
# base creation
|
406 |
+
obj = Expr.__new__(cls, *ordered(args), **assumptions)
|
407 |
+
obj._argset = args
|
408 |
+
return obj
|
409 |
+
|
410 |
+
@classmethod
|
411 |
+
def _collapse_arguments(cls, args, **assumptions):
|
412 |
+
"""Remove redundant args.
|
413 |
+
|
414 |
+
Examples
|
415 |
+
========
|
416 |
+
|
417 |
+
>>> from sympy import Min, Max
|
418 |
+
>>> from sympy.abc import a, b, c, d, e
|
419 |
+
|
420 |
+
Any arg in parent that appears in any
|
421 |
+
parent-like function in any of the flat args
|
422 |
+
of parent can be removed from that sub-arg:
|
423 |
+
|
424 |
+
>>> Min(a, Max(b, Min(a, c, d)))
|
425 |
+
Min(a, Max(b, Min(c, d)))
|
426 |
+
|
427 |
+
If the arg of parent appears in an opposite-than parent
|
428 |
+
function in any of the flat args of parent that function
|
429 |
+
can be replaced with the arg:
|
430 |
+
|
431 |
+
>>> Min(a, Max(b, Min(c, d, Max(a, e))))
|
432 |
+
Min(a, Max(b, Min(a, c, d)))
|
433 |
+
"""
|
434 |
+
if not args:
|
435 |
+
return args
|
436 |
+
args = list(ordered(args))
|
437 |
+
if cls == Min:
|
438 |
+
other = Max
|
439 |
+
else:
|
440 |
+
other = Min
|
441 |
+
|
442 |
+
# find global comparable max of Max and min of Min if a new
|
443 |
+
# value is being introduced in these args at position 0 of
|
444 |
+
# the ordered args
|
445 |
+
if args[0].is_number:
|
446 |
+
sifted = mins, maxs = [], []
|
447 |
+
for i in args:
|
448 |
+
for v in walk(i, Min, Max):
|
449 |
+
if v.args[0].is_comparable:
|
450 |
+
sifted[isinstance(v, Max)].append(v)
|
451 |
+
small = Min.identity
|
452 |
+
for i in mins:
|
453 |
+
v = i.args[0]
|
454 |
+
if v.is_number and (v < small) == True:
|
455 |
+
small = v
|
456 |
+
big = Max.identity
|
457 |
+
for i in maxs:
|
458 |
+
v = i.args[0]
|
459 |
+
if v.is_number and (v > big) == True:
|
460 |
+
big = v
|
461 |
+
# at the point when this function is called from __new__,
|
462 |
+
# there may be more than one numeric arg present since
|
463 |
+
# local zeros have not been handled yet, so look through
|
464 |
+
# more than the first arg
|
465 |
+
if cls == Min:
|
466 |
+
for arg in args:
|
467 |
+
if not arg.is_number:
|
468 |
+
break
|
469 |
+
if (arg < small) == True:
|
470 |
+
small = arg
|
471 |
+
elif cls == Max:
|
472 |
+
for arg in args:
|
473 |
+
if not arg.is_number:
|
474 |
+
break
|
475 |
+
if (arg > big) == True:
|
476 |
+
big = arg
|
477 |
+
T = None
|
478 |
+
if cls == Min:
|
479 |
+
if small != Min.identity:
|
480 |
+
other = Max
|
481 |
+
T = small
|
482 |
+
elif big != Max.identity:
|
483 |
+
other = Min
|
484 |
+
T = big
|
485 |
+
if T is not None:
|
486 |
+
# remove numerical redundancy
|
487 |
+
for i in range(len(args)):
|
488 |
+
a = args[i]
|
489 |
+
if isinstance(a, other):
|
490 |
+
a0 = a.args[0]
|
491 |
+
if ((a0 > T) if other == Max else (a0 < T)) == True:
|
492 |
+
args[i] = cls.identity
|
493 |
+
|
494 |
+
# remove redundant symbolic args
|
495 |
+
def do(ai, a):
|
496 |
+
if not isinstance(ai, (Min, Max)):
|
497 |
+
return ai
|
498 |
+
cond = a in ai.args
|
499 |
+
if not cond:
|
500 |
+
return ai.func(*[do(i, a) for i in ai.args],
|
501 |
+
evaluate=False)
|
502 |
+
if isinstance(ai, cls):
|
503 |
+
return ai.func(*[do(i, a) for i in ai.args if i != a],
|
504 |
+
evaluate=False)
|
505 |
+
return a
|
506 |
+
for i, a in enumerate(args):
|
507 |
+
args[i + 1:] = [do(ai, a) for ai in args[i + 1:]]
|
508 |
+
|
509 |
+
# factor out common elements as for
|
510 |
+
# Min(Max(x, y), Max(x, z)) -> Max(x, Min(y, z))
|
511 |
+
# and vice versa when swapping Min/Max -- do this only for the
|
512 |
+
# easy case where all functions contain something in common;
|
513 |
+
# trying to find some optimal subset of args to modify takes
|
514 |
+
# too long
|
515 |
+
|
516 |
+
def factor_minmax(args):
|
517 |
+
is_other = lambda arg: isinstance(arg, other)
|
518 |
+
other_args, remaining_args = sift(args, is_other, binary=True)
|
519 |
+
if not other_args:
|
520 |
+
return args
|
521 |
+
|
522 |
+
# Min(Max(x, y, z), Max(x, y, u, v)) -> {x,y}, ({z}, {u,v})
|
523 |
+
arg_sets = [set(arg.args) for arg in other_args]
|
524 |
+
common = set.intersection(*arg_sets)
|
525 |
+
if not common:
|
526 |
+
return args
|
527 |
+
|
528 |
+
new_other_args = list(common)
|
529 |
+
arg_sets_diff = [arg_set - common for arg_set in arg_sets]
|
530 |
+
|
531 |
+
# If any set is empty after removing common then all can be
|
532 |
+
# discarded e.g. Min(Max(a, b, c), Max(a, b)) -> Max(a, b)
|
533 |
+
if all(arg_sets_diff):
|
534 |
+
other_args_diff = [other(*s, evaluate=False) for s in arg_sets_diff]
|
535 |
+
new_other_args.append(cls(*other_args_diff, evaluate=False))
|
536 |
+
|
537 |
+
other_args_factored = other(*new_other_args, evaluate=False)
|
538 |
+
return remaining_args + [other_args_factored]
|
539 |
+
|
540 |
+
if len(args) > 1:
|
541 |
+
args = factor_minmax(args)
|
542 |
+
|
543 |
+
return args
|
544 |
+
|
545 |
+
@classmethod
|
546 |
+
def _new_args_filter(cls, arg_sequence):
|
547 |
+
"""
|
548 |
+
Generator filtering args.
|
549 |
+
|
550 |
+
first standard filter, for cls.zero and cls.identity.
|
551 |
+
Also reshape ``Max(a, Max(b, c))`` to ``Max(a, b, c)``,
|
552 |
+
and check arguments for comparability
|
553 |
+
"""
|
554 |
+
for arg in arg_sequence:
|
555 |
+
# pre-filter, checking comparability of arguments
|
556 |
+
if not isinstance(arg, Expr) or arg.is_extended_real is False or (
|
557 |
+
arg.is_number and
|
558 |
+
not arg.is_comparable):
|
559 |
+
raise ValueError("The argument '%s' is not comparable." % arg)
|
560 |
+
|
561 |
+
if arg == cls.zero:
|
562 |
+
raise ShortCircuit(arg)
|
563 |
+
elif arg == cls.identity:
|
564 |
+
continue
|
565 |
+
elif arg.func == cls:
|
566 |
+
yield from arg.args
|
567 |
+
else:
|
568 |
+
yield arg
|
569 |
+
|
570 |
+
@classmethod
|
571 |
+
def _find_localzeros(cls, values, **options):
|
572 |
+
"""
|
573 |
+
Sequentially allocate values to localzeros.
|
574 |
+
|
575 |
+
When a value is identified as being more extreme than another member it
|
576 |
+
replaces that member; if this is never true, then the value is simply
|
577 |
+
appended to the localzeros.
|
578 |
+
"""
|
579 |
+
localzeros = set()
|
580 |
+
for v in values:
|
581 |
+
is_newzero = True
|
582 |
+
localzeros_ = list(localzeros)
|
583 |
+
for z in localzeros_:
|
584 |
+
if id(v) == id(z):
|
585 |
+
is_newzero = False
|
586 |
+
else:
|
587 |
+
con = cls._is_connected(v, z)
|
588 |
+
if con:
|
589 |
+
is_newzero = False
|
590 |
+
if con is True or con == cls:
|
591 |
+
localzeros.remove(z)
|
592 |
+
localzeros.update([v])
|
593 |
+
if is_newzero:
|
594 |
+
localzeros.update([v])
|
595 |
+
return localzeros
|
596 |
+
|
597 |
+
@classmethod
|
598 |
+
def _is_connected(cls, x, y):
|
599 |
+
"""
|
600 |
+
Check if x and y are connected somehow.
|
601 |
+
"""
|
602 |
+
for i in range(2):
|
603 |
+
if x == y:
|
604 |
+
return True
|
605 |
+
t, f = Max, Min
|
606 |
+
for op in "><":
|
607 |
+
for j in range(2):
|
608 |
+
try:
|
609 |
+
if op == ">":
|
610 |
+
v = x >= y
|
611 |
+
else:
|
612 |
+
v = x <= y
|
613 |
+
except TypeError:
|
614 |
+
return False # non-real arg
|
615 |
+
if not v.is_Relational:
|
616 |
+
return t if v else f
|
617 |
+
t, f = f, t
|
618 |
+
x, y = y, x
|
619 |
+
x, y = y, x # run next pass with reversed order relative to start
|
620 |
+
# simplification can be expensive, so be conservative
|
621 |
+
# in what is attempted
|
622 |
+
x = factor_terms(x - y)
|
623 |
+
y = S.Zero
|
624 |
+
|
625 |
+
return False
|
626 |
+
|
627 |
+
def _eval_derivative(self, s):
|
628 |
+
# f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s)
|
629 |
+
i = 0
|
630 |
+
l = []
|
631 |
+
for a in self.args:
|
632 |
+
i += 1
|
633 |
+
da = a.diff(s)
|
634 |
+
if da.is_zero:
|
635 |
+
continue
|
636 |
+
try:
|
637 |
+
df = self.fdiff(i)
|
638 |
+
except ArgumentIndexError:
|
639 |
+
df = Function.fdiff(self, i)
|
640 |
+
l.append(df * da)
|
641 |
+
return Add(*l)
|
642 |
+
|
643 |
+
def _eval_rewrite_as_Abs(self, *args, **kwargs):
|
644 |
+
from sympy.functions.elementary.complexes import Abs
|
645 |
+
s = (args[0] + self.func(*args[1:]))/2
|
646 |
+
d = abs(args[0] - self.func(*args[1:]))/2
|
647 |
+
return (s + d if isinstance(self, Max) else s - d).rewrite(Abs)
|
648 |
+
|
649 |
+
def evalf(self, n=15, **options):
|
650 |
+
return self.func(*[a.evalf(n, **options) for a in self.args])
|
651 |
+
|
652 |
+
def n(self, *args, **kwargs):
|
653 |
+
return self.evalf(*args, **kwargs)
|
654 |
+
|
655 |
+
_eval_is_algebraic = lambda s: _torf(i.is_algebraic for i in s.args)
|
656 |
+
_eval_is_antihermitian = lambda s: _torf(i.is_antihermitian for i in s.args)
|
657 |
+
_eval_is_commutative = lambda s: _torf(i.is_commutative for i in s.args)
|
658 |
+
_eval_is_complex = lambda s: _torf(i.is_complex for i in s.args)
|
659 |
+
_eval_is_composite = lambda s: _torf(i.is_composite for i in s.args)
|
660 |
+
_eval_is_even = lambda s: _torf(i.is_even for i in s.args)
|
661 |
+
_eval_is_finite = lambda s: _torf(i.is_finite for i in s.args)
|
662 |
+
_eval_is_hermitian = lambda s: _torf(i.is_hermitian for i in s.args)
|
663 |
+
_eval_is_imaginary = lambda s: _torf(i.is_imaginary for i in s.args)
|
664 |
+
_eval_is_infinite = lambda s: _torf(i.is_infinite for i in s.args)
|
665 |
+
_eval_is_integer = lambda s: _torf(i.is_integer for i in s.args)
|
666 |
+
_eval_is_irrational = lambda s: _torf(i.is_irrational for i in s.args)
|
667 |
+
_eval_is_negative = lambda s: _torf(i.is_negative for i in s.args)
|
668 |
+
_eval_is_noninteger = lambda s: _torf(i.is_noninteger for i in s.args)
|
669 |
+
_eval_is_nonnegative = lambda s: _torf(i.is_nonnegative for i in s.args)
|
670 |
+
_eval_is_nonpositive = lambda s: _torf(i.is_nonpositive for i in s.args)
|
671 |
+
_eval_is_nonzero = lambda s: _torf(i.is_nonzero for i in s.args)
|
672 |
+
_eval_is_odd = lambda s: _torf(i.is_odd for i in s.args)
|
673 |
+
_eval_is_polar = lambda s: _torf(i.is_polar for i in s.args)
|
674 |
+
_eval_is_positive = lambda s: _torf(i.is_positive for i in s.args)
|
675 |
+
_eval_is_prime = lambda s: _torf(i.is_prime for i in s.args)
|
676 |
+
_eval_is_rational = lambda s: _torf(i.is_rational for i in s.args)
|
677 |
+
_eval_is_real = lambda s: _torf(i.is_real for i in s.args)
|
678 |
+
_eval_is_extended_real = lambda s: _torf(i.is_extended_real for i in s.args)
|
679 |
+
_eval_is_transcendental = lambda s: _torf(i.is_transcendental for i in s.args)
|
680 |
+
_eval_is_zero = lambda s: _torf(i.is_zero for i in s.args)
|
681 |
+
|
682 |
+
|
683 |
+
class Max(MinMaxBase, Application):
|
684 |
+
r"""
|
685 |
+
Return, if possible, the maximum value of the list.
|
686 |
+
|
687 |
+
When number of arguments is equal one, then
|
688 |
+
return this argument.
|
689 |
+
|
690 |
+
When number of arguments is equal two, then
|
691 |
+
return, if possible, the value from (a, b) that is $\ge$ the other.
|
692 |
+
|
693 |
+
In common case, when the length of list greater than 2, the task
|
694 |
+
is more complicated. Return only the arguments, which are greater
|
695 |
+
than others, if it is possible to determine directional relation.
|
696 |
+
|
697 |
+
If is not possible to determine such a relation, return a partially
|
698 |
+
evaluated result.
|
699 |
+
|
700 |
+
Assumptions are used to make the decision too.
|
701 |
+
|
702 |
+
Also, only comparable arguments are permitted.
|
703 |
+
|
704 |
+
It is named ``Max`` and not ``max`` to avoid conflicts
|
705 |
+
with the built-in function ``max``.
|
706 |
+
|
707 |
+
|
708 |
+
Examples
|
709 |
+
========
|
710 |
+
|
711 |
+
>>> from sympy import Max, Symbol, oo
|
712 |
+
>>> from sympy.abc import x, y, z
|
713 |
+
>>> p = Symbol('p', positive=True)
|
714 |
+
>>> n = Symbol('n', negative=True)
|
715 |
+
|
716 |
+
>>> Max(x, -2)
|
717 |
+
Max(-2, x)
|
718 |
+
>>> Max(x, -2).subs(x, 3)
|
719 |
+
3
|
720 |
+
>>> Max(p, -2)
|
721 |
+
p
|
722 |
+
>>> Max(x, y)
|
723 |
+
Max(x, y)
|
724 |
+
>>> Max(x, y) == Max(y, x)
|
725 |
+
True
|
726 |
+
>>> Max(x, Max(y, z))
|
727 |
+
Max(x, y, z)
|
728 |
+
>>> Max(n, 8, p, 7, -oo)
|
729 |
+
Max(8, p)
|
730 |
+
>>> Max (1, x, oo)
|
731 |
+
oo
|
732 |
+
|
733 |
+
* Algorithm
|
734 |
+
|
735 |
+
The task can be considered as searching of supremums in the
|
736 |
+
directed complete partial orders [1]_.
|
737 |
+
|
738 |
+
The source values are sequentially allocated by the isolated subsets
|
739 |
+
in which supremums are searched and result as Max arguments.
|
740 |
+
|
741 |
+
If the resulted supremum is single, then it is returned.
|
742 |
+
|
743 |
+
The isolated subsets are the sets of values which are only the comparable
|
744 |
+
with each other in the current set. E.g. natural numbers are comparable with
|
745 |
+
each other, but not comparable with the `x` symbol. Another example: the
|
746 |
+
symbol `x` with negative assumption is comparable with a natural number.
|
747 |
+
|
748 |
+
Also there are "least" elements, which are comparable with all others,
|
749 |
+
and have a zero property (maximum or minimum for all elements).
|
750 |
+
For example, in case of $\infty$, the allocation operation is terminated
|
751 |
+
and only this value is returned.
|
752 |
+
|
753 |
+
Assumption:
|
754 |
+
- if $A > B > C$ then $A > C$
|
755 |
+
- if $A = B$ then $B$ can be removed
|
756 |
+
|
757 |
+
References
|
758 |
+
==========
|
759 |
+
|
760 |
+
.. [1] https://en.wikipedia.org/wiki/Directed_complete_partial_order
|
761 |
+
.. [2] https://en.wikipedia.org/wiki/Lattice_%28order%29
|
762 |
+
|
763 |
+
See Also
|
764 |
+
========
|
765 |
+
|
766 |
+
Min : find minimum values
|
767 |
+
"""
|
768 |
+
zero = S.Infinity
|
769 |
+
identity = S.NegativeInfinity
|
770 |
+
|
771 |
+
def fdiff( self, argindex ):
|
772 |
+
from sympy.functions.special.delta_functions import Heaviside
|
773 |
+
n = len(self.args)
|
774 |
+
if 0 < argindex and argindex <= n:
|
775 |
+
argindex -= 1
|
776 |
+
if n == 2:
|
777 |
+
return Heaviside(self.args[argindex] - self.args[1 - argindex])
|
778 |
+
newargs = tuple([self.args[i] for i in range(n) if i != argindex])
|
779 |
+
return Heaviside(self.args[argindex] - Max(*newargs))
|
780 |
+
else:
|
781 |
+
raise ArgumentIndexError(self, argindex)
|
782 |
+
|
783 |
+
def _eval_rewrite_as_Heaviside(self, *args, **kwargs):
|
784 |
+
from sympy.functions.special.delta_functions import Heaviside
|
785 |
+
return Add(*[j*Mul(*[Heaviside(j - i) for i in args if i!=j]) \
|
786 |
+
for j in args])
|
787 |
+
|
788 |
+
def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
|
789 |
+
return _minmax_as_Piecewise('>=', *args)
|
790 |
+
|
791 |
+
def _eval_is_positive(self):
|
792 |
+
return fuzzy_or(a.is_positive for a in self.args)
|
793 |
+
|
794 |
+
def _eval_is_nonnegative(self):
|
795 |
+
return fuzzy_or(a.is_nonnegative for a in self.args)
|
796 |
+
|
797 |
+
def _eval_is_negative(self):
|
798 |
+
return fuzzy_and(a.is_negative for a in self.args)
|
799 |
+
|
800 |
+
|
801 |
+
class Min(MinMaxBase, Application):
|
802 |
+
"""
|
803 |
+
Return, if possible, the minimum value of the list.
|
804 |
+
It is named ``Min`` and not ``min`` to avoid conflicts
|
805 |
+
with the built-in function ``min``.
|
806 |
+
|
807 |
+
Examples
|
808 |
+
========
|
809 |
+
|
810 |
+
>>> from sympy import Min, Symbol, oo
|
811 |
+
>>> from sympy.abc import x, y
|
812 |
+
>>> p = Symbol('p', positive=True)
|
813 |
+
>>> n = Symbol('n', negative=True)
|
814 |
+
|
815 |
+
>>> Min(x, -2)
|
816 |
+
Min(-2, x)
|
817 |
+
>>> Min(x, -2).subs(x, 3)
|
818 |
+
-2
|
819 |
+
>>> Min(p, -3)
|
820 |
+
-3
|
821 |
+
>>> Min(x, y)
|
822 |
+
Min(x, y)
|
823 |
+
>>> Min(n, 8, p, -7, p, oo)
|
824 |
+
Min(-7, n)
|
825 |
+
|
826 |
+
See Also
|
827 |
+
========
|
828 |
+
|
829 |
+
Max : find maximum values
|
830 |
+
"""
|
831 |
+
zero = S.NegativeInfinity
|
832 |
+
identity = S.Infinity
|
833 |
+
|
834 |
+
def fdiff( self, argindex ):
|
835 |
+
from sympy.functions.special.delta_functions import Heaviside
|
836 |
+
n = len(self.args)
|
837 |
+
if 0 < argindex and argindex <= n:
|
838 |
+
argindex -= 1
|
839 |
+
if n == 2:
|
840 |
+
return Heaviside( self.args[1-argindex] - self.args[argindex] )
|
841 |
+
newargs = tuple([ self.args[i] for i in range(n) if i != argindex])
|
842 |
+
return Heaviside( Min(*newargs) - self.args[argindex] )
|
843 |
+
else:
|
844 |
+
raise ArgumentIndexError(self, argindex)
|
845 |
+
|
846 |
+
def _eval_rewrite_as_Heaviside(self, *args, **kwargs):
|
847 |
+
from sympy.functions.special.delta_functions import Heaviside
|
848 |
+
return Add(*[j*Mul(*[Heaviside(i-j) for i in args if i!=j]) \
|
849 |
+
for j in args])
|
850 |
+
|
851 |
+
def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
|
852 |
+
return _minmax_as_Piecewise('<=', *args)
|
853 |
+
|
854 |
+
def _eval_is_positive(self):
|
855 |
+
return fuzzy_and(a.is_positive for a in self.args)
|
856 |
+
|
857 |
+
def _eval_is_nonnegative(self):
|
858 |
+
return fuzzy_and(a.is_nonnegative for a in self.args)
|
859 |
+
|
860 |
+
def _eval_is_negative(self):
|
861 |
+
return fuzzy_or(a.is_negative for a in self.args)
|
862 |
+
|
863 |
+
|
864 |
+
class Rem(Function):
|
865 |
+
"""Returns the remainder when ``p`` is divided by ``q`` where ``p`` is finite
|
866 |
+
and ``q`` is not equal to zero. The result, ``p - int(p/q)*q``, has the same sign
|
867 |
+
as the divisor.
|
868 |
+
|
869 |
+
Parameters
|
870 |
+
==========
|
871 |
+
|
872 |
+
p : Expr
|
873 |
+
Dividend.
|
874 |
+
|
875 |
+
q : Expr
|
876 |
+
Divisor.
|
877 |
+
|
878 |
+
Notes
|
879 |
+
=====
|
880 |
+
|
881 |
+
``Rem`` corresponds to the ``%`` operator in C.
|
882 |
+
|
883 |
+
Examples
|
884 |
+
========
|
885 |
+
|
886 |
+
>>> from sympy.abc import x, y
|
887 |
+
>>> from sympy import Rem
|
888 |
+
>>> Rem(x**3, y)
|
889 |
+
Rem(x**3, y)
|
890 |
+
>>> Rem(x**3, y).subs({x: -5, y: 3})
|
891 |
+
-2
|
892 |
+
|
893 |
+
See Also
|
894 |
+
========
|
895 |
+
|
896 |
+
Mod
|
897 |
+
"""
|
898 |
+
kind = NumberKind
|
899 |
+
|
900 |
+
@classmethod
|
901 |
+
def eval(cls, p, q):
|
902 |
+
"""Return the function remainder if both p, q are numbers and q is not
|
903 |
+
zero.
|
904 |
+
"""
|
905 |
+
|
906 |
+
if q.is_zero:
|
907 |
+
raise ZeroDivisionError("Division by zero")
|
908 |
+
if p is S.NaN or q is S.NaN or p.is_finite is False or q.is_finite is False:
|
909 |
+
return S.NaN
|
910 |
+
if p is S.Zero or p in (q, -q) or (p.is_integer and q == 1):
|
911 |
+
return S.Zero
|
912 |
+
|
913 |
+
if q.is_Number:
|
914 |
+
if p.is_Number:
|
915 |
+
return p - Integer(p/q)*q
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/piecewise.py
ADDED
@@ -0,0 +1,1506 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import S, Function, diff, Tuple, Dummy, Mul
|
2 |
+
from sympy.core.basic import Basic, as_Basic
|
3 |
+
from sympy.core.numbers import Rational, NumberSymbol, _illegal
|
4 |
+
from sympy.core.parameters import global_parameters
|
5 |
+
from sympy.core.relational import (Lt, Gt, Eq, Ne, Relational,
|
6 |
+
_canonical, _canonical_coeff)
|
7 |
+
from sympy.core.sorting import ordered
|
8 |
+
from sympy.functions.elementary.miscellaneous import Max, Min
|
9 |
+
from sympy.logic.boolalg import (And, Boolean, distribute_and_over_or, Not,
|
10 |
+
true, false, Or, ITE, simplify_logic, to_cnf, distribute_or_over_and)
|
11 |
+
from sympy.utilities.iterables import uniq, sift, common_prefix
|
12 |
+
from sympy.utilities.misc import filldedent, func_name
|
13 |
+
|
14 |
+
from itertools import product
|
15 |
+
|
16 |
+
Undefined = S.NaN # Piecewise()
|
17 |
+
|
18 |
+
class ExprCondPair(Tuple):
|
19 |
+
"""Represents an expression, condition pair."""
|
20 |
+
|
21 |
+
def __new__(cls, expr, cond):
|
22 |
+
expr = as_Basic(expr)
|
23 |
+
if cond == True:
|
24 |
+
return Tuple.__new__(cls, expr, true)
|
25 |
+
elif cond == False:
|
26 |
+
return Tuple.__new__(cls, expr, false)
|
27 |
+
elif isinstance(cond, Basic) and cond.has(Piecewise):
|
28 |
+
cond = piecewise_fold(cond)
|
29 |
+
if isinstance(cond, Piecewise):
|
30 |
+
cond = cond.rewrite(ITE)
|
31 |
+
|
32 |
+
if not isinstance(cond, Boolean):
|
33 |
+
raise TypeError(filldedent('''
|
34 |
+
Second argument must be a Boolean,
|
35 |
+
not `%s`''' % func_name(cond)))
|
36 |
+
return Tuple.__new__(cls, expr, cond)
|
37 |
+
|
38 |
+
@property
|
39 |
+
def expr(self):
|
40 |
+
"""
|
41 |
+
Returns the expression of this pair.
|
42 |
+
"""
|
43 |
+
return self.args[0]
|
44 |
+
|
45 |
+
@property
|
46 |
+
def cond(self):
|
47 |
+
"""
|
48 |
+
Returns the condition of this pair.
|
49 |
+
"""
|
50 |
+
return self.args[1]
|
51 |
+
|
52 |
+
@property
|
53 |
+
def is_commutative(self):
|
54 |
+
return self.expr.is_commutative
|
55 |
+
|
56 |
+
def __iter__(self):
|
57 |
+
yield self.expr
|
58 |
+
yield self.cond
|
59 |
+
|
60 |
+
def _eval_simplify(self, **kwargs):
|
61 |
+
return self.func(*[a.simplify(**kwargs) for a in self.args])
|
62 |
+
|
63 |
+
|
64 |
+
class Piecewise(Function):
|
65 |
+
"""
|
66 |
+
Represents a piecewise function.
|
67 |
+
|
68 |
+
Usage:
|
69 |
+
|
70 |
+
Piecewise( (expr,cond), (expr,cond), ... )
|
71 |
+
- Each argument is a 2-tuple defining an expression and condition
|
72 |
+
- The conds are evaluated in turn returning the first that is True.
|
73 |
+
If any of the evaluated conds are not explicitly False,
|
74 |
+
e.g. ``x < 1``, the function is returned in symbolic form.
|
75 |
+
- If the function is evaluated at a place where all conditions are False,
|
76 |
+
nan will be returned.
|
77 |
+
- Pairs where the cond is explicitly False, will be removed and no pair
|
78 |
+
appearing after a True condition will ever be retained. If a single
|
79 |
+
pair with a True condition remains, it will be returned, even when
|
80 |
+
evaluation is False.
|
81 |
+
|
82 |
+
Examples
|
83 |
+
========
|
84 |
+
|
85 |
+
>>> from sympy import Piecewise, log, piecewise_fold
|
86 |
+
>>> from sympy.abc import x, y
|
87 |
+
>>> f = x**2
|
88 |
+
>>> g = log(x)
|
89 |
+
>>> p = Piecewise((0, x < -1), (f, x <= 1), (g, True))
|
90 |
+
>>> p.subs(x,1)
|
91 |
+
1
|
92 |
+
>>> p.subs(x,5)
|
93 |
+
log(5)
|
94 |
+
|
95 |
+
Booleans can contain Piecewise elements:
|
96 |
+
|
97 |
+
>>> cond = (x < y).subs(x, Piecewise((2, x < 0), (3, True))); cond
|
98 |
+
Piecewise((2, x < 0), (3, True)) < y
|
99 |
+
|
100 |
+
The folded version of this results in a Piecewise whose
|
101 |
+
expressions are Booleans:
|
102 |
+
|
103 |
+
>>> folded_cond = piecewise_fold(cond); folded_cond
|
104 |
+
Piecewise((2 < y, x < 0), (3 < y, True))
|
105 |
+
|
106 |
+
When a Boolean containing Piecewise (like cond) or a Piecewise
|
107 |
+
with Boolean expressions (like folded_cond) is used as a condition,
|
108 |
+
it is converted to an equivalent :class:`~.ITE` object:
|
109 |
+
|
110 |
+
>>> Piecewise((1, folded_cond))
|
111 |
+
Piecewise((1, ITE(x < 0, y > 2, y > 3)))
|
112 |
+
|
113 |
+
When a condition is an ``ITE``, it will be converted to a simplified
|
114 |
+
Boolean expression:
|
115 |
+
|
116 |
+
>>> piecewise_fold(_)
|
117 |
+
Piecewise((1, ((x >= 0) | (y > 2)) & ((y > 3) | (x < 0))))
|
118 |
+
|
119 |
+
See Also
|
120 |
+
========
|
121 |
+
|
122 |
+
piecewise_fold
|
123 |
+
piecewise_exclusive
|
124 |
+
ITE
|
125 |
+
"""
|
126 |
+
|
127 |
+
nargs = None
|
128 |
+
is_Piecewise = True
|
129 |
+
|
130 |
+
def __new__(cls, *args, **options):
|
131 |
+
if len(args) == 0:
|
132 |
+
raise TypeError("At least one (expr, cond) pair expected.")
|
133 |
+
# (Try to) sympify args first
|
134 |
+
newargs = []
|
135 |
+
for ec in args:
|
136 |
+
# ec could be a ExprCondPair or a tuple
|
137 |
+
pair = ExprCondPair(*getattr(ec, 'args', ec))
|
138 |
+
cond = pair.cond
|
139 |
+
if cond is false:
|
140 |
+
continue
|
141 |
+
newargs.append(pair)
|
142 |
+
if cond is true:
|
143 |
+
break
|
144 |
+
|
145 |
+
eval = options.pop('evaluate', global_parameters.evaluate)
|
146 |
+
if eval:
|
147 |
+
r = cls.eval(*newargs)
|
148 |
+
if r is not None:
|
149 |
+
return r
|
150 |
+
elif len(newargs) == 1 and newargs[0].cond == True:
|
151 |
+
return newargs[0].expr
|
152 |
+
|
153 |
+
return Basic.__new__(cls, *newargs, **options)
|
154 |
+
|
155 |
+
@classmethod
|
156 |
+
def eval(cls, *_args):
|
157 |
+
"""Either return a modified version of the args or, if no
|
158 |
+
modifications were made, return None.
|
159 |
+
|
160 |
+
Modifications that are made here:
|
161 |
+
|
162 |
+
1. relationals are made canonical
|
163 |
+
2. any False conditions are dropped
|
164 |
+
3. any repeat of a previous condition is ignored
|
165 |
+
4. any args past one with a true condition are dropped
|
166 |
+
|
167 |
+
If there are no args left, nan will be returned.
|
168 |
+
If there is a single arg with a True condition, its
|
169 |
+
corresponding expression will be returned.
|
170 |
+
|
171 |
+
EXAMPLES
|
172 |
+
========
|
173 |
+
|
174 |
+
>>> from sympy import Piecewise
|
175 |
+
>>> from sympy.abc import x
|
176 |
+
>>> cond = -x < -1
|
177 |
+
>>> args = [(1, cond), (4, cond), (3, False), (2, True), (5, x < 1)]
|
178 |
+
>>> Piecewise(*args, evaluate=False)
|
179 |
+
Piecewise((1, -x < -1), (4, -x < -1), (2, True))
|
180 |
+
>>> Piecewise(*args)
|
181 |
+
Piecewise((1, x > 1), (2, True))
|
182 |
+
"""
|
183 |
+
if not _args:
|
184 |
+
return Undefined
|
185 |
+
|
186 |
+
if len(_args) == 1 and _args[0][-1] == True:
|
187 |
+
return _args[0][0]
|
188 |
+
|
189 |
+
newargs = _piecewise_collapse_arguments(_args)
|
190 |
+
|
191 |
+
# some conditions may have been redundant
|
192 |
+
missing = len(newargs) != len(_args)
|
193 |
+
# some conditions may have changed
|
194 |
+
same = all(a == b for a, b in zip(newargs, _args))
|
195 |
+
# if either change happened we return the expr with the
|
196 |
+
# updated args
|
197 |
+
if not newargs:
|
198 |
+
raise ValueError(filldedent('''
|
199 |
+
There are no conditions (or none that
|
200 |
+
are not trivially false) to define an
|
201 |
+
expression.'''))
|
202 |
+
if missing or not same:
|
203 |
+
return cls(*newargs)
|
204 |
+
|
205 |
+
def doit(self, **hints):
|
206 |
+
"""
|
207 |
+
Evaluate this piecewise function.
|
208 |
+
"""
|
209 |
+
newargs = []
|
210 |
+
for e, c in self.args:
|
211 |
+
if hints.get('deep', True):
|
212 |
+
if isinstance(e, Basic):
|
213 |
+
newe = e.doit(**hints)
|
214 |
+
if newe != self:
|
215 |
+
e = newe
|
216 |
+
if isinstance(c, Basic):
|
217 |
+
c = c.doit(**hints)
|
218 |
+
newargs.append((e, c))
|
219 |
+
return self.func(*newargs)
|
220 |
+
|
221 |
+
def _eval_simplify(self, **kwargs):
|
222 |
+
return piecewise_simplify(self, **kwargs)
|
223 |
+
|
224 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
225 |
+
for e, c in self.args:
|
226 |
+
if c == True or c.subs(x, 0) == True:
|
227 |
+
return e.as_leading_term(x)
|
228 |
+
|
229 |
+
def _eval_adjoint(self):
|
230 |
+
return self.func(*[(e.adjoint(), c) for e, c in self.args])
|
231 |
+
|
232 |
+
def _eval_conjugate(self):
|
233 |
+
return self.func(*[(e.conjugate(), c) for e, c in self.args])
|
234 |
+
|
235 |
+
def _eval_derivative(self, x):
|
236 |
+
return self.func(*[(diff(e, x), c) for e, c in self.args])
|
237 |
+
|
238 |
+
def _eval_evalf(self, prec):
|
239 |
+
return self.func(*[(e._evalf(prec), c) for e, c in self.args])
|
240 |
+
|
241 |
+
def _eval_is_meromorphic(self, x, a):
|
242 |
+
# Conditions often implicitly assume that the argument is real.
|
243 |
+
# Hence, there needs to be some check for as_set.
|
244 |
+
if not a.is_real:
|
245 |
+
return None
|
246 |
+
|
247 |
+
# Then, scan ExprCondPairs in the given order to find a piece that would contain a,
|
248 |
+
# possibly as a boundary point.
|
249 |
+
for e, c in self.args:
|
250 |
+
cond = c.subs(x, a)
|
251 |
+
|
252 |
+
if cond.is_Relational:
|
253 |
+
return None
|
254 |
+
if a in c.as_set().boundary:
|
255 |
+
return None
|
256 |
+
# Apply expression if a is an interior point of the domain of e.
|
257 |
+
if cond:
|
258 |
+
return e._eval_is_meromorphic(x, a)
|
259 |
+
|
260 |
+
def piecewise_integrate(self, x, **kwargs):
|
261 |
+
"""Return the Piecewise with each expression being
|
262 |
+
replaced with its antiderivative. To obtain a continuous
|
263 |
+
antiderivative, use the :func:`~.integrate` function or method.
|
264 |
+
|
265 |
+
Examples
|
266 |
+
========
|
267 |
+
|
268 |
+
>>> from sympy import Piecewise
|
269 |
+
>>> from sympy.abc import x
|
270 |
+
>>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
|
271 |
+
>>> p.piecewise_integrate(x)
|
272 |
+
Piecewise((0, x < 0), (x, x < 1), (2*x, True))
|
273 |
+
|
274 |
+
Note that this does not give a continuous function, e.g.
|
275 |
+
at x = 1 the 3rd condition applies and the antiderivative
|
276 |
+
there is 2*x so the value of the antiderivative is 2:
|
277 |
+
|
278 |
+
>>> anti = _
|
279 |
+
>>> anti.subs(x, 1)
|
280 |
+
2
|
281 |
+
|
282 |
+
The continuous derivative accounts for the integral *up to*
|
283 |
+
the point of interest, however:
|
284 |
+
|
285 |
+
>>> p.integrate(x)
|
286 |
+
Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
|
287 |
+
>>> _.subs(x, 1)
|
288 |
+
1
|
289 |
+
|
290 |
+
See Also
|
291 |
+
========
|
292 |
+
Piecewise._eval_integral
|
293 |
+
"""
|
294 |
+
from sympy.integrals import integrate
|
295 |
+
return self.func(*[(integrate(e, x, **kwargs), c) for e, c in self.args])
|
296 |
+
|
297 |
+
def _handle_irel(self, x, handler):
|
298 |
+
"""Return either None (if the conditions of self depend only on x) else
|
299 |
+
a Piecewise expression whose expressions (handled by the handler that
|
300 |
+
was passed) are paired with the governing x-independent relationals,
|
301 |
+
e.g. Piecewise((A, a(x) & b(y)), (B, c(x) | c(y)) ->
|
302 |
+
Piecewise(
|
303 |
+
(handler(Piecewise((A, a(x) & True), (B, c(x) | True)), b(y) & c(y)),
|
304 |
+
(handler(Piecewise((A, a(x) & True), (B, c(x) | False)), b(y)),
|
305 |
+
(handler(Piecewise((A, a(x) & False), (B, c(x) | True)), c(y)),
|
306 |
+
(handler(Piecewise((A, a(x) & False), (B, c(x) | False)), True))
|
307 |
+
"""
|
308 |
+
# identify governing relationals
|
309 |
+
rel = self.atoms(Relational)
|
310 |
+
irel = list(ordered([r for r in rel if x not in r.free_symbols
|
311 |
+
and r not in (S.true, S.false)]))
|
312 |
+
if irel:
|
313 |
+
args = {}
|
314 |
+
exprinorder = []
|
315 |
+
for truth in product((1, 0), repeat=len(irel)):
|
316 |
+
reps = dict(zip(irel, truth))
|
317 |
+
# only store the true conditions since the false are implied
|
318 |
+
# when they appear lower in the Piecewise args
|
319 |
+
if 1 not in truth:
|
320 |
+
cond = None # flag this one so it doesn't get combined
|
321 |
+
else:
|
322 |
+
andargs = Tuple(*[i for i in reps if reps[i]])
|
323 |
+
free = list(andargs.free_symbols)
|
324 |
+
if len(free) == 1:
|
325 |
+
from sympy.solvers.inequalities import (
|
326 |
+
reduce_inequalities, _solve_inequality)
|
327 |
+
try:
|
328 |
+
t = reduce_inequalities(andargs, free[0])
|
329 |
+
# ValueError when there are potentially
|
330 |
+
# nonvanishing imaginary parts
|
331 |
+
except (ValueError, NotImplementedError):
|
332 |
+
# at least isolate free symbol on left
|
333 |
+
t = And(*[_solve_inequality(
|
334 |
+
a, free[0], linear=True)
|
335 |
+
for a in andargs])
|
336 |
+
else:
|
337 |
+
t = And(*andargs)
|
338 |
+
if t is S.false:
|
339 |
+
continue # an impossible combination
|
340 |
+
cond = t
|
341 |
+
expr = handler(self.xreplace(reps))
|
342 |
+
if isinstance(expr, self.func) and len(expr.args) == 1:
|
343 |
+
expr, econd = expr.args[0]
|
344 |
+
cond = And(econd, True if cond is None else cond)
|
345 |
+
# the ec pairs are being collected since all possibilities
|
346 |
+
# are being enumerated, but don't put the last one in since
|
347 |
+
# its expr might match a previous expression and it
|
348 |
+
# must appear last in the args
|
349 |
+
if cond is not None:
|
350 |
+
args.setdefault(expr, []).append(cond)
|
351 |
+
# but since we only store the true conditions we must maintain
|
352 |
+
# the order so that the expression with the most true values
|
353 |
+
# comes first
|
354 |
+
exprinorder.append(expr)
|
355 |
+
# convert collected conditions as args of Or
|
356 |
+
for k in args:
|
357 |
+
args[k] = Or(*args[k])
|
358 |
+
# take them in the order obtained
|
359 |
+
args = [(e, args[e]) for e in uniq(exprinorder)]
|
360 |
+
# add in the last arg
|
361 |
+
args.append((expr, True))
|
362 |
+
return Piecewise(*args)
|
363 |
+
|
364 |
+
def _eval_integral(self, x, _first=True, **kwargs):
|
365 |
+
"""Return the indefinite integral of the
|
366 |
+
Piecewise such that subsequent substitution of x with a
|
367 |
+
value will give the value of the integral (not including
|
368 |
+
the constant of integration) up to that point. To only
|
369 |
+
integrate the individual parts of Piecewise, use the
|
370 |
+
``piecewise_integrate`` method.
|
371 |
+
|
372 |
+
Examples
|
373 |
+
========
|
374 |
+
|
375 |
+
>>> from sympy import Piecewise
|
376 |
+
>>> from sympy.abc import x
|
377 |
+
>>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
|
378 |
+
>>> p.integrate(x)
|
379 |
+
Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
|
380 |
+
>>> p.piecewise_integrate(x)
|
381 |
+
Piecewise((0, x < 0), (x, x < 1), (2*x, True))
|
382 |
+
|
383 |
+
See Also
|
384 |
+
========
|
385 |
+
Piecewise.piecewise_integrate
|
386 |
+
"""
|
387 |
+
from sympy.integrals.integrals import integrate
|
388 |
+
|
389 |
+
if _first:
|
390 |
+
def handler(ipw):
|
391 |
+
if isinstance(ipw, self.func):
|
392 |
+
return ipw._eval_integral(x, _first=False, **kwargs)
|
393 |
+
else:
|
394 |
+
return ipw.integrate(x, **kwargs)
|
395 |
+
irv = self._handle_irel(x, handler)
|
396 |
+
if irv is not None:
|
397 |
+
return irv
|
398 |
+
|
399 |
+
# handle a Piecewise from -oo to oo with and no x-independent relationals
|
400 |
+
# -----------------------------------------------------------------------
|
401 |
+
ok, abei = self._intervals(x)
|
402 |
+
if not ok:
|
403 |
+
from sympy.integrals.integrals import Integral
|
404 |
+
return Integral(self, x) # unevaluated
|
405 |
+
|
406 |
+
pieces = [(a, b) for a, b, _, _ in abei]
|
407 |
+
oo = S.Infinity
|
408 |
+
done = [(-oo, oo, -1)]
|
409 |
+
for k, p in enumerate(pieces):
|
410 |
+
if p == (-oo, oo):
|
411 |
+
# all undone intervals will get this key
|
412 |
+
for j, (a, b, i) in enumerate(done):
|
413 |
+
if i == -1:
|
414 |
+
done[j] = a, b, k
|
415 |
+
break # nothing else to consider
|
416 |
+
N = len(done) - 1
|
417 |
+
for j, (a, b, i) in enumerate(reversed(done)):
|
418 |
+
if i == -1:
|
419 |
+
j = N - j
|
420 |
+
done[j: j + 1] = _clip(p, (a, b), k)
|
421 |
+
done = [(a, b, i) for a, b, i in done if a != b]
|
422 |
+
|
423 |
+
# append an arg if there is a hole so a reference to
|
424 |
+
# argument -1 will give Undefined
|
425 |
+
if any(i == -1 for (a, b, i) in done):
|
426 |
+
abei.append((-oo, oo, Undefined, -1))
|
427 |
+
|
428 |
+
# return the sum of the intervals
|
429 |
+
args = []
|
430 |
+
sum = None
|
431 |
+
for a, b, i in done:
|
432 |
+
anti = integrate(abei[i][-2], x, **kwargs)
|
433 |
+
if sum is None:
|
434 |
+
sum = anti
|
435 |
+
else:
|
436 |
+
sum = sum.subs(x, a)
|
437 |
+
e = anti._eval_interval(x, a, x)
|
438 |
+
if sum.has(*_illegal) or e.has(*_illegal):
|
439 |
+
sum = anti
|
440 |
+
else:
|
441 |
+
sum += e
|
442 |
+
# see if we know whether b is contained in original
|
443 |
+
# condition
|
444 |
+
if b is S.Infinity:
|
445 |
+
cond = True
|
446 |
+
elif self.args[abei[i][-1]].cond.subs(x, b) == False:
|
447 |
+
cond = (x < b)
|
448 |
+
else:
|
449 |
+
cond = (x <= b)
|
450 |
+
args.append((sum, cond))
|
451 |
+
return Piecewise(*args)
|
452 |
+
|
453 |
+
def _eval_interval(self, sym, a, b, _first=True):
|
454 |
+
"""Evaluates the function along the sym in a given interval [a, b]"""
|
455 |
+
# FIXME: Currently complex intervals are not supported. A possible
|
456 |
+
# replacement algorithm, discussed in issue 5227, can be found in the
|
457 |
+
# following papers;
|
458 |
+
# http://portal.acm.org/citation.cfm?id=281649
|
459 |
+
# http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.70.4127&rep=rep1&type=pdf
|
460 |
+
|
461 |
+
if a is None or b is None:
|
462 |
+
# In this case, it is just simple substitution
|
463 |
+
return super()._eval_interval(sym, a, b)
|
464 |
+
else:
|
465 |
+
x, lo, hi = map(as_Basic, (sym, a, b))
|
466 |
+
|
467 |
+
if _first: # get only x-dependent relationals
|
468 |
+
def handler(ipw):
|
469 |
+
if isinstance(ipw, self.func):
|
470 |
+
return ipw._eval_interval(x, lo, hi, _first=None)
|
471 |
+
else:
|
472 |
+
return ipw._eval_interval(x, lo, hi)
|
473 |
+
irv = self._handle_irel(x, handler)
|
474 |
+
if irv is not None:
|
475 |
+
return irv
|
476 |
+
|
477 |
+
if (lo < hi) is S.false or (
|
478 |
+
lo is S.Infinity or hi is S.NegativeInfinity):
|
479 |
+
rv = self._eval_interval(x, hi, lo, _first=False)
|
480 |
+
if isinstance(rv, Piecewise):
|
481 |
+
rv = Piecewise(*[(-e, c) for e, c in rv.args])
|
482 |
+
else:
|
483 |
+
rv = -rv
|
484 |
+
return rv
|
485 |
+
|
486 |
+
if (lo < hi) is S.true or (
|
487 |
+
hi is S.Infinity or lo is S.NegativeInfinity):
|
488 |
+
pass
|
489 |
+
else:
|
490 |
+
_a = Dummy('lo')
|
491 |
+
_b = Dummy('hi')
|
492 |
+
a = lo if lo.is_comparable else _a
|
493 |
+
b = hi if hi.is_comparable else _b
|
494 |
+
pos = self._eval_interval(x, a, b, _first=False)
|
495 |
+
if a == _a and b == _b:
|
496 |
+
# it's purely symbolic so just swap lo and hi and
|
497 |
+
# change the sign to get the value for when lo > hi
|
498 |
+
neg, pos = (-pos.xreplace({_a: hi, _b: lo}),
|
499 |
+
pos.xreplace({_a: lo, _b: hi}))
|
500 |
+
else:
|
501 |
+
# at least one of the bounds was comparable, so allow
|
502 |
+
# _eval_interval to use that information when computing
|
503 |
+
# the interval with lo and hi reversed
|
504 |
+
neg, pos = (-self._eval_interval(x, hi, lo, _first=False),
|
505 |
+
pos.xreplace({_a: lo, _b: hi}))
|
506 |
+
|
507 |
+
# allow simplification based on ordering of lo and hi
|
508 |
+
p = Dummy('', positive=True)
|
509 |
+
if lo.is_Symbol:
|
510 |
+
pos = pos.xreplace({lo: hi - p}).xreplace({p: hi - lo})
|
511 |
+
neg = neg.xreplace({lo: hi + p}).xreplace({p: lo - hi})
|
512 |
+
elif hi.is_Symbol:
|
513 |
+
pos = pos.xreplace({hi: lo + p}).xreplace({p: hi - lo})
|
514 |
+
neg = neg.xreplace({hi: lo - p}).xreplace({p: lo - hi})
|
515 |
+
# evaluate limits that may have unevaluate Min/Max
|
516 |
+
touch = lambda _: _.replace(
|
517 |
+
lambda x: isinstance(x, (Min, Max)),
|
518 |
+
lambda x: x.func(*x.args))
|
519 |
+
neg = touch(neg)
|
520 |
+
pos = touch(pos)
|
521 |
+
# assemble return expression; make the first condition be Lt
|
522 |
+
# b/c then the first expression will look the same whether
|
523 |
+
# the lo or hi limit is symbolic
|
524 |
+
if a == _a: # the lower limit was symbolic
|
525 |
+
rv = Piecewise(
|
526 |
+
(pos,
|
527 |
+
lo < hi),
|
528 |
+
(neg,
|
529 |
+
True))
|
530 |
+
else:
|
531 |
+
rv = Piecewise(
|
532 |
+
(neg,
|
533 |
+
hi < lo),
|
534 |
+
(pos,
|
535 |
+
True))
|
536 |
+
|
537 |
+
if rv == Undefined:
|
538 |
+
raise ValueError("Can't integrate across undefined region.")
|
539 |
+
if any(isinstance(i, Piecewise) for i in (pos, neg)):
|
540 |
+
rv = piecewise_fold(rv)
|
541 |
+
return rv
|
542 |
+
|
543 |
+
# handle a Piecewise with lo <= hi and no x-independent relationals
|
544 |
+
# -----------------------------------------------------------------
|
545 |
+
ok, abei = self._intervals(x)
|
546 |
+
if not ok:
|
547 |
+
from sympy.integrals.integrals import Integral
|
548 |
+
# not being able to do the interval of f(x) can
|
549 |
+
# be stated as not being able to do the integral
|
550 |
+
# of f'(x) over the same range
|
551 |
+
return Integral(self.diff(x), (x, lo, hi)) # unevaluated
|
552 |
+
|
553 |
+
pieces = [(a, b) for a, b, _, _ in abei]
|
554 |
+
done = [(lo, hi, -1)]
|
555 |
+
oo = S.Infinity
|
556 |
+
for k, p in enumerate(pieces):
|
557 |
+
if p[:2] == (-oo, oo):
|
558 |
+
# all undone intervals will get this key
|
559 |
+
for j, (a, b, i) in enumerate(done):
|
560 |
+
if i == -1:
|
561 |
+
done[j] = a, b, k
|
562 |
+
break # nothing else to consider
|
563 |
+
N = len(done) - 1
|
564 |
+
for j, (a, b, i) in enumerate(reversed(done)):
|
565 |
+
if i == -1:
|
566 |
+
j = N - j
|
567 |
+
done[j: j + 1] = _clip(p, (a, b), k)
|
568 |
+
done = [(a, b, i) for a, b, i in done if a != b]
|
569 |
+
|
570 |
+
# return the sum of the intervals
|
571 |
+
sum = S.Zero
|
572 |
+
upto = None
|
573 |
+
for a, b, i in done:
|
574 |
+
if i == -1:
|
575 |
+
if upto is None:
|
576 |
+
return Undefined
|
577 |
+
# TODO simplify hi <= upto
|
578 |
+
return Piecewise((sum, hi <= upto), (Undefined, True))
|
579 |
+
sum += abei[i][-2]._eval_interval(x, a, b)
|
580 |
+
upto = b
|
581 |
+
return sum
|
582 |
+
|
583 |
+
def _intervals(self, sym, err_on_Eq=False):
|
584 |
+
r"""Return a bool and a message (when bool is False), else a
|
585 |
+
list of unique tuples, (a, b, e, i), where a and b
|
586 |
+
are the lower and upper bounds in which the expression e of
|
587 |
+
argument i in self is defined and $a < b$ (when involving
|
588 |
+
numbers) or $a \le b$ when involving symbols.
|
589 |
+
|
590 |
+
If there are any relationals not involving sym, or any
|
591 |
+
relational cannot be solved for sym, the bool will be False
|
592 |
+
a message be given as the second return value. The calling
|
593 |
+
routine should have removed such relationals before calling
|
594 |
+
this routine.
|
595 |
+
|
596 |
+
The evaluated conditions will be returned as ranges.
|
597 |
+
Discontinuous ranges will be returned separately with
|
598 |
+
identical expressions. The first condition that evaluates to
|
599 |
+
True will be returned as the last tuple with a, b = -oo, oo.
|
600 |
+
"""
|
601 |
+
from sympy.solvers.inequalities import _solve_inequality
|
602 |
+
|
603 |
+
assert isinstance(self, Piecewise)
|
604 |
+
|
605 |
+
def nonsymfail(cond):
|
606 |
+
return False, filldedent('''
|
607 |
+
A condition not involving
|
608 |
+
%s appeared: %s''' % (sym, cond))
|
609 |
+
|
610 |
+
def _solve_relational(r):
|
611 |
+
if sym not in r.free_symbols:
|
612 |
+
return nonsymfail(r)
|
613 |
+
try:
|
614 |
+
rv = _solve_inequality(r, sym)
|
615 |
+
except NotImplementedError:
|
616 |
+
return False, 'Unable to solve relational %s for %s.' % (r, sym)
|
617 |
+
if isinstance(rv, Relational):
|
618 |
+
free = rv.args[1].free_symbols
|
619 |
+
if rv.args[0] != sym or sym in free:
|
620 |
+
return False, 'Unable to solve relational %s for %s.' % (r, sym)
|
621 |
+
if rv.rel_op == '==':
|
622 |
+
# this equality has been affirmed to have the form
|
623 |
+
# Eq(sym, rhs) where rhs is sym-free; it represents
|
624 |
+
# a zero-width interval which will be ignored
|
625 |
+
# whether it is an isolated condition or contained
|
626 |
+
# within an And or an Or
|
627 |
+
rv = S.false
|
628 |
+
elif rv.rel_op == '!=':
|
629 |
+
try:
|
630 |
+
rv = Or(sym < rv.rhs, sym > rv.rhs)
|
631 |
+
except TypeError:
|
632 |
+
# e.g. x != I ==> all real x satisfy
|
633 |
+
rv = S.true
|
634 |
+
elif rv == (S.NegativeInfinity < sym) & (sym < S.Infinity):
|
635 |
+
rv = S.true
|
636 |
+
return True, rv
|
637 |
+
|
638 |
+
args = list(self.args)
|
639 |
+
# make self canonical wrt Relationals
|
640 |
+
keys = self.atoms(Relational)
|
641 |
+
reps = {}
|
642 |
+
for r in keys:
|
643 |
+
ok, s = _solve_relational(r)
|
644 |
+
if ok != True:
|
645 |
+
return False, ok
|
646 |
+
reps[r] = s
|
647 |
+
# process args individually so if any evaluate, their position
|
648 |
+
# in the original Piecewise will be known
|
649 |
+
args = [i.xreplace(reps) for i in self.args]
|
650 |
+
|
651 |
+
# precondition args
|
652 |
+
expr_cond = []
|
653 |
+
default = idefault = None
|
654 |
+
for i, (expr, cond) in enumerate(args):
|
655 |
+
if cond is S.false:
|
656 |
+
continue
|
657 |
+
if cond is S.true:
|
658 |
+
default = expr
|
659 |
+
idefault = i
|
660 |
+
break
|
661 |
+
if isinstance(cond, Eq):
|
662 |
+
# unanticipated condition, but it is here in case a
|
663 |
+
# replacement caused an Eq to appear
|
664 |
+
if err_on_Eq:
|
665 |
+
return False, 'encountered Eq condition: %s' % cond
|
666 |
+
continue # zero width interval
|
667 |
+
|
668 |
+
cond = to_cnf(cond)
|
669 |
+
if isinstance(cond, And):
|
670 |
+
cond = distribute_or_over_and(cond)
|
671 |
+
|
672 |
+
if isinstance(cond, Or):
|
673 |
+
expr_cond.extend(
|
674 |
+
[(i, expr, o) for o in cond.args
|
675 |
+
if not isinstance(o, Eq)])
|
676 |
+
elif cond is not S.false:
|
677 |
+
expr_cond.append((i, expr, cond))
|
678 |
+
elif cond is S.true:
|
679 |
+
default = expr
|
680 |
+
idefault = i
|
681 |
+
break
|
682 |
+
|
683 |
+
# determine intervals represented by conditions
|
684 |
+
int_expr = []
|
685 |
+
for iarg, expr, cond in expr_cond:
|
686 |
+
if isinstance(cond, And):
|
687 |
+
lower = S.NegativeInfinity
|
688 |
+
upper = S.Infinity
|
689 |
+
exclude = []
|
690 |
+
for cond2 in cond.args:
|
691 |
+
if not isinstance(cond2, Relational):
|
692 |
+
return False, 'expecting only Relationals'
|
693 |
+
if isinstance(cond2, Eq):
|
694 |
+
lower = upper # ignore
|
695 |
+
if err_on_Eq:
|
696 |
+
return False, 'encountered secondary Eq condition'
|
697 |
+
break
|
698 |
+
elif isinstance(cond2, Ne):
|
699 |
+
l, r = cond2.args
|
700 |
+
if l == sym:
|
701 |
+
exclude.append(r)
|
702 |
+
elif r == sym:
|
703 |
+
exclude.append(l)
|
704 |
+
else:
|
705 |
+
return nonsymfail(cond2)
|
706 |
+
continue
|
707 |
+
elif cond2.lts == sym:
|
708 |
+
upper = Min(cond2.gts, upper)
|
709 |
+
elif cond2.gts == sym:
|
710 |
+
lower = Max(cond2.lts, lower)
|
711 |
+
else:
|
712 |
+
return nonsymfail(cond2) # should never get here
|
713 |
+
if exclude:
|
714 |
+
exclude = list(ordered(exclude))
|
715 |
+
newcond = []
|
716 |
+
for i, e in enumerate(exclude):
|
717 |
+
if e < lower == True or e > upper == True:
|
718 |
+
continue
|
719 |
+
if not newcond:
|
720 |
+
newcond.append((None, lower)) # add a primer
|
721 |
+
newcond.append((newcond[-1][1], e))
|
722 |
+
newcond.append((newcond[-1][1], upper))
|
723 |
+
newcond.pop(0) # remove the primer
|
724 |
+
expr_cond.extend([(iarg, expr, And(i[0] < sym, sym < i[1])) for i in newcond])
|
725 |
+
continue
|
726 |
+
elif isinstance(cond, Relational) and cond.rel_op != '!=':
|
727 |
+
lower, upper = cond.lts, cond.gts # part 1: initialize with givens
|
728 |
+
if cond.lts == sym: # part 1a: expand the side ...
|
729 |
+
lower = S.NegativeInfinity # e.g. x <= 0 ---> -oo <= 0
|
730 |
+
elif cond.gts == sym: # part 1a: ... that can be expanded
|
731 |
+
upper = S.Infinity # e.g. x >= 0 ---> oo >= 0
|
732 |
+
else:
|
733 |
+
return nonsymfail(cond)
|
734 |
+
else:
|
735 |
+
return False, 'unrecognized condition: %s' % cond
|
736 |
+
|
737 |
+
lower, upper = lower, Max(lower, upper)
|
738 |
+
if err_on_Eq and lower == upper:
|
739 |
+
return False, 'encountered Eq condition'
|
740 |
+
if (lower >= upper) is not S.true:
|
741 |
+
int_expr.append((lower, upper, expr, iarg))
|
742 |
+
|
743 |
+
if default is not None:
|
744 |
+
int_expr.append(
|
745 |
+
(S.NegativeInfinity, S.Infinity, default, idefault))
|
746 |
+
|
747 |
+
return True, list(uniq(int_expr))
|
748 |
+
|
749 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
750 |
+
args = [(ec.expr._eval_nseries(x, n, logx), ec.cond) for ec in self.args]
|
751 |
+
return self.func(*args)
|
752 |
+
|
753 |
+
def _eval_power(self, s):
|
754 |
+
return self.func(*[(e**s, c) for e, c in self.args])
|
755 |
+
|
756 |
+
def _eval_subs(self, old, new):
|
757 |
+
# this is strictly not necessary, but we can keep track
|
758 |
+
# of whether True or False conditions arise and be
|
759 |
+
# somewhat more efficient by avoiding other substitutions
|
760 |
+
# and avoiding invalid conditions that appear after a
|
761 |
+
# True condition
|
762 |
+
args = list(self.args)
|
763 |
+
args_exist = False
|
764 |
+
for i, (e, c) in enumerate(args):
|
765 |
+
c = c._subs(old, new)
|
766 |
+
if c != False:
|
767 |
+
args_exist = True
|
768 |
+
e = e._subs(old, new)
|
769 |
+
args[i] = (e, c)
|
770 |
+
if c == True:
|
771 |
+
break
|
772 |
+
if not args_exist:
|
773 |
+
args = ((Undefined, True),)
|
774 |
+
return self.func(*args)
|
775 |
+
|
776 |
+
def _eval_transpose(self):
|
777 |
+
return self.func(*[(e.transpose(), c) for e, c in self.args])
|
778 |
+
|
779 |
+
def _eval_template_is_attr(self, is_attr):
|
780 |
+
b = None
|
781 |
+
for expr, _ in self.args:
|
782 |
+
a = getattr(expr, is_attr)
|
783 |
+
if a is None:
|
784 |
+
return
|
785 |
+
if b is None:
|
786 |
+
b = a
|
787 |
+
elif b is not a:
|
788 |
+
return
|
789 |
+
return b
|
790 |
+
|
791 |
+
_eval_is_finite = lambda self: self._eval_template_is_attr(
|
792 |
+
'is_finite')
|
793 |
+
_eval_is_complex = lambda self: self._eval_template_is_attr('is_complex')
|
794 |
+
_eval_is_even = lambda self: self._eval_template_is_attr('is_even')
|
795 |
+
_eval_is_imaginary = lambda self: self._eval_template_is_attr(
|
796 |
+
'is_imaginary')
|
797 |
+
_eval_is_integer = lambda self: self._eval_template_is_attr('is_integer')
|
798 |
+
_eval_is_irrational = lambda self: self._eval_template_is_attr(
|
799 |
+
'is_irrational')
|
800 |
+
_eval_is_negative = lambda self: self._eval_template_is_attr('is_negative')
|
801 |
+
_eval_is_nonnegative = lambda self: self._eval_template_is_attr(
|
802 |
+
'is_nonnegative')
|
803 |
+
_eval_is_nonpositive = lambda self: self._eval_template_is_attr(
|
804 |
+
'is_nonpositive')
|
805 |
+
_eval_is_nonzero = lambda self: self._eval_template_is_attr(
|
806 |
+
'is_nonzero')
|
807 |
+
_eval_is_odd = lambda self: self._eval_template_is_attr('is_odd')
|
808 |
+
_eval_is_polar = lambda self: self._eval_template_is_attr('is_polar')
|
809 |
+
_eval_is_positive = lambda self: self._eval_template_is_attr('is_positive')
|
810 |
+
_eval_is_extended_real = lambda self: self._eval_template_is_attr(
|
811 |
+
'is_extended_real')
|
812 |
+
_eval_is_extended_positive = lambda self: self._eval_template_is_attr(
|
813 |
+
'is_extended_positive')
|
814 |
+
_eval_is_extended_negative = lambda self: self._eval_template_is_attr(
|
815 |
+
'is_extended_negative')
|
816 |
+
_eval_is_extended_nonzero = lambda self: self._eval_template_is_attr(
|
817 |
+
'is_extended_nonzero')
|
818 |
+
_eval_is_extended_nonpositive = lambda self: self._eval_template_is_attr(
|
819 |
+
'is_extended_nonpositive')
|
820 |
+
_eval_is_extended_nonnegative = lambda self: self._eval_template_is_attr(
|
821 |
+
'is_extended_nonnegative')
|
822 |
+
_eval_is_real = lambda self: self._eval_template_is_attr('is_real')
|
823 |
+
_eval_is_zero = lambda self: self._eval_template_is_attr(
|
824 |
+
'is_zero')
|
825 |
+
|
826 |
+
@classmethod
|
827 |
+
def __eval_cond(cls, cond):
|
828 |
+
"""Return the truth value of the condition."""
|
829 |
+
if cond == True:
|
830 |
+
return True
|
831 |
+
if isinstance(cond, Eq):
|
832 |
+
try:
|
833 |
+
diff = cond.lhs - cond.rhs
|
834 |
+
if diff.is_commutative:
|
835 |
+
return diff.is_zero
|
836 |
+
except TypeError:
|
837 |
+
pass
|
838 |
+
|
839 |
+
def as_expr_set_pairs(self, domain=None):
|
840 |
+
"""Return tuples for each argument of self that give
|
841 |
+
the expression and the interval in which it is valid
|
842 |
+
which is contained within the given domain.
|
843 |
+
If a condition cannot be converted to a set, an error
|
844 |
+
will be raised. The variable of the conditions is
|
845 |
+
assumed to be real; sets of real values are returned.
|
846 |
+
|
847 |
+
Examples
|
848 |
+
========
|
849 |
+
|
850 |
+
>>> from sympy import Piecewise, Interval
|
851 |
+
>>> from sympy.abc import x
|
852 |
+
>>> p = Piecewise(
|
853 |
+
... (1, x < 2),
|
854 |
+
... (2,(x > 0) & (x < 4)),
|
855 |
+
... (3, True))
|
856 |
+
>>> p.as_expr_set_pairs()
|
857 |
+
[(1, Interval.open(-oo, 2)),
|
858 |
+
(2, Interval.Ropen(2, 4)),
|
859 |
+
(3, Interval(4, oo))]
|
860 |
+
>>> p.as_expr_set_pairs(Interval(0, 3))
|
861 |
+
[(1, Interval.Ropen(0, 2)),
|
862 |
+
(2, Interval(2, 3))]
|
863 |
+
"""
|
864 |
+
if domain is None:
|
865 |
+
domain = S.Reals
|
866 |
+
exp_sets = []
|
867 |
+
U = domain
|
868 |
+
complex = not domain.is_subset(S.Reals)
|
869 |
+
cond_free = set()
|
870 |
+
for expr, cond in self.args:
|
871 |
+
cond_free |= cond.free_symbols
|
872 |
+
if len(cond_free) > 1:
|
873 |
+
raise NotImplementedError(filldedent('''
|
874 |
+
multivariate conditions are not handled.'''))
|
875 |
+
if complex:
|
876 |
+
for i in cond.atoms(Relational):
|
877 |
+
if not isinstance(i, (Eq, Ne)):
|
878 |
+
raise ValueError(filldedent('''
|
879 |
+
Inequalities in the complex domain are
|
880 |
+
not supported. Try the real domain by
|
881 |
+
setting domain=S.Reals'''))
|
882 |
+
cond_int = U.intersect(cond.as_set())
|
883 |
+
U = U - cond_int
|
884 |
+
if cond_int != S.EmptySet:
|
885 |
+
exp_sets.append((expr, cond_int))
|
886 |
+
return exp_sets
|
887 |
+
|
888 |
+
def _eval_rewrite_as_ITE(self, *args, **kwargs):
|
889 |
+
byfree = {}
|
890 |
+
args = list(args)
|
891 |
+
default = any(c == True for b, c in args)
|
892 |
+
for i, (b, c) in enumerate(args):
|
893 |
+
if not isinstance(b, Boolean) and b != True:
|
894 |
+
raise TypeError(filldedent('''
|
895 |
+
Expecting Boolean or bool but got `%s`
|
896 |
+
''' % func_name(b)))
|
897 |
+
if c == True:
|
898 |
+
break
|
899 |
+
# loop over independent conditions for this b
|
900 |
+
for c in c.args if isinstance(c, Or) else [c]:
|
901 |
+
free = c.free_symbols
|
902 |
+
x = free.pop()
|
903 |
+
try:
|
904 |
+
byfree[x] = byfree.setdefault(
|
905 |
+
x, S.EmptySet).union(c.as_set())
|
906 |
+
except NotImplementedError:
|
907 |
+
if not default:
|
908 |
+
raise NotImplementedError(filldedent('''
|
909 |
+
A method to determine whether a multivariate
|
910 |
+
conditional is consistent with a complete coverage
|
911 |
+
of all variables has not been implemented so the
|
912 |
+
rewrite is being stopped after encountering `%s`.
|
913 |
+
This error would not occur if a default expression
|
914 |
+
like `(foo, True)` were given.
|
915 |
+
''' % c))
|
916 |
+
if byfree[x] in (S.UniversalSet, S.Reals):
|
917 |
+
# collapse the ith condition to True and break
|
918 |
+
args[i] = list(args[i])
|
919 |
+
c = args[i][1] = True
|
920 |
+
break
|
921 |
+
if c == True:
|
922 |
+
break
|
923 |
+
if c != True:
|
924 |
+
raise ValueError(filldedent('''
|
925 |
+
Conditions must cover all reals or a final default
|
926 |
+
condition `(foo, True)` must be given.
|
927 |
+
'''))
|
928 |
+
last, _ = args[i] # ignore all past ith arg
|
929 |
+
for a, c in reversed(args[:i]):
|
930 |
+
last = ITE(c, a, last)
|
931 |
+
return _canonical(last)
|
932 |
+
|
933 |
+
def _eval_rewrite_as_KroneckerDelta(self, *args):
|
934 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
935 |
+
|
936 |
+
rules = {
|
937 |
+
And: [False, False],
|
938 |
+
Or: [True, True],
|
939 |
+
Not: [True, False],
|
940 |
+
Eq: [None, None],
|
941 |
+
Ne: [None, None]
|
942 |
+
}
|
943 |
+
|
944 |
+
class UnrecognizedCondition(Exception):
|
945 |
+
pass
|
946 |
+
|
947 |
+
def rewrite(cond):
|
948 |
+
if isinstance(cond, Eq):
|
949 |
+
return KroneckerDelta(*cond.args)
|
950 |
+
if isinstance(cond, Ne):
|
951 |
+
return 1 - KroneckerDelta(*cond.args)
|
952 |
+
|
953 |
+
cls, args = type(cond), cond.args
|
954 |
+
if cls not in rules:
|
955 |
+
raise UnrecognizedCondition(cls)
|
956 |
+
|
957 |
+
b1, b2 = rules[cls]
|
958 |
+
k = Mul(*[1 - rewrite(c) for c in args]) if b1 else Mul(*[rewrite(c) for c in args])
|
959 |
+
|
960 |
+
if b2:
|
961 |
+
return 1 - k
|
962 |
+
return k
|
963 |
+
|
964 |
+
conditions = []
|
965 |
+
true_value = None
|
966 |
+
for value, cond in args:
|
967 |
+
if type(cond) in rules:
|
968 |
+
conditions.append((value, cond))
|
969 |
+
elif cond is S.true:
|
970 |
+
if true_value is None:
|
971 |
+
true_value = value
|
972 |
+
else:
|
973 |
+
return
|
974 |
+
|
975 |
+
if true_value is not None:
|
976 |
+
result = true_value
|
977 |
+
|
978 |
+
for value, cond in conditions[::-1]:
|
979 |
+
try:
|
980 |
+
k = rewrite(cond)
|
981 |
+
result = k * value + (1 - k) * result
|
982 |
+
except UnrecognizedCondition:
|
983 |
+
return
|
984 |
+
|
985 |
+
return result
|
986 |
+
|
987 |
+
|
988 |
+
def piecewise_fold(expr, evaluate=True):
|
989 |
+
"""
|
990 |
+
Takes an expression containing a piecewise function and returns the
|
991 |
+
expression in piecewise form. In addition, any ITE conditions are
|
992 |
+
rewritten in negation normal form and simplified.
|
993 |
+
|
994 |
+
The final Piecewise is evaluated (default) but if the raw form
|
995 |
+
is desired, send ``evaluate=False``; if trivial evaluation is
|
996 |
+
desired, send ``evaluate=None`` and duplicate conditions and
|
997 |
+
processing of True and False will be handled.
|
998 |
+
|
999 |
+
Examples
|
1000 |
+
========
|
1001 |
+
|
1002 |
+
>>> from sympy import Piecewise, piecewise_fold, S
|
1003 |
+
>>> from sympy.abc import x
|
1004 |
+
>>> p = Piecewise((x, x < 1), (1, S(1) <= x))
|
1005 |
+
>>> piecewise_fold(x*p)
|
1006 |
+
Piecewise((x**2, x < 1), (x, True))
|
1007 |
+
|
1008 |
+
See Also
|
1009 |
+
========
|
1010 |
+
|
1011 |
+
Piecewise
|
1012 |
+
piecewise_exclusive
|
1013 |
+
"""
|
1014 |
+
if not isinstance(expr, Basic) or not expr.has(Piecewise):
|
1015 |
+
return expr
|
1016 |
+
|
1017 |
+
new_args = []
|
1018 |
+
if isinstance(expr, (ExprCondPair, Piecewise)):
|
1019 |
+
for e, c in expr.args:
|
1020 |
+
if not isinstance(e, Piecewise):
|
1021 |
+
e = piecewise_fold(e)
|
1022 |
+
# we don't keep Piecewise in condition because
|
1023 |
+
# it has to be checked to see that it's complete
|
1024 |
+
# and we convert it to ITE at that time
|
1025 |
+
assert not c.has(Piecewise) # pragma: no cover
|
1026 |
+
if isinstance(c, ITE):
|
1027 |
+
c = c.to_nnf()
|
1028 |
+
c = simplify_logic(c, form='cnf')
|
1029 |
+
if isinstance(e, Piecewise):
|
1030 |
+
new_args.extend([(piecewise_fold(ei), And(ci, c))
|
1031 |
+
for ei, ci in e.args])
|
1032 |
+
else:
|
1033 |
+
new_args.append((e, c))
|
1034 |
+
else:
|
1035 |
+
# Given
|
1036 |
+
# P1 = Piecewise((e11, c1), (e12, c2), A)
|
1037 |
+
# P2 = Piecewise((e21, c1), (e22, c2), B)
|
1038 |
+
# ...
|
1039 |
+
# the folding of f(P1, P2) is trivially
|
1040 |
+
# Piecewise(
|
1041 |
+
# (f(e11, e21), c1),
|
1042 |
+
# (f(e12, e22), c2),
|
1043 |
+
# (f(Piecewise(A), Piecewise(B)), True))
|
1044 |
+
# Certain objects end up rewriting themselves as thus, so
|
1045 |
+
# we do that grouping before the more generic folding.
|
1046 |
+
# The following applies this idea when f = Add or f = Mul
|
1047 |
+
# (and the expression is commutative).
|
1048 |
+
if expr.is_Add or expr.is_Mul and expr.is_commutative:
|
1049 |
+
p, args = sift(expr.args, lambda x: x.is_Piecewise, binary=True)
|
1050 |
+
pc = sift(p, lambda x: tuple([c for e,c in x.args]))
|
1051 |
+
for c in list(ordered(pc)):
|
1052 |
+
if len(pc[c]) > 1:
|
1053 |
+
pargs = [list(i.args) for i in pc[c]]
|
1054 |
+
# the first one is the same; there may be more
|
1055 |
+
com = common_prefix(*[
|
1056 |
+
[i.cond for i in j] for j in pargs])
|
1057 |
+
n = len(com)
|
1058 |
+
collected = []
|
1059 |
+
for i in range(n):
|
1060 |
+
collected.append((
|
1061 |
+
expr.func(*[ai[i].expr for ai in pargs]),
|
1062 |
+
com[i]))
|
1063 |
+
remains = []
|
1064 |
+
for a in pargs:
|
1065 |
+
if n == len(a): # no more args
|
1066 |
+
continue
|
1067 |
+
if a[n].cond == True: # no longer Piecewise
|
1068 |
+
remains.append(a[n].expr)
|
1069 |
+
else: # restore the remaining Piecewise
|
1070 |
+
remains.append(
|
1071 |
+
Piecewise(*a[n:], evaluate=False))
|
1072 |
+
if remains:
|
1073 |
+
collected.append((expr.func(*remains), True))
|
1074 |
+
args.append(Piecewise(*collected, evaluate=False))
|
1075 |
+
continue
|
1076 |
+
args.extend(pc[c])
|
1077 |
+
else:
|
1078 |
+
args = expr.args
|
1079 |
+
# fold
|
1080 |
+
folded = list(map(piecewise_fold, args))
|
1081 |
+
for ec in product(*[
|
1082 |
+
(i.args if isinstance(i, Piecewise) else
|
1083 |
+
[(i, true)]) for i in folded]):
|
1084 |
+
e, c = zip(*ec)
|
1085 |
+
new_args.append((expr.func(*e), And(*c)))
|
1086 |
+
|
1087 |
+
if evaluate is None:
|
1088 |
+
# don't return duplicate conditions, otherwise don't evaluate
|
1089 |
+
new_args = list(reversed([(e, c) for c, e in {
|
1090 |
+
c: e for e, c in reversed(new_args)}.items()]))
|
1091 |
+
rv = Piecewise(*new_args, evaluate=evaluate)
|
1092 |
+
if evaluate is None and len(rv.args) == 1 and rv.args[0].cond == True:
|
1093 |
+
return rv.args[0].expr
|
1094 |
+
if any(s.expr.has(Piecewise) for p in rv.atoms(Piecewise) for s in p.args):
|
1095 |
+
return piecewise_fold(rv)
|
1096 |
+
return rv
|
1097 |
+
|
1098 |
+
|
1099 |
+
def _clip(A, B, k):
|
1100 |
+
"""Return interval B as intervals that are covered by A (keyed
|
1101 |
+
to k) and all other intervals of B not covered by A keyed to -1.
|
1102 |
+
|
1103 |
+
The reference point of each interval is the rhs; if the lhs is
|
1104 |
+
greater than the rhs then an interval of zero width interval will
|
1105 |
+
result, e.g. (4, 1) is treated like (1, 1).
|
1106 |
+
|
1107 |
+
Examples
|
1108 |
+
========
|
1109 |
+
|
1110 |
+
>>> from sympy.functions.elementary.piecewise import _clip
|
1111 |
+
>>> from sympy import Tuple
|
1112 |
+
>>> A = Tuple(1, 3)
|
1113 |
+
>>> B = Tuple(2, 4)
|
1114 |
+
>>> _clip(A, B, 0)
|
1115 |
+
[(2, 3, 0), (3, 4, -1)]
|
1116 |
+
|
1117 |
+
Interpretation: interval portion (2, 3) of interval (2, 4) is
|
1118 |
+
covered by interval (1, 3) and is keyed to 0 as requested;
|
1119 |
+
interval (3, 4) was not covered by (1, 3) and is keyed to -1.
|
1120 |
+
"""
|
1121 |
+
a, b = B
|
1122 |
+
c, d = A
|
1123 |
+
c, d = Min(Max(c, a), b), Min(Max(d, a), b)
|
1124 |
+
a, b = Min(a, b), b
|
1125 |
+
p = []
|
1126 |
+
if a != c:
|
1127 |
+
p.append((a, c, -1))
|
1128 |
+
else:
|
1129 |
+
pass
|
1130 |
+
if c != d:
|
1131 |
+
p.append((c, d, k))
|
1132 |
+
else:
|
1133 |
+
pass
|
1134 |
+
if b != d:
|
1135 |
+
if d == c and p and p[-1][-1] == -1:
|
1136 |
+
p[-1] = p[-1][0], b, -1
|
1137 |
+
else:
|
1138 |
+
p.append((d, b, -1))
|
1139 |
+
else:
|
1140 |
+
pass
|
1141 |
+
|
1142 |
+
return p
|
1143 |
+
|
1144 |
+
|
1145 |
+
def piecewise_simplify_arguments(expr, **kwargs):
|
1146 |
+
from sympy.simplify.simplify import simplify
|
1147 |
+
|
1148 |
+
# simplify conditions
|
1149 |
+
f1 = expr.args[0].cond.free_symbols
|
1150 |
+
args = None
|
1151 |
+
if len(f1) == 1 and not expr.atoms(Eq):
|
1152 |
+
x = f1.pop()
|
1153 |
+
# this won't return intervals involving Eq
|
1154 |
+
# and it won't handle symbols treated as
|
1155 |
+
# booleans
|
1156 |
+
ok, abe_ = expr._intervals(x, err_on_Eq=True)
|
1157 |
+
def include(c, x, a):
|
1158 |
+
"return True if c.subs(x, a) is True, else False"
|
1159 |
+
try:
|
1160 |
+
return c.subs(x, a) == True
|
1161 |
+
except TypeError:
|
1162 |
+
return False
|
1163 |
+
if ok:
|
1164 |
+
args = []
|
1165 |
+
covered = S.EmptySet
|
1166 |
+
from sympy.sets.sets import Interval
|
1167 |
+
for a, b, e, i in abe_:
|
1168 |
+
c = expr.args[i].cond
|
1169 |
+
incl_a = include(c, x, a)
|
1170 |
+
incl_b = include(c, x, b)
|
1171 |
+
iv = Interval(a, b, not incl_a, not incl_b)
|
1172 |
+
cset = iv - covered
|
1173 |
+
if not cset:
|
1174 |
+
continue
|
1175 |
+
if incl_a and incl_b:
|
1176 |
+
if a.is_infinite and b.is_infinite:
|
1177 |
+
c = S.true
|
1178 |
+
elif b.is_infinite:
|
1179 |
+
c = (x >= a)
|
1180 |
+
elif a in covered or a.is_infinite:
|
1181 |
+
c = (x <= b)
|
1182 |
+
else:
|
1183 |
+
c = And(a <= x, x <= b)
|
1184 |
+
elif incl_a:
|
1185 |
+
if a in covered or a.is_infinite:
|
1186 |
+
c = (x < b)
|
1187 |
+
else:
|
1188 |
+
c = And(a <= x, x < b)
|
1189 |
+
elif incl_b:
|
1190 |
+
if b.is_infinite:
|
1191 |
+
c = (x > a)
|
1192 |
+
else:
|
1193 |
+
c = (x <= b)
|
1194 |
+
else:
|
1195 |
+
if a in covered:
|
1196 |
+
c = (x < b)
|
1197 |
+
else:
|
1198 |
+
c = And(a < x, x < b)
|
1199 |
+
covered |= iv
|
1200 |
+
if a is S.NegativeInfinity and incl_a:
|
1201 |
+
covered |= {S.NegativeInfinity}
|
1202 |
+
if b is S.Infinity and incl_b:
|
1203 |
+
covered |= {S.Infinity}
|
1204 |
+
args.append((e, c))
|
1205 |
+
if not S.Reals.is_subset(covered):
|
1206 |
+
args.append((Undefined, True))
|
1207 |
+
if args is None:
|
1208 |
+
args = list(expr.args)
|
1209 |
+
for i in range(len(args)):
|
1210 |
+
e, c = args[i]
|
1211 |
+
if isinstance(c, Basic):
|
1212 |
+
c = simplify(c, **kwargs)
|
1213 |
+
args[i] = (e, c)
|
1214 |
+
|
1215 |
+
# simplify expressions
|
1216 |
+
doit = kwargs.pop('doit', None)
|
1217 |
+
for i in range(len(args)):
|
1218 |
+
e, c = args[i]
|
1219 |
+
if isinstance(e, Basic):
|
1220 |
+
# Skip doit to avoid growth at every call for some integrals
|
1221 |
+
# and sums, see sympy/sympy#17165
|
1222 |
+
newe = simplify(e, doit=False, **kwargs)
|
1223 |
+
if newe != e:
|
1224 |
+
e = newe
|
1225 |
+
args[i] = (e, c)
|
1226 |
+
|
1227 |
+
# restore kwargs flag
|
1228 |
+
if doit is not None:
|
1229 |
+
kwargs['doit'] = doit
|
1230 |
+
|
1231 |
+
return Piecewise(*args)
|
1232 |
+
|
1233 |
+
|
1234 |
+
def _piecewise_collapse_arguments(_args):
|
1235 |
+
newargs = [] # the unevaluated conditions
|
1236 |
+
current_cond = set() # the conditions up to a given e, c pair
|
1237 |
+
for expr, cond in _args:
|
1238 |
+
cond = cond.replace(
|
1239 |
+
lambda _: _.is_Relational, _canonical_coeff)
|
1240 |
+
# Check here if expr is a Piecewise and collapse if one of
|
1241 |
+
# the conds in expr matches cond. This allows the collapsing
|
1242 |
+
# of Piecewise((Piecewise((x,x<0)),x<0)) to Piecewise((x,x<0)).
|
1243 |
+
# This is important when using piecewise_fold to simplify
|
1244 |
+
# multiple Piecewise instances having the same conds.
|
1245 |
+
# Eventually, this code should be able to collapse Piecewise's
|
1246 |
+
# having different intervals, but this will probably require
|
1247 |
+
# using the new assumptions.
|
1248 |
+
if isinstance(expr, Piecewise):
|
1249 |
+
unmatching = []
|
1250 |
+
for i, (e, c) in enumerate(expr.args):
|
1251 |
+
if c in current_cond:
|
1252 |
+
# this would already have triggered
|
1253 |
+
continue
|
1254 |
+
if c == cond:
|
1255 |
+
if c != True:
|
1256 |
+
# nothing past this condition will ever
|
1257 |
+
# trigger and only those args before this
|
1258 |
+
# that didn't match a previous condition
|
1259 |
+
# could possibly trigger
|
1260 |
+
if unmatching:
|
1261 |
+
expr = Piecewise(*(
|
1262 |
+
unmatching + [(e, c)]))
|
1263 |
+
else:
|
1264 |
+
expr = e
|
1265 |
+
break
|
1266 |
+
else:
|
1267 |
+
unmatching.append((e, c))
|
1268 |
+
|
1269 |
+
# check for condition repeats
|
1270 |
+
got = False
|
1271 |
+
# -- if an And contains a condition that was
|
1272 |
+
# already encountered, then the And will be
|
1273 |
+
# False: if the previous condition was False
|
1274 |
+
# then the And will be False and if the previous
|
1275 |
+
# condition is True then then we wouldn't get to
|
1276 |
+
# this point. In either case, we can skip this condition.
|
1277 |
+
for i in ([cond] +
|
1278 |
+
(list(cond.args) if isinstance(cond, And) else
|
1279 |
+
[])):
|
1280 |
+
if i in current_cond:
|
1281 |
+
got = True
|
1282 |
+
break
|
1283 |
+
if got:
|
1284 |
+
continue
|
1285 |
+
|
1286 |
+
# -- if not(c) is already in current_cond then c is
|
1287 |
+
# a redundant condition in an And. This does not
|
1288 |
+
# apply to Or, however: (e1, c), (e2, Or(~c, d))
|
1289 |
+
# is not (e1, c), (e2, d) because if c and d are
|
1290 |
+
# both False this would give no results when the
|
1291 |
+
# true answer should be (e2, True)
|
1292 |
+
if isinstance(cond, And):
|
1293 |
+
nonredundant = []
|
1294 |
+
for c in cond.args:
|
1295 |
+
if isinstance(c, Relational):
|
1296 |
+
if c.negated.canonical in current_cond:
|
1297 |
+
continue
|
1298 |
+
# if a strict inequality appears after
|
1299 |
+
# a non-strict one, then the condition is
|
1300 |
+
# redundant
|
1301 |
+
if isinstance(c, (Lt, Gt)) and (
|
1302 |
+
c.weak in current_cond):
|
1303 |
+
cond = False
|
1304 |
+
break
|
1305 |
+
nonredundant.append(c)
|
1306 |
+
else:
|
1307 |
+
cond = cond.func(*nonredundant)
|
1308 |
+
elif isinstance(cond, Relational):
|
1309 |
+
if cond.negated.canonical in current_cond:
|
1310 |
+
cond = S.true
|
1311 |
+
|
1312 |
+
current_cond.add(cond)
|
1313 |
+
|
1314 |
+
# collect successive e,c pairs when exprs or cond match
|
1315 |
+
if newargs:
|
1316 |
+
if newargs[-1].expr == expr:
|
1317 |
+
orcond = Or(cond, newargs[-1].cond)
|
1318 |
+
if isinstance(orcond, (And, Or)):
|
1319 |
+
orcond = distribute_and_over_or(orcond)
|
1320 |
+
newargs[-1] = ExprCondPair(expr, orcond)
|
1321 |
+
continue
|
1322 |
+
elif newargs[-1].cond == cond:
|
1323 |
+
continue
|
1324 |
+
newargs.append(ExprCondPair(expr, cond))
|
1325 |
+
return newargs
|
1326 |
+
|
1327 |
+
|
1328 |
+
_blessed = lambda e: getattr(e.lhs, '_diff_wrt', False) and (
|
1329 |
+
getattr(e.rhs, '_diff_wrt', None) or
|
1330 |
+
isinstance(e.rhs, (Rational, NumberSymbol)))
|
1331 |
+
|
1332 |
+
|
1333 |
+
def piecewise_simplify(expr, **kwargs):
|
1334 |
+
expr = piecewise_simplify_arguments(expr, **kwargs)
|
1335 |
+
if not isinstance(expr, Piecewise):
|
1336 |
+
return expr
|
1337 |
+
args = list(expr.args)
|
1338 |
+
|
1339 |
+
args = _piecewise_simplify_eq_and(args)
|
1340 |
+
args = _piecewise_simplify_equal_to_next_segment(args)
|
1341 |
+
return Piecewise(*args)
|
1342 |
+
|
1343 |
+
|
1344 |
+
def _piecewise_simplify_equal_to_next_segment(args):
|
1345 |
+
"""
|
1346 |
+
See if expressions valid for an Equal expression happens to evaluate
|
1347 |
+
to the same function as in the next piecewise segment, see:
|
1348 |
+
https://github.com/sympy/sympy/issues/8458
|
1349 |
+
"""
|
1350 |
+
prevexpr = None
|
1351 |
+
for i, (expr, cond) in reversed(list(enumerate(args))):
|
1352 |
+
if prevexpr is not None:
|
1353 |
+
if isinstance(cond, And):
|
1354 |
+
eqs, other = sift(cond.args,
|
1355 |
+
lambda i: isinstance(i, Eq), binary=True)
|
1356 |
+
elif isinstance(cond, Eq):
|
1357 |
+
eqs, other = [cond], []
|
1358 |
+
else:
|
1359 |
+
eqs = other = []
|
1360 |
+
_prevexpr = prevexpr
|
1361 |
+
_expr = expr
|
1362 |
+
if eqs and not other:
|
1363 |
+
eqs = list(ordered(eqs))
|
1364 |
+
for e in eqs:
|
1365 |
+
# allow 2 args to collapse into 1 for any e
|
1366 |
+
# otherwise limit simplification to only simple-arg
|
1367 |
+
# Eq instances
|
1368 |
+
if len(args) == 2 or _blessed(e):
|
1369 |
+
_prevexpr = _prevexpr.subs(*e.args)
|
1370 |
+
_expr = _expr.subs(*e.args)
|
1371 |
+
# Did it evaluate to the same?
|
1372 |
+
if _prevexpr == _expr:
|
1373 |
+
# Set the expression for the Not equal section to the same
|
1374 |
+
# as the next. These will be merged when creating the new
|
1375 |
+
# Piecewise
|
1376 |
+
args[i] = args[i].func(args[i + 1][0], cond)
|
1377 |
+
else:
|
1378 |
+
# Update the expression that we compare against
|
1379 |
+
prevexpr = expr
|
1380 |
+
else:
|
1381 |
+
prevexpr = expr
|
1382 |
+
return args
|
1383 |
+
|
1384 |
+
|
1385 |
+
def _piecewise_simplify_eq_and(args):
|
1386 |
+
"""
|
1387 |
+
Try to simplify conditions and the expression for
|
1388 |
+
equalities that are part of the condition, e.g.
|
1389 |
+
Piecewise((n, And(Eq(n,0), Eq(n + m, 0))), (1, True))
|
1390 |
+
-> Piecewise((0, And(Eq(n, 0), Eq(m, 0))), (1, True))
|
1391 |
+
"""
|
1392 |
+
for i, (expr, cond) in enumerate(args):
|
1393 |
+
if isinstance(cond, And):
|
1394 |
+
eqs, other = sift(cond.args,
|
1395 |
+
lambda i: isinstance(i, Eq), binary=True)
|
1396 |
+
elif isinstance(cond, Eq):
|
1397 |
+
eqs, other = [cond], []
|
1398 |
+
else:
|
1399 |
+
eqs = other = []
|
1400 |
+
if eqs:
|
1401 |
+
eqs = list(ordered(eqs))
|
1402 |
+
for j, e in enumerate(eqs):
|
1403 |
+
# these blessed lhs objects behave like Symbols
|
1404 |
+
# and the rhs are simple replacements for the "symbols"
|
1405 |
+
if _blessed(e):
|
1406 |
+
expr = expr.subs(*e.args)
|
1407 |
+
eqs[j + 1:] = [ei.subs(*e.args) for ei in eqs[j + 1:]]
|
1408 |
+
other = [ei.subs(*e.args) for ei in other]
|
1409 |
+
cond = And(*(eqs + other))
|
1410 |
+
args[i] = args[i].func(expr, cond)
|
1411 |
+
return args
|
1412 |
+
|
1413 |
+
|
1414 |
+
def piecewise_exclusive(expr, *, skip_nan=False, deep=True):
|
1415 |
+
"""
|
1416 |
+
Rewrite :class:`Piecewise` with mutually exclusive conditions.
|
1417 |
+
|
1418 |
+
Explanation
|
1419 |
+
===========
|
1420 |
+
|
1421 |
+
SymPy represents the conditions of a :class:`Piecewise` in an
|
1422 |
+
"if-elif"-fashion, allowing more than one condition to be simultaneously
|
1423 |
+
True. The interpretation is that the first condition that is True is the
|
1424 |
+
case that holds. While this is a useful representation computationally it
|
1425 |
+
is not how a piecewise formula is typically shown in a mathematical text.
|
1426 |
+
The :func:`piecewise_exclusive` function can be used to rewrite any
|
1427 |
+
:class:`Piecewise` with more typical mutually exclusive conditions.
|
1428 |
+
|
1429 |
+
Note that further manipulation of the resulting :class:`Piecewise`, e.g.
|
1430 |
+
simplifying it, will most likely make it non-exclusive. Hence, this is
|
1431 |
+
primarily a function to be used in conjunction with printing the Piecewise
|
1432 |
+
or if one would like to reorder the expression-condition pairs.
|
1433 |
+
|
1434 |
+
If it is not possible to determine that all possibilities are covered by
|
1435 |
+
the different cases of the :class:`Piecewise` then a final
|
1436 |
+
:class:`~sympy.core.numbers.NaN` case will be included explicitly. This
|
1437 |
+
can be prevented by passing ``skip_nan=True``.
|
1438 |
+
|
1439 |
+
Examples
|
1440 |
+
========
|
1441 |
+
|
1442 |
+
>>> from sympy import piecewise_exclusive, Symbol, Piecewise, S
|
1443 |
+
>>> x = Symbol('x', real=True)
|
1444 |
+
>>> p = Piecewise((0, x < 0), (S.Half, x <= 0), (1, True))
|
1445 |
+
>>> piecewise_exclusive(p)
|
1446 |
+
Piecewise((0, x < 0), (1/2, Eq(x, 0)), (1, x > 0))
|
1447 |
+
>>> piecewise_exclusive(Piecewise((2, x > 1)))
|
1448 |
+
Piecewise((2, x > 1), (nan, x <= 1))
|
1449 |
+
>>> piecewise_exclusive(Piecewise((2, x > 1)), skip_nan=True)
|
1450 |
+
Piecewise((2, x > 1))
|
1451 |
+
|
1452 |
+
Parameters
|
1453 |
+
==========
|
1454 |
+
|
1455 |
+
expr: a SymPy expression.
|
1456 |
+
Any :class:`Piecewise` in the expression will be rewritten.
|
1457 |
+
skip_nan: ``bool`` (default ``False``)
|
1458 |
+
If ``skip_nan`` is set to ``True`` then a final
|
1459 |
+
:class:`~sympy.core.numbers.NaN` case will not be included.
|
1460 |
+
deep: ``bool`` (default ``True``)
|
1461 |
+
If ``deep`` is ``True`` then :func:`piecewise_exclusive` will rewrite
|
1462 |
+
any :class:`Piecewise` subexpressions in ``expr`` rather than just
|
1463 |
+
rewriting ``expr`` itself.
|
1464 |
+
|
1465 |
+
Returns
|
1466 |
+
=======
|
1467 |
+
|
1468 |
+
An expression equivalent to ``expr`` but where all :class:`Piecewise` have
|
1469 |
+
been rewritten with mutually exclusive conditions.
|
1470 |
+
|
1471 |
+
See Also
|
1472 |
+
========
|
1473 |
+
|
1474 |
+
Piecewise
|
1475 |
+
piecewise_fold
|
1476 |
+
"""
|
1477 |
+
|
1478 |
+
def make_exclusive(*pwargs):
|
1479 |
+
|
1480 |
+
cumcond = false
|
1481 |
+
newargs = []
|
1482 |
+
|
1483 |
+
# Handle the first n-1 cases
|
1484 |
+
for expr_i, cond_i in pwargs[:-1]:
|
1485 |
+
cancond = And(cond_i, Not(cumcond)).simplify()
|
1486 |
+
cumcond = Or(cond_i, cumcond).simplify()
|
1487 |
+
newargs.append((expr_i, cancond))
|
1488 |
+
|
1489 |
+
# For the nth case defer simplification of cumcond
|
1490 |
+
expr_n, cond_n = pwargs[-1]
|
1491 |
+
cancond_n = And(cond_n, Not(cumcond)).simplify()
|
1492 |
+
newargs.append((expr_n, cancond_n))
|
1493 |
+
|
1494 |
+
if not skip_nan:
|
1495 |
+
cumcond = Or(cond_n, cumcond).simplify()
|
1496 |
+
if cumcond is not true:
|
1497 |
+
newargs.append((Undefined, Not(cumcond).simplify()))
|
1498 |
+
|
1499 |
+
return Piecewise(*newargs, evaluate=False)
|
1500 |
+
|
1501 |
+
if deep:
|
1502 |
+
return expr.replace(Piecewise, make_exclusive)
|
1503 |
+
elif isinstance(expr, Piecewise):
|
1504 |
+
return make_exclusive(*expr.args)
|
1505 |
+
else:
|
1506 |
+
return expr
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_complexes.py
ADDED
@@ -0,0 +1,1018 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.expr import Expr
|
2 |
+
from sympy.core.function import (Derivative, Function, Lambda, expand)
|
3 |
+
from sympy.core.numbers import (E, I, Rational, comp, nan, oo, pi, zoo)
|
4 |
+
from sympy.core.relational import Eq
|
5 |
+
from sympy.core.singleton import S
|
6 |
+
from sympy.core.symbol import (Symbol, symbols)
|
7 |
+
from sympy.functions.elementary.complexes import (Abs, adjoint, arg, conjugate, im, re, sign, transpose)
|
8 |
+
from sympy.functions.elementary.exponential import (exp, exp_polar, log)
|
9 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
10 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
11 |
+
from sympy.functions.elementary.trigonometric import (acos, atan, atan2, cos, sin)
|
12 |
+
from sympy.functions.special.delta_functions import (DiracDelta, Heaviside)
|
13 |
+
from sympy.integrals.integrals import Integral
|
14 |
+
from sympy.matrices.dense import Matrix
|
15 |
+
from sympy.matrices.expressions.funcmatrix import FunctionMatrix
|
16 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
17 |
+
from sympy.matrices.immutable import (ImmutableMatrix, ImmutableSparseMatrix)
|
18 |
+
from sympy.matrices import SparseMatrix
|
19 |
+
from sympy.sets.sets import Interval
|
20 |
+
from sympy.core.expr import unchanged
|
21 |
+
from sympy.core.function import ArgumentIndexError
|
22 |
+
from sympy.testing.pytest import XFAIL, raises, _both_exp_pow
|
23 |
+
|
24 |
+
|
25 |
+
def N_equals(a, b):
|
26 |
+
"""Check whether two complex numbers are numerically close"""
|
27 |
+
return comp(a.n(), b.n(), 1.e-6)
|
28 |
+
|
29 |
+
|
30 |
+
def test_re():
|
31 |
+
x, y = symbols('x,y')
|
32 |
+
a, b = symbols('a,b', real=True)
|
33 |
+
|
34 |
+
r = Symbol('r', real=True)
|
35 |
+
i = Symbol('i', imaginary=True)
|
36 |
+
|
37 |
+
assert re(nan) is nan
|
38 |
+
|
39 |
+
assert re(oo) is oo
|
40 |
+
assert re(-oo) is -oo
|
41 |
+
|
42 |
+
assert re(0) == 0
|
43 |
+
|
44 |
+
assert re(1) == 1
|
45 |
+
assert re(-1) == -1
|
46 |
+
|
47 |
+
assert re(E) == E
|
48 |
+
assert re(-E) == -E
|
49 |
+
|
50 |
+
assert unchanged(re, x)
|
51 |
+
assert re(x*I) == -im(x)
|
52 |
+
assert re(r*I) == 0
|
53 |
+
assert re(r) == r
|
54 |
+
assert re(i*I) == I * i
|
55 |
+
assert re(i) == 0
|
56 |
+
|
57 |
+
assert re(x + y) == re(x) + re(y)
|
58 |
+
assert re(x + r) == re(x) + r
|
59 |
+
|
60 |
+
assert re(re(x)) == re(x)
|
61 |
+
|
62 |
+
assert re(2 + I) == 2
|
63 |
+
assert re(x + I) == re(x)
|
64 |
+
|
65 |
+
assert re(x + y*I) == re(x) - im(y)
|
66 |
+
assert re(x + r*I) == re(x)
|
67 |
+
|
68 |
+
assert re(log(2*I)) == log(2)
|
69 |
+
|
70 |
+
assert re((2 + I)**2).expand(complex=True) == 3
|
71 |
+
|
72 |
+
assert re(conjugate(x)) == re(x)
|
73 |
+
assert conjugate(re(x)) == re(x)
|
74 |
+
|
75 |
+
assert re(x).as_real_imag() == (re(x), 0)
|
76 |
+
|
77 |
+
assert re(i*r*x).diff(r) == re(i*x)
|
78 |
+
assert re(i*r*x).diff(i) == I*r*im(x)
|
79 |
+
|
80 |
+
assert re(
|
81 |
+
sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)
|
82 |
+
assert re(a * (2 + b*I)) == 2*a
|
83 |
+
|
84 |
+
assert re((1 + sqrt(a + b*I))/2) == \
|
85 |
+
(a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)/2 + S.Half
|
86 |
+
|
87 |
+
assert re(x).rewrite(im) == x - S.ImaginaryUnit*im(x)
|
88 |
+
assert (x + re(y)).rewrite(re, im) == x + y - S.ImaginaryUnit*im(y)
|
89 |
+
|
90 |
+
a = Symbol('a', algebraic=True)
|
91 |
+
t = Symbol('t', transcendental=True)
|
92 |
+
x = Symbol('x')
|
93 |
+
assert re(a).is_algebraic
|
94 |
+
assert re(x).is_algebraic is None
|
95 |
+
assert re(t).is_algebraic is False
|
96 |
+
|
97 |
+
assert re(S.ComplexInfinity) is S.NaN
|
98 |
+
|
99 |
+
n, m, l = symbols('n m l')
|
100 |
+
A = MatrixSymbol('A',n,m)
|
101 |
+
assert re(A) == (S.Half) * (A + conjugate(A))
|
102 |
+
|
103 |
+
A = Matrix([[1 + 4*I,2],[0, -3*I]])
|
104 |
+
assert re(A) == Matrix([[1, 2],[0, 0]])
|
105 |
+
|
106 |
+
A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]])
|
107 |
+
assert re(A) == ImmutableMatrix([[1, 3],[0, 0]])
|
108 |
+
|
109 |
+
X = SparseMatrix([[2*j + i*I for i in range(5)] for j in range(5)])
|
110 |
+
assert re(X) - Matrix([[0, 0, 0, 0, 0],
|
111 |
+
[2, 2, 2, 2, 2],
|
112 |
+
[4, 4, 4, 4, 4],
|
113 |
+
[6, 6, 6, 6, 6],
|
114 |
+
[8, 8, 8, 8, 8]]) == Matrix.zeros(5)
|
115 |
+
|
116 |
+
assert im(X) - Matrix([[0, 1, 2, 3, 4],
|
117 |
+
[0, 1, 2, 3, 4],
|
118 |
+
[0, 1, 2, 3, 4],
|
119 |
+
[0, 1, 2, 3, 4],
|
120 |
+
[0, 1, 2, 3, 4]]) == Matrix.zeros(5)
|
121 |
+
|
122 |
+
X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I))
|
123 |
+
assert re(X) == Matrix([[0, 0, 0], [1, 1, 1], [2, 2, 2]])
|
124 |
+
|
125 |
+
|
126 |
+
def test_im():
|
127 |
+
x, y = symbols('x,y')
|
128 |
+
a, b = symbols('a,b', real=True)
|
129 |
+
|
130 |
+
r = Symbol('r', real=True)
|
131 |
+
i = Symbol('i', imaginary=True)
|
132 |
+
|
133 |
+
assert im(nan) is nan
|
134 |
+
|
135 |
+
assert im(oo*I) is oo
|
136 |
+
assert im(-oo*I) is -oo
|
137 |
+
|
138 |
+
assert im(0) == 0
|
139 |
+
|
140 |
+
assert im(1) == 0
|
141 |
+
assert im(-1) == 0
|
142 |
+
|
143 |
+
assert im(E*I) == E
|
144 |
+
assert im(-E*I) == -E
|
145 |
+
|
146 |
+
assert unchanged(im, x)
|
147 |
+
assert im(x*I) == re(x)
|
148 |
+
assert im(r*I) == r
|
149 |
+
assert im(r) == 0
|
150 |
+
assert im(i*I) == 0
|
151 |
+
assert im(i) == -I * i
|
152 |
+
|
153 |
+
assert im(x + y) == im(x) + im(y)
|
154 |
+
assert im(x + r) == im(x)
|
155 |
+
assert im(x + r*I) == im(x) + r
|
156 |
+
|
157 |
+
assert im(im(x)*I) == im(x)
|
158 |
+
|
159 |
+
assert im(2 + I) == 1
|
160 |
+
assert im(x + I) == im(x) + 1
|
161 |
+
|
162 |
+
assert im(x + y*I) == im(x) + re(y)
|
163 |
+
assert im(x + r*I) == im(x) + r
|
164 |
+
|
165 |
+
assert im(log(2*I)) == pi/2
|
166 |
+
|
167 |
+
assert im((2 + I)**2).expand(complex=True) == 4
|
168 |
+
|
169 |
+
assert im(conjugate(x)) == -im(x)
|
170 |
+
assert conjugate(im(x)) == im(x)
|
171 |
+
|
172 |
+
assert im(x).as_real_imag() == (im(x), 0)
|
173 |
+
|
174 |
+
assert im(i*r*x).diff(r) == im(i*x)
|
175 |
+
assert im(i*r*x).diff(i) == -I * re(r*x)
|
176 |
+
|
177 |
+
assert im(
|
178 |
+
sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)
|
179 |
+
assert im(a * (2 + b*I)) == a*b
|
180 |
+
|
181 |
+
assert im((1 + sqrt(a + b*I))/2) == \
|
182 |
+
(a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2
|
183 |
+
|
184 |
+
assert im(x).rewrite(re) == -S.ImaginaryUnit * (x - re(x))
|
185 |
+
assert (x + im(y)).rewrite(im, re) == x - S.ImaginaryUnit * (y - re(y))
|
186 |
+
|
187 |
+
a = Symbol('a', algebraic=True)
|
188 |
+
t = Symbol('t', transcendental=True)
|
189 |
+
x = Symbol('x')
|
190 |
+
assert re(a).is_algebraic
|
191 |
+
assert re(x).is_algebraic is None
|
192 |
+
assert re(t).is_algebraic is False
|
193 |
+
|
194 |
+
assert im(S.ComplexInfinity) is S.NaN
|
195 |
+
|
196 |
+
n, m, l = symbols('n m l')
|
197 |
+
A = MatrixSymbol('A',n,m)
|
198 |
+
|
199 |
+
assert im(A) == (S.One/(2*I)) * (A - conjugate(A))
|
200 |
+
|
201 |
+
A = Matrix([[1 + 4*I, 2],[0, -3*I]])
|
202 |
+
assert im(A) == Matrix([[4, 0],[0, -3]])
|
203 |
+
|
204 |
+
A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]])
|
205 |
+
assert im(A) == ImmutableMatrix([[3, -2],[0, 2]])
|
206 |
+
|
207 |
+
X = ImmutableSparseMatrix(
|
208 |
+
[[i*I + i for i in range(5)] for i in range(5)])
|
209 |
+
Y = SparseMatrix([list(range(5)) for i in range(5)])
|
210 |
+
assert im(X).as_immutable() == Y
|
211 |
+
|
212 |
+
X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I))
|
213 |
+
assert im(X) == Matrix([[0, 1, 2], [0, 1, 2], [0, 1, 2]])
|
214 |
+
|
215 |
+
def test_sign():
|
216 |
+
assert sign(1.2) == 1
|
217 |
+
assert sign(-1.2) == -1
|
218 |
+
assert sign(3*I) == I
|
219 |
+
assert sign(-3*I) == -I
|
220 |
+
assert sign(0) == 0
|
221 |
+
assert sign(0, evaluate=False).doit() == 0
|
222 |
+
assert sign(oo, evaluate=False).doit() == 1
|
223 |
+
assert sign(nan) is nan
|
224 |
+
assert sign(2 + 2*I).doit() == sqrt(2)*(2 + 2*I)/4
|
225 |
+
assert sign(2 + 3*I).simplify() == sign(2 + 3*I)
|
226 |
+
assert sign(2 + 2*I).simplify() == sign(1 + I)
|
227 |
+
assert sign(im(sqrt(1 - sqrt(3)))) == 1
|
228 |
+
assert sign(sqrt(1 - sqrt(3))) == I
|
229 |
+
|
230 |
+
x = Symbol('x')
|
231 |
+
assert sign(x).is_finite is True
|
232 |
+
assert sign(x).is_complex is True
|
233 |
+
assert sign(x).is_imaginary is None
|
234 |
+
assert sign(x).is_integer is None
|
235 |
+
assert sign(x).is_real is None
|
236 |
+
assert sign(x).is_zero is None
|
237 |
+
assert sign(x).doit() == sign(x)
|
238 |
+
assert sign(1.2*x) == sign(x)
|
239 |
+
assert sign(2*x) == sign(x)
|
240 |
+
assert sign(I*x) == I*sign(x)
|
241 |
+
assert sign(-2*I*x) == -I*sign(x)
|
242 |
+
assert sign(conjugate(x)) == conjugate(sign(x))
|
243 |
+
|
244 |
+
p = Symbol('p', positive=True)
|
245 |
+
n = Symbol('n', negative=True)
|
246 |
+
m = Symbol('m', negative=True)
|
247 |
+
assert sign(2*p*x) == sign(x)
|
248 |
+
assert sign(n*x) == -sign(x)
|
249 |
+
assert sign(n*m*x) == sign(x)
|
250 |
+
|
251 |
+
x = Symbol('x', imaginary=True)
|
252 |
+
assert sign(x).is_imaginary is True
|
253 |
+
assert sign(x).is_integer is False
|
254 |
+
assert sign(x).is_real is False
|
255 |
+
assert sign(x).is_zero is False
|
256 |
+
assert sign(x).diff(x) == 2*DiracDelta(-I*x)
|
257 |
+
assert sign(x).doit() == x / Abs(x)
|
258 |
+
assert conjugate(sign(x)) == -sign(x)
|
259 |
+
|
260 |
+
x = Symbol('x', real=True)
|
261 |
+
assert sign(x).is_imaginary is False
|
262 |
+
assert sign(x).is_integer is True
|
263 |
+
assert sign(x).is_real is True
|
264 |
+
assert sign(x).is_zero is None
|
265 |
+
assert sign(x).diff(x) == 2*DiracDelta(x)
|
266 |
+
assert sign(x).doit() == sign(x)
|
267 |
+
assert conjugate(sign(x)) == sign(x)
|
268 |
+
|
269 |
+
x = Symbol('x', nonzero=True)
|
270 |
+
assert sign(x).is_imaginary is False
|
271 |
+
assert sign(x).is_integer is True
|
272 |
+
assert sign(x).is_real is True
|
273 |
+
assert sign(x).is_zero is False
|
274 |
+
assert sign(x).doit() == x / Abs(x)
|
275 |
+
assert sign(Abs(x)) == 1
|
276 |
+
assert Abs(sign(x)) == 1
|
277 |
+
|
278 |
+
x = Symbol('x', positive=True)
|
279 |
+
assert sign(x).is_imaginary is False
|
280 |
+
assert sign(x).is_integer is True
|
281 |
+
assert sign(x).is_real is True
|
282 |
+
assert sign(x).is_zero is False
|
283 |
+
assert sign(x).doit() == x / Abs(x)
|
284 |
+
assert sign(Abs(x)) == 1
|
285 |
+
assert Abs(sign(x)) == 1
|
286 |
+
|
287 |
+
x = 0
|
288 |
+
assert sign(x).is_imaginary is False
|
289 |
+
assert sign(x).is_integer is True
|
290 |
+
assert sign(x).is_real is True
|
291 |
+
assert sign(x).is_zero is True
|
292 |
+
assert sign(x).doit() == 0
|
293 |
+
assert sign(Abs(x)) == 0
|
294 |
+
assert Abs(sign(x)) == 0
|
295 |
+
|
296 |
+
nz = Symbol('nz', nonzero=True, integer=True)
|
297 |
+
assert sign(nz).is_imaginary is False
|
298 |
+
assert sign(nz).is_integer is True
|
299 |
+
assert sign(nz).is_real is True
|
300 |
+
assert sign(nz).is_zero is False
|
301 |
+
assert sign(nz)**2 == 1
|
302 |
+
assert (sign(nz)**3).args == (sign(nz), 3)
|
303 |
+
|
304 |
+
assert sign(Symbol('x', nonnegative=True)).is_nonnegative
|
305 |
+
assert sign(Symbol('x', nonnegative=True)).is_nonpositive is None
|
306 |
+
assert sign(Symbol('x', nonpositive=True)).is_nonnegative is None
|
307 |
+
assert sign(Symbol('x', nonpositive=True)).is_nonpositive
|
308 |
+
assert sign(Symbol('x', real=True)).is_nonnegative is None
|
309 |
+
assert sign(Symbol('x', real=True)).is_nonpositive is None
|
310 |
+
assert sign(Symbol('x', real=True, zero=False)).is_nonpositive is None
|
311 |
+
|
312 |
+
x, y = Symbol('x', real=True), Symbol('y')
|
313 |
+
f = Function('f')
|
314 |
+
assert sign(x).rewrite(Piecewise) == \
|
315 |
+
Piecewise((1, x > 0), (-1, x < 0), (0, True))
|
316 |
+
assert sign(y).rewrite(Piecewise) == sign(y)
|
317 |
+
assert sign(x).rewrite(Heaviside) == 2*Heaviside(x, H0=S(1)/2) - 1
|
318 |
+
assert sign(y).rewrite(Heaviside) == sign(y)
|
319 |
+
assert sign(y).rewrite(Abs) == Piecewise((0, Eq(y, 0)), (y/Abs(y), True))
|
320 |
+
assert sign(f(y)).rewrite(Abs) == Piecewise((0, Eq(f(y), 0)), (f(y)/Abs(f(y)), True))
|
321 |
+
|
322 |
+
# evaluate what can be evaluated
|
323 |
+
assert sign(exp_polar(I*pi)*pi) is S.NegativeOne
|
324 |
+
|
325 |
+
eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
|
326 |
+
# if there is a fast way to know when and when you cannot prove an
|
327 |
+
# expression like this is zero then the equality to zero is ok
|
328 |
+
assert sign(eq).func is sign or sign(eq) == 0
|
329 |
+
# but sometimes it's hard to do this so it's better not to load
|
330 |
+
# abs down with tests that will be very slow
|
331 |
+
q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
|
332 |
+
p = expand(q**3)**Rational(1, 3)
|
333 |
+
d = p - q
|
334 |
+
assert sign(d).func is sign or sign(d) == 0
|
335 |
+
|
336 |
+
|
337 |
+
def test_as_real_imag():
|
338 |
+
n = pi**1000
|
339 |
+
# the special code for working out the real
|
340 |
+
# and complex parts of a power with Integer exponent
|
341 |
+
# should not run if there is no imaginary part, hence
|
342 |
+
# this should not hang
|
343 |
+
assert n.as_real_imag() == (n, 0)
|
344 |
+
|
345 |
+
# issue 6261
|
346 |
+
x = Symbol('x')
|
347 |
+
assert sqrt(x).as_real_imag() == \
|
348 |
+
((re(x)**2 + im(x)**2)**Rational(1, 4)*cos(atan2(im(x), re(x))/2),
|
349 |
+
(re(x)**2 + im(x)**2)**Rational(1, 4)*sin(atan2(im(x), re(x))/2))
|
350 |
+
|
351 |
+
# issue 3853
|
352 |
+
a, b = symbols('a,b', real=True)
|
353 |
+
assert ((1 + sqrt(a + b*I))/2).as_real_imag() == \
|
354 |
+
(
|
355 |
+
(a**2 + b**2)**Rational(
|
356 |
+
1, 4)*cos(atan2(b, a)/2)/2 + S.Half,
|
357 |
+
(a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2)
|
358 |
+
|
359 |
+
assert sqrt(a**2).as_real_imag() == (sqrt(a**2), 0)
|
360 |
+
i = symbols('i', imaginary=True)
|
361 |
+
assert sqrt(i**2).as_real_imag() == (0, abs(i))
|
362 |
+
|
363 |
+
assert ((1 + I)/(1 - I)).as_real_imag() == (0, 1)
|
364 |
+
assert ((1 + I)**3/(1 - I)).as_real_imag() == (-2, 0)
|
365 |
+
|
366 |
+
|
367 |
+
@XFAIL
|
368 |
+
def test_sign_issue_3068():
|
369 |
+
n = pi**1000
|
370 |
+
i = int(n)
|
371 |
+
x = Symbol('x')
|
372 |
+
assert (n - i).round() == 1 # doesn't hang
|
373 |
+
assert sign(n - i) == 1
|
374 |
+
# perhaps it's not possible to get the sign right when
|
375 |
+
# only 1 digit is being requested for this situation;
|
376 |
+
# 2 digits works
|
377 |
+
assert (n - x).n(1, subs={x: i}) > 0
|
378 |
+
assert (n - x).n(2, subs={x: i}) > 0
|
379 |
+
|
380 |
+
|
381 |
+
def test_Abs():
|
382 |
+
raises(TypeError, lambda: Abs(Interval(2, 3))) # issue 8717
|
383 |
+
|
384 |
+
x, y = symbols('x,y')
|
385 |
+
assert sign(sign(x)) == sign(x)
|
386 |
+
assert sign(x*y).func is sign
|
387 |
+
assert Abs(0) == 0
|
388 |
+
assert Abs(1) == 1
|
389 |
+
assert Abs(-1) == 1
|
390 |
+
assert Abs(I) == 1
|
391 |
+
assert Abs(-I) == 1
|
392 |
+
assert Abs(nan) is nan
|
393 |
+
assert Abs(zoo) is oo
|
394 |
+
assert Abs(I * pi) == pi
|
395 |
+
assert Abs(-I * pi) == pi
|
396 |
+
assert Abs(I * x) == Abs(x)
|
397 |
+
assert Abs(-I * x) == Abs(x)
|
398 |
+
assert Abs(-2*x) == 2*Abs(x)
|
399 |
+
assert Abs(-2.0*x) == 2.0*Abs(x)
|
400 |
+
assert Abs(2*pi*x*y) == 2*pi*Abs(x*y)
|
401 |
+
assert Abs(conjugate(x)) == Abs(x)
|
402 |
+
assert conjugate(Abs(x)) == Abs(x)
|
403 |
+
assert Abs(x).expand(complex=True) == sqrt(re(x)**2 + im(x)**2)
|
404 |
+
|
405 |
+
a = Symbol('a', positive=True)
|
406 |
+
assert Abs(2*pi*x*a) == 2*pi*a*Abs(x)
|
407 |
+
assert Abs(2*pi*I*x*a) == 2*pi*a*Abs(x)
|
408 |
+
|
409 |
+
x = Symbol('x', real=True)
|
410 |
+
n = Symbol('n', integer=True)
|
411 |
+
assert Abs((-1)**n) == 1
|
412 |
+
assert x**(2*n) == Abs(x)**(2*n)
|
413 |
+
assert Abs(x).diff(x) == sign(x)
|
414 |
+
assert abs(x) == Abs(x) # Python built-in
|
415 |
+
assert Abs(x)**3 == x**2*Abs(x)
|
416 |
+
assert Abs(x)**4 == x**4
|
417 |
+
assert (
|
418 |
+
Abs(x)**(3*n)).args == (Abs(x), 3*n) # leave symbolic odd unchanged
|
419 |
+
assert (1/Abs(x)).args == (Abs(x), -1)
|
420 |
+
assert 1/Abs(x)**3 == 1/(x**2*Abs(x))
|
421 |
+
assert Abs(x)**-3 == Abs(x)/(x**4)
|
422 |
+
assert Abs(x**3) == x**2*Abs(x)
|
423 |
+
assert Abs(I**I) == exp(-pi/2)
|
424 |
+
assert Abs((4 + 5*I)**(6 + 7*I)) == 68921*exp(-7*atan(Rational(5, 4)))
|
425 |
+
y = Symbol('y', real=True)
|
426 |
+
assert Abs(I**y) == 1
|
427 |
+
y = Symbol('y')
|
428 |
+
assert Abs(I**y) == exp(-pi*im(y)/2)
|
429 |
+
|
430 |
+
x = Symbol('x', imaginary=True)
|
431 |
+
assert Abs(x).diff(x) == -sign(x)
|
432 |
+
|
433 |
+
eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
|
434 |
+
# if there is a fast way to know when you can and when you cannot prove an
|
435 |
+
# expression like this is zero then the equality to zero is ok
|
436 |
+
assert abs(eq).func is Abs or abs(eq) == 0
|
437 |
+
# but sometimes it's hard to do this so it's better not to load
|
438 |
+
# abs down with tests that will be very slow
|
439 |
+
q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
|
440 |
+
p = expand(q**3)**Rational(1, 3)
|
441 |
+
d = p - q
|
442 |
+
assert abs(d).func is Abs or abs(d) == 0
|
443 |
+
|
444 |
+
assert Abs(4*exp(pi*I/4)) == 4
|
445 |
+
assert Abs(3**(2 + I)) == 9
|
446 |
+
assert Abs((-3)**(1 - I)) == 3*exp(pi)
|
447 |
+
|
448 |
+
assert Abs(oo) is oo
|
449 |
+
assert Abs(-oo) is oo
|
450 |
+
assert Abs(oo + I) is oo
|
451 |
+
assert Abs(oo + I*oo) is oo
|
452 |
+
|
453 |
+
a = Symbol('a', algebraic=True)
|
454 |
+
t = Symbol('t', transcendental=True)
|
455 |
+
x = Symbol('x')
|
456 |
+
assert re(a).is_algebraic
|
457 |
+
assert re(x).is_algebraic is None
|
458 |
+
assert re(t).is_algebraic is False
|
459 |
+
assert Abs(x).fdiff() == sign(x)
|
460 |
+
raises(ArgumentIndexError, lambda: Abs(x).fdiff(2))
|
461 |
+
|
462 |
+
# doesn't have recursion error
|
463 |
+
arg = sqrt(acos(1 - I)*acos(1 + I))
|
464 |
+
assert abs(arg) == arg
|
465 |
+
|
466 |
+
# special handling to put Abs in denom
|
467 |
+
assert abs(1/x) == 1/Abs(x)
|
468 |
+
e = abs(2/x**2)
|
469 |
+
assert e.is_Mul and e == 2/Abs(x**2)
|
470 |
+
assert unchanged(Abs, y/x)
|
471 |
+
assert unchanged(Abs, x/(x + 1))
|
472 |
+
assert unchanged(Abs, x*y)
|
473 |
+
p = Symbol('p', positive=True)
|
474 |
+
assert abs(x/p) == abs(x)/p
|
475 |
+
|
476 |
+
# coverage
|
477 |
+
assert unchanged(Abs, Symbol('x', real=True)**y)
|
478 |
+
# issue 19627
|
479 |
+
f = Function('f', positive=True)
|
480 |
+
assert sqrt(f(x)**2) == f(x)
|
481 |
+
# issue 21625
|
482 |
+
assert unchanged(Abs, S("im(acos(-i + acosh(-g + i)))"))
|
483 |
+
|
484 |
+
|
485 |
+
def test_Abs_rewrite():
|
486 |
+
x = Symbol('x', real=True)
|
487 |
+
a = Abs(x).rewrite(Heaviside).expand()
|
488 |
+
assert a == x*Heaviside(x) - x*Heaviside(-x)
|
489 |
+
for i in [-2, -1, 0, 1, 2]:
|
490 |
+
assert a.subs(x, i) == abs(i)
|
491 |
+
y = Symbol('y')
|
492 |
+
assert Abs(y).rewrite(Heaviside) == Abs(y)
|
493 |
+
|
494 |
+
x, y = Symbol('x', real=True), Symbol('y')
|
495 |
+
assert Abs(x).rewrite(Piecewise) == Piecewise((x, x >= 0), (-x, True))
|
496 |
+
assert Abs(y).rewrite(Piecewise) == Abs(y)
|
497 |
+
assert Abs(y).rewrite(sign) == y/sign(y)
|
498 |
+
|
499 |
+
i = Symbol('i', imaginary=True)
|
500 |
+
assert abs(i).rewrite(Piecewise) == Piecewise((I*i, I*i >= 0), (-I*i, True))
|
501 |
+
|
502 |
+
|
503 |
+
assert Abs(y).rewrite(conjugate) == sqrt(y*conjugate(y))
|
504 |
+
assert Abs(i).rewrite(conjugate) == sqrt(-i**2) # == -I*i
|
505 |
+
|
506 |
+
y = Symbol('y', extended_real=True)
|
507 |
+
assert (Abs(exp(-I*x)-exp(-I*y))**2).rewrite(conjugate) == \
|
508 |
+
-exp(I*x)*exp(-I*y) + 2 - exp(-I*x)*exp(I*y)
|
509 |
+
|
510 |
+
|
511 |
+
def test_Abs_real():
|
512 |
+
# test some properties of abs that only apply
|
513 |
+
# to real numbers
|
514 |
+
x = Symbol('x', complex=True)
|
515 |
+
assert sqrt(x**2) != Abs(x)
|
516 |
+
assert Abs(x**2) != x**2
|
517 |
+
|
518 |
+
x = Symbol('x', real=True)
|
519 |
+
assert sqrt(x**2) == Abs(x)
|
520 |
+
assert Abs(x**2) == x**2
|
521 |
+
|
522 |
+
# if the symbol is zero, the following will still apply
|
523 |
+
nn = Symbol('nn', nonnegative=True, real=True)
|
524 |
+
np = Symbol('np', nonpositive=True, real=True)
|
525 |
+
assert Abs(nn) == nn
|
526 |
+
assert Abs(np) == -np
|
527 |
+
|
528 |
+
|
529 |
+
def test_Abs_properties():
|
530 |
+
x = Symbol('x')
|
531 |
+
assert Abs(x).is_real is None
|
532 |
+
assert Abs(x).is_extended_real is True
|
533 |
+
assert Abs(x).is_rational is None
|
534 |
+
assert Abs(x).is_positive is None
|
535 |
+
assert Abs(x).is_nonnegative is None
|
536 |
+
assert Abs(x).is_extended_positive is None
|
537 |
+
assert Abs(x).is_extended_nonnegative is True
|
538 |
+
|
539 |
+
f = Symbol('x', finite=True)
|
540 |
+
assert Abs(f).is_real is True
|
541 |
+
assert Abs(f).is_extended_real is True
|
542 |
+
assert Abs(f).is_rational is None
|
543 |
+
assert Abs(f).is_positive is None
|
544 |
+
assert Abs(f).is_nonnegative is True
|
545 |
+
assert Abs(f).is_extended_positive is None
|
546 |
+
assert Abs(f).is_extended_nonnegative is True
|
547 |
+
|
548 |
+
z = Symbol('z', complex=True, zero=False)
|
549 |
+
assert Abs(z).is_real is True # since complex implies finite
|
550 |
+
assert Abs(z).is_extended_real is True
|
551 |
+
assert Abs(z).is_rational is None
|
552 |
+
assert Abs(z).is_positive is True
|
553 |
+
assert Abs(z).is_extended_positive is True
|
554 |
+
assert Abs(z).is_zero is False
|
555 |
+
|
556 |
+
p = Symbol('p', positive=True)
|
557 |
+
assert Abs(p).is_real is True
|
558 |
+
assert Abs(p).is_extended_real is True
|
559 |
+
assert Abs(p).is_rational is None
|
560 |
+
assert Abs(p).is_positive is True
|
561 |
+
assert Abs(p).is_zero is False
|
562 |
+
|
563 |
+
q = Symbol('q', rational=True)
|
564 |
+
assert Abs(q).is_real is True
|
565 |
+
assert Abs(q).is_rational is True
|
566 |
+
assert Abs(q).is_integer is None
|
567 |
+
assert Abs(q).is_positive is None
|
568 |
+
assert Abs(q).is_nonnegative is True
|
569 |
+
|
570 |
+
i = Symbol('i', integer=True)
|
571 |
+
assert Abs(i).is_real is True
|
572 |
+
assert Abs(i).is_integer is True
|
573 |
+
assert Abs(i).is_positive is None
|
574 |
+
assert Abs(i).is_nonnegative is True
|
575 |
+
|
576 |
+
e = Symbol('n', even=True)
|
577 |
+
ne = Symbol('ne', real=True, even=False)
|
578 |
+
assert Abs(e).is_even is True
|
579 |
+
assert Abs(ne).is_even is False
|
580 |
+
assert Abs(i).is_even is None
|
581 |
+
|
582 |
+
o = Symbol('n', odd=True)
|
583 |
+
no = Symbol('no', real=True, odd=False)
|
584 |
+
assert Abs(o).is_odd is True
|
585 |
+
assert Abs(no).is_odd is False
|
586 |
+
assert Abs(i).is_odd is None
|
587 |
+
|
588 |
+
|
589 |
+
def test_abs():
|
590 |
+
# this tests that abs calls Abs; don't rename to
|
591 |
+
# test_Abs since that test is already above
|
592 |
+
a = Symbol('a', positive=True)
|
593 |
+
assert abs(I*(1 + a)**2) == (1 + a)**2
|
594 |
+
|
595 |
+
|
596 |
+
def test_arg():
|
597 |
+
assert arg(0) is nan
|
598 |
+
assert arg(1) == 0
|
599 |
+
assert arg(-1) == pi
|
600 |
+
assert arg(I) == pi/2
|
601 |
+
assert arg(-I) == -pi/2
|
602 |
+
assert arg(1 + I) == pi/4
|
603 |
+
assert arg(-1 + I) == pi*Rational(3, 4)
|
604 |
+
assert arg(1 - I) == -pi/4
|
605 |
+
assert arg(exp_polar(4*pi*I)) == 4*pi
|
606 |
+
assert arg(exp_polar(-7*pi*I)) == -7*pi
|
607 |
+
assert arg(exp_polar(5 - 3*pi*I/4)) == pi*Rational(-3, 4)
|
608 |
+
f = Function('f')
|
609 |
+
assert not arg(f(0) + I*f(1)).atoms(re)
|
610 |
+
|
611 |
+
# check nesting
|
612 |
+
x = Symbol('x')
|
613 |
+
assert arg(arg(arg(x))) is not S.NaN
|
614 |
+
assert arg(arg(arg(arg(x)))) is S.NaN
|
615 |
+
r = Symbol('r', extended_real=True)
|
616 |
+
assert arg(arg(r)) is not S.NaN
|
617 |
+
assert arg(arg(arg(r))) is S.NaN
|
618 |
+
|
619 |
+
p = Function('p', extended_positive=True)
|
620 |
+
assert arg(p(x)) == 0
|
621 |
+
assert arg((3 + I)*p(x)) == arg(3 + I)
|
622 |
+
|
623 |
+
p = Symbol('p', positive=True)
|
624 |
+
assert arg(p) == 0
|
625 |
+
assert arg(p*I) == pi/2
|
626 |
+
|
627 |
+
n = Symbol('n', negative=True)
|
628 |
+
assert arg(n) == pi
|
629 |
+
assert arg(n*I) == -pi/2
|
630 |
+
|
631 |
+
x = Symbol('x')
|
632 |
+
assert conjugate(arg(x)) == arg(x)
|
633 |
+
|
634 |
+
e = p + I*p**2
|
635 |
+
assert arg(e) == arg(1 + p*I)
|
636 |
+
# make sure sign doesn't swap
|
637 |
+
e = -2*p + 4*I*p**2
|
638 |
+
assert arg(e) == arg(-1 + 2*p*I)
|
639 |
+
# make sure sign isn't lost
|
640 |
+
x = symbols('x', real=True) # could be zero
|
641 |
+
e = x + I*x
|
642 |
+
assert arg(e) == arg(x*(1 + I))
|
643 |
+
assert arg(e/p) == arg(x*(1 + I))
|
644 |
+
e = p*cos(p) + I*log(p)*exp(p)
|
645 |
+
assert arg(e).args[0] == e
|
646 |
+
# keep it simple -- let the user do more advanced cancellation
|
647 |
+
e = (p + 1) + I*(p**2 - 1)
|
648 |
+
assert arg(e).args[0] == e
|
649 |
+
|
650 |
+
f = Function('f')
|
651 |
+
e = 2*x*(f(0) - 1) - 2*x*f(0)
|
652 |
+
assert arg(e) == arg(-2*x)
|
653 |
+
assert arg(f(0)).func == arg and arg(f(0)).args == (f(0),)
|
654 |
+
|
655 |
+
|
656 |
+
def test_arg_rewrite():
|
657 |
+
assert arg(1 + I) == atan2(1, 1)
|
658 |
+
|
659 |
+
x = Symbol('x', real=True)
|
660 |
+
y = Symbol('y', real=True)
|
661 |
+
assert arg(x + I*y).rewrite(atan2) == atan2(y, x)
|
662 |
+
|
663 |
+
|
664 |
+
def test_adjoint():
|
665 |
+
a = Symbol('a', antihermitian=True)
|
666 |
+
b = Symbol('b', hermitian=True)
|
667 |
+
assert adjoint(a) == -a
|
668 |
+
assert adjoint(I*a) == I*a
|
669 |
+
assert adjoint(b) == b
|
670 |
+
assert adjoint(I*b) == -I*b
|
671 |
+
assert adjoint(a*b) == -b*a
|
672 |
+
assert adjoint(I*a*b) == I*b*a
|
673 |
+
|
674 |
+
x, y = symbols('x y')
|
675 |
+
assert adjoint(adjoint(x)) == x
|
676 |
+
assert adjoint(x + y) == adjoint(x) + adjoint(y)
|
677 |
+
assert adjoint(x - y) == adjoint(x) - adjoint(y)
|
678 |
+
assert adjoint(x * y) == adjoint(x) * adjoint(y)
|
679 |
+
assert adjoint(x / y) == adjoint(x) / adjoint(y)
|
680 |
+
assert adjoint(-x) == -adjoint(x)
|
681 |
+
|
682 |
+
x, y = symbols('x y', commutative=False)
|
683 |
+
assert adjoint(adjoint(x)) == x
|
684 |
+
assert adjoint(x + y) == adjoint(x) + adjoint(y)
|
685 |
+
assert adjoint(x - y) == adjoint(x) - adjoint(y)
|
686 |
+
assert adjoint(x * y) == adjoint(y) * adjoint(x)
|
687 |
+
assert adjoint(x / y) == 1 / adjoint(y) * adjoint(x)
|
688 |
+
assert adjoint(-x) == -adjoint(x)
|
689 |
+
|
690 |
+
|
691 |
+
def test_conjugate():
|
692 |
+
a = Symbol('a', real=True)
|
693 |
+
b = Symbol('b', imaginary=True)
|
694 |
+
assert conjugate(a) == a
|
695 |
+
assert conjugate(I*a) == -I*a
|
696 |
+
assert conjugate(b) == -b
|
697 |
+
assert conjugate(I*b) == I*b
|
698 |
+
assert conjugate(a*b) == -a*b
|
699 |
+
assert conjugate(I*a*b) == I*a*b
|
700 |
+
|
701 |
+
x, y = symbols('x y')
|
702 |
+
assert conjugate(conjugate(x)) == x
|
703 |
+
assert conjugate(x).inverse() == conjugate
|
704 |
+
assert conjugate(x + y) == conjugate(x) + conjugate(y)
|
705 |
+
assert conjugate(x - y) == conjugate(x) - conjugate(y)
|
706 |
+
assert conjugate(x * y) == conjugate(x) * conjugate(y)
|
707 |
+
assert conjugate(x / y) == conjugate(x) / conjugate(y)
|
708 |
+
assert conjugate(-x) == -conjugate(x)
|
709 |
+
|
710 |
+
a = Symbol('a', algebraic=True)
|
711 |
+
t = Symbol('t', transcendental=True)
|
712 |
+
assert re(a).is_algebraic
|
713 |
+
assert re(x).is_algebraic is None
|
714 |
+
assert re(t).is_algebraic is False
|
715 |
+
|
716 |
+
|
717 |
+
def test_conjugate_transpose():
|
718 |
+
x = Symbol('x')
|
719 |
+
assert conjugate(transpose(x)) == adjoint(x)
|
720 |
+
assert transpose(conjugate(x)) == adjoint(x)
|
721 |
+
assert adjoint(transpose(x)) == conjugate(x)
|
722 |
+
assert transpose(adjoint(x)) == conjugate(x)
|
723 |
+
assert adjoint(conjugate(x)) == transpose(x)
|
724 |
+
assert conjugate(adjoint(x)) == transpose(x)
|
725 |
+
|
726 |
+
class Symmetric(Expr):
|
727 |
+
def _eval_adjoint(self):
|
728 |
+
return None
|
729 |
+
|
730 |
+
def _eval_conjugate(self):
|
731 |
+
return None
|
732 |
+
|
733 |
+
def _eval_transpose(self):
|
734 |
+
return self
|
735 |
+
x = Symmetric()
|
736 |
+
assert conjugate(x) == adjoint(x)
|
737 |
+
assert transpose(x) == x
|
738 |
+
|
739 |
+
|
740 |
+
def test_transpose():
|
741 |
+
a = Symbol('a', complex=True)
|
742 |
+
assert transpose(a) == a
|
743 |
+
assert transpose(I*a) == I*a
|
744 |
+
|
745 |
+
x, y = symbols('x y')
|
746 |
+
assert transpose(transpose(x)) == x
|
747 |
+
assert transpose(x + y) == transpose(x) + transpose(y)
|
748 |
+
assert transpose(x - y) == transpose(x) - transpose(y)
|
749 |
+
assert transpose(x * y) == transpose(x) * transpose(y)
|
750 |
+
assert transpose(x / y) == transpose(x) / transpose(y)
|
751 |
+
assert transpose(-x) == -transpose(x)
|
752 |
+
|
753 |
+
x, y = symbols('x y', commutative=False)
|
754 |
+
assert transpose(transpose(x)) == x
|
755 |
+
assert transpose(x + y) == transpose(x) + transpose(y)
|
756 |
+
assert transpose(x - y) == transpose(x) - transpose(y)
|
757 |
+
assert transpose(x * y) == transpose(y) * transpose(x)
|
758 |
+
assert transpose(x / y) == 1 / transpose(y) * transpose(x)
|
759 |
+
assert transpose(-x) == -transpose(x)
|
760 |
+
|
761 |
+
|
762 |
+
@_both_exp_pow
|
763 |
+
def test_polarify():
|
764 |
+
from sympy.functions.elementary.complexes import (polar_lift, polarify)
|
765 |
+
x = Symbol('x')
|
766 |
+
z = Symbol('z', polar=True)
|
767 |
+
f = Function('f')
|
768 |
+
ES = {}
|
769 |
+
|
770 |
+
assert polarify(-1) == (polar_lift(-1), ES)
|
771 |
+
assert polarify(1 + I) == (polar_lift(1 + I), ES)
|
772 |
+
|
773 |
+
assert polarify(exp(x), subs=False) == exp(x)
|
774 |
+
assert polarify(1 + x, subs=False) == 1 + x
|
775 |
+
assert polarify(f(I) + x, subs=False) == f(polar_lift(I)) + x
|
776 |
+
|
777 |
+
assert polarify(x, lift=True) == polar_lift(x)
|
778 |
+
assert polarify(z, lift=True) == z
|
779 |
+
assert polarify(f(x), lift=True) == f(polar_lift(x))
|
780 |
+
assert polarify(1 + x, lift=True) == polar_lift(1 + x)
|
781 |
+
assert polarify(1 + f(x), lift=True) == polar_lift(1 + f(polar_lift(x)))
|
782 |
+
|
783 |
+
newex, subs = polarify(f(x) + z)
|
784 |
+
assert newex.subs(subs) == f(x) + z
|
785 |
+
|
786 |
+
mu = Symbol("mu")
|
787 |
+
sigma = Symbol("sigma", positive=True)
|
788 |
+
|
789 |
+
# Make sure polarify(lift=True) doesn't try to lift the integration
|
790 |
+
# variable
|
791 |
+
assert polarify(
|
792 |
+
Integral(sqrt(2)*x*exp(-(-mu + x)**2/(2*sigma**2))/(2*sqrt(pi)*sigma),
|
793 |
+
(x, -oo, oo)), lift=True) == Integral(sqrt(2)*(sigma*exp_polar(0))**exp_polar(I*pi)*
|
794 |
+
exp((sigma*exp_polar(0))**(2*exp_polar(I*pi))*exp_polar(I*pi)*polar_lift(-mu + x)**
|
795 |
+
(2*exp_polar(0))/2)*exp_polar(0)*polar_lift(x)/(2*sqrt(pi)), (x, -oo, oo))
|
796 |
+
|
797 |
+
|
798 |
+
def test_unpolarify():
|
799 |
+
from sympy.functions.elementary.complexes import (polar_lift, principal_branch, unpolarify)
|
800 |
+
from sympy.core.relational import Ne
|
801 |
+
from sympy.functions.elementary.hyperbolic import tanh
|
802 |
+
from sympy.functions.special.error_functions import erf
|
803 |
+
from sympy.functions.special.gamma_functions import (gamma, uppergamma)
|
804 |
+
from sympy.abc import x
|
805 |
+
p = exp_polar(7*I) + 1
|
806 |
+
u = exp(7*I) + 1
|
807 |
+
|
808 |
+
assert unpolarify(1) == 1
|
809 |
+
assert unpolarify(p) == u
|
810 |
+
assert unpolarify(p**2) == u**2
|
811 |
+
assert unpolarify(p**x) == p**x
|
812 |
+
assert unpolarify(p*x) == u*x
|
813 |
+
assert unpolarify(p + x) == u + x
|
814 |
+
assert unpolarify(sqrt(sin(p))) == sqrt(sin(u))
|
815 |
+
|
816 |
+
# Test reduction to principal branch 2*pi.
|
817 |
+
t = principal_branch(x, 2*pi)
|
818 |
+
assert unpolarify(t) == x
|
819 |
+
assert unpolarify(sqrt(t)) == sqrt(t)
|
820 |
+
|
821 |
+
# Test exponents_only.
|
822 |
+
assert unpolarify(p**p, exponents_only=True) == p**u
|
823 |
+
assert unpolarify(uppergamma(x, p**p)) == uppergamma(x, p**u)
|
824 |
+
|
825 |
+
# Test functions.
|
826 |
+
assert unpolarify(sin(p)) == sin(u)
|
827 |
+
assert unpolarify(tanh(p)) == tanh(u)
|
828 |
+
assert unpolarify(gamma(p)) == gamma(u)
|
829 |
+
assert unpolarify(erf(p)) == erf(u)
|
830 |
+
assert unpolarify(uppergamma(x, p)) == uppergamma(x, p)
|
831 |
+
|
832 |
+
assert unpolarify(uppergamma(sin(p), sin(p + exp_polar(0)))) == \
|
833 |
+
uppergamma(sin(u), sin(u + 1))
|
834 |
+
assert unpolarify(uppergamma(polar_lift(0), 2*exp_polar(0))) == \
|
835 |
+
uppergamma(0, 2)
|
836 |
+
|
837 |
+
assert unpolarify(Eq(p, 0)) == Eq(u, 0)
|
838 |
+
assert unpolarify(Ne(p, 0)) == Ne(u, 0)
|
839 |
+
assert unpolarify(polar_lift(x) > 0) == (x > 0)
|
840 |
+
|
841 |
+
# Test bools
|
842 |
+
assert unpolarify(True) is True
|
843 |
+
|
844 |
+
|
845 |
+
def test_issue_4035():
|
846 |
+
x = Symbol('x')
|
847 |
+
assert Abs(x).expand(trig=True) == Abs(x)
|
848 |
+
assert sign(x).expand(trig=True) == sign(x)
|
849 |
+
assert arg(x).expand(trig=True) == arg(x)
|
850 |
+
|
851 |
+
|
852 |
+
def test_issue_3206():
|
853 |
+
x = Symbol('x')
|
854 |
+
assert Abs(Abs(x)) == Abs(x)
|
855 |
+
|
856 |
+
|
857 |
+
def test_issue_4754_derivative_conjugate():
|
858 |
+
x = Symbol('x', real=True)
|
859 |
+
y = Symbol('y', imaginary=True)
|
860 |
+
f = Function('f')
|
861 |
+
assert (f(x).conjugate()).diff(x) == (f(x).diff(x)).conjugate()
|
862 |
+
assert (f(y).conjugate()).diff(y) == -(f(y).diff(y)).conjugate()
|
863 |
+
|
864 |
+
|
865 |
+
def test_derivatives_issue_4757():
|
866 |
+
x = Symbol('x', real=True)
|
867 |
+
y = Symbol('y', imaginary=True)
|
868 |
+
f = Function('f')
|
869 |
+
assert re(f(x)).diff(x) == re(f(x).diff(x))
|
870 |
+
assert im(f(x)).diff(x) == im(f(x).diff(x))
|
871 |
+
assert re(f(y)).diff(y) == -I*im(f(y).diff(y))
|
872 |
+
assert im(f(y)).diff(y) == -I*re(f(y).diff(y))
|
873 |
+
assert Abs(f(x)).diff(x).subs(f(x), 1 + I*x).doit() == x/sqrt(1 + x**2)
|
874 |
+
assert arg(f(x)).diff(x).subs(f(x), 1 + I*x**2).doit() == 2*x/(1 + x**4)
|
875 |
+
assert Abs(f(y)).diff(y).subs(f(y), 1 + y).doit() == -y/sqrt(1 - y**2)
|
876 |
+
assert arg(f(y)).diff(y).subs(f(y), I + y**2).doit() == 2*y/(1 + y**4)
|
877 |
+
|
878 |
+
|
879 |
+
def test_issue_11413():
|
880 |
+
from sympy.simplify.simplify import simplify
|
881 |
+
v0 = Symbol('v0')
|
882 |
+
v1 = Symbol('v1')
|
883 |
+
v2 = Symbol('v2')
|
884 |
+
V = Matrix([[v0],[v1],[v2]])
|
885 |
+
U = V.normalized()
|
886 |
+
assert U == Matrix([
|
887 |
+
[v0/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
|
888 |
+
[v1/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
|
889 |
+
[v2/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)]])
|
890 |
+
U.norm = sqrt(v0**2/(v0**2 + v1**2 + v2**2) + v1**2/(v0**2 + v1**2 + v2**2) + v2**2/(v0**2 + v1**2 + v2**2))
|
891 |
+
assert simplify(U.norm) == 1
|
892 |
+
|
893 |
+
|
894 |
+
def test_periodic_argument():
|
895 |
+
from sympy.functions.elementary.complexes import (periodic_argument, polar_lift, principal_branch, unbranched_argument)
|
896 |
+
x = Symbol('x')
|
897 |
+
p = Symbol('p', positive=True)
|
898 |
+
|
899 |
+
assert unbranched_argument(2 + I) == periodic_argument(2 + I, oo)
|
900 |
+
assert unbranched_argument(1 + x) == periodic_argument(1 + x, oo)
|
901 |
+
assert N_equals(unbranched_argument((1 + I)**2), pi/2)
|
902 |
+
assert N_equals(unbranched_argument((1 - I)**2), -pi/2)
|
903 |
+
assert N_equals(periodic_argument((1 + I)**2, 3*pi), pi/2)
|
904 |
+
assert N_equals(periodic_argument((1 - I)**2, 3*pi), -pi/2)
|
905 |
+
|
906 |
+
assert unbranched_argument(principal_branch(x, pi)) == \
|
907 |
+
periodic_argument(x, pi)
|
908 |
+
|
909 |
+
assert unbranched_argument(polar_lift(2 + I)) == unbranched_argument(2 + I)
|
910 |
+
assert periodic_argument(polar_lift(2 + I), 2*pi) == \
|
911 |
+
periodic_argument(2 + I, 2*pi)
|
912 |
+
assert periodic_argument(polar_lift(2 + I), 3*pi) == \
|
913 |
+
periodic_argument(2 + I, 3*pi)
|
914 |
+
assert periodic_argument(polar_lift(2 + I), pi) == \
|
915 |
+
periodic_argument(polar_lift(2 + I), pi)
|
916 |
+
|
917 |
+
assert unbranched_argument(polar_lift(1 + I)) == pi/4
|
918 |
+
assert periodic_argument(2*p, p) == periodic_argument(p, p)
|
919 |
+
assert periodic_argument(pi*p, p) == periodic_argument(p, p)
|
920 |
+
|
921 |
+
assert Abs(polar_lift(1 + I)) == Abs(1 + I)
|
922 |
+
|
923 |
+
|
924 |
+
@XFAIL
|
925 |
+
def test_principal_branch_fail():
|
926 |
+
# TODO XXX why does abs(x)._eval_evalf() not fall back to global evalf?
|
927 |
+
from sympy.functions.elementary.complexes import principal_branch
|
928 |
+
assert N_equals(principal_branch((1 + I)**2, pi/2), 0)
|
929 |
+
|
930 |
+
|
931 |
+
def test_principal_branch():
|
932 |
+
from sympy.functions.elementary.complexes import (polar_lift, principal_branch)
|
933 |
+
p = Symbol('p', positive=True)
|
934 |
+
x = Symbol('x')
|
935 |
+
neg = Symbol('x', negative=True)
|
936 |
+
|
937 |
+
assert principal_branch(polar_lift(x), p) == principal_branch(x, p)
|
938 |
+
assert principal_branch(polar_lift(2 + I), p) == principal_branch(2 + I, p)
|
939 |
+
assert principal_branch(2*x, p) == 2*principal_branch(x, p)
|
940 |
+
assert principal_branch(1, pi) == exp_polar(0)
|
941 |
+
assert principal_branch(-1, 2*pi) == exp_polar(I*pi)
|
942 |
+
assert principal_branch(-1, pi) == exp_polar(0)
|
943 |
+
assert principal_branch(exp_polar(3*pi*I)*x, 2*pi) == \
|
944 |
+
principal_branch(exp_polar(I*pi)*x, 2*pi)
|
945 |
+
assert principal_branch(neg*exp_polar(pi*I), 2*pi) == neg*exp_polar(-I*pi)
|
946 |
+
# related to issue #14692
|
947 |
+
assert principal_branch(exp_polar(-I*pi/2)/polar_lift(neg), 2*pi) == \
|
948 |
+
exp_polar(-I*pi/2)/neg
|
949 |
+
|
950 |
+
assert N_equals(principal_branch((1 + I)**2, 2*pi), 2*I)
|
951 |
+
assert N_equals(principal_branch((1 + I)**2, 3*pi), 2*I)
|
952 |
+
assert N_equals(principal_branch((1 + I)**2, 1*pi), 2*I)
|
953 |
+
|
954 |
+
# test argument sanitization
|
955 |
+
assert principal_branch(x, I).func is principal_branch
|
956 |
+
assert principal_branch(x, -4).func is principal_branch
|
957 |
+
assert principal_branch(x, -oo).func is principal_branch
|
958 |
+
assert principal_branch(x, zoo).func is principal_branch
|
959 |
+
|
960 |
+
|
961 |
+
@XFAIL
|
962 |
+
def test_issue_6167_6151():
|
963 |
+
n = pi**1000
|
964 |
+
i = int(n)
|
965 |
+
assert sign(n - i) == 1
|
966 |
+
assert abs(n - i) == n - i
|
967 |
+
x = Symbol('x')
|
968 |
+
eps = pi**-1500
|
969 |
+
big = pi**1000
|
970 |
+
one = cos(x)**2 + sin(x)**2
|
971 |
+
e = big*one - big + eps
|
972 |
+
from sympy.simplify.simplify import simplify
|
973 |
+
assert sign(simplify(e)) == 1
|
974 |
+
for xi in (111, 11, 1, Rational(1, 10)):
|
975 |
+
assert sign(e.subs(x, xi)) == 1
|
976 |
+
|
977 |
+
|
978 |
+
def test_issue_14216():
|
979 |
+
from sympy.functions.elementary.complexes import unpolarify
|
980 |
+
A = MatrixSymbol("A", 2, 2)
|
981 |
+
assert unpolarify(A[0, 0]) == A[0, 0]
|
982 |
+
assert unpolarify(A[0, 0]*A[1, 0]) == A[0, 0]*A[1, 0]
|
983 |
+
|
984 |
+
|
985 |
+
def test_issue_14238():
|
986 |
+
# doesn't cause recursion error
|
987 |
+
r = Symbol('r', real=True)
|
988 |
+
assert Abs(r + Piecewise((0, r > 0), (1 - r, True)))
|
989 |
+
|
990 |
+
|
991 |
+
def test_issue_22189():
|
992 |
+
x = Symbol('x')
|
993 |
+
for a in (sqrt(7 - 2*x) - 2, 1 - x):
|
994 |
+
assert Abs(a) - Abs(-a) == 0, a
|
995 |
+
|
996 |
+
|
997 |
+
def test_zero_assumptions():
|
998 |
+
nr = Symbol('nonreal', real=False, finite=True)
|
999 |
+
ni = Symbol('nonimaginary', imaginary=False)
|
1000 |
+
# imaginary implies not zero
|
1001 |
+
nzni = Symbol('nonzerononimaginary', zero=False, imaginary=False)
|
1002 |
+
|
1003 |
+
assert re(nr).is_zero is None
|
1004 |
+
assert im(nr).is_zero is False
|
1005 |
+
|
1006 |
+
assert re(ni).is_zero is None
|
1007 |
+
assert im(ni).is_zero is None
|
1008 |
+
|
1009 |
+
assert re(nzni).is_zero is False
|
1010 |
+
assert im(nzni).is_zero is None
|
1011 |
+
|
1012 |
+
|
1013 |
+
@_both_exp_pow
|
1014 |
+
def test_issue_15893():
|
1015 |
+
f = Function('f', real=True)
|
1016 |
+
x = Symbol('x', real=True)
|
1017 |
+
eq = Derivative(Abs(f(x)), f(x))
|
1018 |
+
assert eq.doit() == sign(f(x))
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_exponential.py
ADDED
@@ -0,0 +1,806 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.assumptions.refine import refine
|
2 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
3 |
+
from sympy.concrete.products import Product
|
4 |
+
from sympy.concrete.summations import Sum
|
5 |
+
from sympy.core.function import expand_log
|
6 |
+
from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
|
7 |
+
from sympy.core.power import Pow
|
8 |
+
from sympy.core.singleton import S
|
9 |
+
from sympy.core.symbol import (Symbol, symbols)
|
10 |
+
from sympy.functions.elementary.complexes import (adjoint, conjugate, re, sign, transpose)
|
11 |
+
from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log)
|
12 |
+
from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh)
|
13 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
14 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
|
15 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
16 |
+
from sympy.polys.polytools import gcd
|
17 |
+
from sympy.series.order import O
|
18 |
+
from sympy.simplify.simplify import simplify
|
19 |
+
from sympy.core.parameters import global_parameters
|
20 |
+
from sympy.functions.elementary.exponential import match_real_imag
|
21 |
+
from sympy.abc import x, y, z
|
22 |
+
from sympy.core.expr import unchanged
|
23 |
+
from sympy.core.function import ArgumentIndexError
|
24 |
+
from sympy.testing.pytest import raises, XFAIL, _both_exp_pow
|
25 |
+
|
26 |
+
|
27 |
+
@_both_exp_pow
|
28 |
+
def test_exp_values():
|
29 |
+
if global_parameters.exp_is_pow:
|
30 |
+
assert type(exp(x)) is Pow
|
31 |
+
else:
|
32 |
+
assert type(exp(x)) is exp
|
33 |
+
|
34 |
+
k = Symbol('k', integer=True)
|
35 |
+
|
36 |
+
assert exp(nan) is nan
|
37 |
+
|
38 |
+
assert exp(oo) is oo
|
39 |
+
assert exp(-oo) == 0
|
40 |
+
|
41 |
+
assert exp(0) == 1
|
42 |
+
assert exp(1) == E
|
43 |
+
assert exp(-1 + x).as_base_exp() == (S.Exp1, x - 1)
|
44 |
+
assert exp(1 + x).as_base_exp() == (S.Exp1, x + 1)
|
45 |
+
|
46 |
+
assert exp(pi*I/2) == I
|
47 |
+
assert exp(pi*I) == -1
|
48 |
+
assert exp(pi*I*Rational(3, 2)) == -I
|
49 |
+
assert exp(2*pi*I) == 1
|
50 |
+
|
51 |
+
assert refine(exp(pi*I*2*k)) == 1
|
52 |
+
assert refine(exp(pi*I*2*(k + S.Half))) == -1
|
53 |
+
assert refine(exp(pi*I*2*(k + Rational(1, 4)))) == I
|
54 |
+
assert refine(exp(pi*I*2*(k + Rational(3, 4)))) == -I
|
55 |
+
|
56 |
+
assert exp(log(x)) == x
|
57 |
+
assert exp(2*log(x)) == x**2
|
58 |
+
assert exp(pi*log(x)) == x**pi
|
59 |
+
|
60 |
+
assert exp(17*log(x) + E*log(y)) == x**17 * y**E
|
61 |
+
|
62 |
+
assert exp(x*log(x)) != x**x
|
63 |
+
assert exp(sin(x)*log(x)) != x
|
64 |
+
|
65 |
+
assert exp(3*log(x) + oo*x) == exp(oo*x) * x**3
|
66 |
+
assert exp(4*log(x)*log(y) + 3*log(x)) == x**3 * exp(4*log(x)*log(y))
|
67 |
+
|
68 |
+
assert exp(-oo, evaluate=False).is_finite is True
|
69 |
+
assert exp(oo, evaluate=False).is_finite is False
|
70 |
+
|
71 |
+
|
72 |
+
@_both_exp_pow
|
73 |
+
def test_exp_period():
|
74 |
+
assert exp(I*pi*Rational(9, 4)) == exp(I*pi/4)
|
75 |
+
assert exp(I*pi*Rational(46, 18)) == exp(I*pi*Rational(5, 9))
|
76 |
+
assert exp(I*pi*Rational(25, 7)) == exp(I*pi*Rational(-3, 7))
|
77 |
+
assert exp(I*pi*Rational(-19, 3)) == exp(-I*pi/3)
|
78 |
+
assert exp(I*pi*Rational(37, 8)) - exp(I*pi*Rational(-11, 8)) == 0
|
79 |
+
assert exp(I*pi*Rational(-5, 3)) / exp(I*pi*Rational(11, 5)) * exp(I*pi*Rational(148, 15)) == 1
|
80 |
+
|
81 |
+
assert exp(2 - I*pi*Rational(17, 5)) == exp(2 + I*pi*Rational(3, 5))
|
82 |
+
assert exp(log(3) + I*pi*Rational(29, 9)) == 3 * exp(I*pi*Rational(-7, 9))
|
83 |
+
|
84 |
+
n = Symbol('n', integer=True)
|
85 |
+
e = Symbol('e', even=True)
|
86 |
+
assert exp(e*I*pi) == 1
|
87 |
+
assert exp((e + 1)*I*pi) == -1
|
88 |
+
assert exp((1 + 4*n)*I*pi/2) == I
|
89 |
+
assert exp((-1 + 4*n)*I*pi/2) == -I
|
90 |
+
|
91 |
+
|
92 |
+
@_both_exp_pow
|
93 |
+
def test_exp_log():
|
94 |
+
x = Symbol("x", real=True)
|
95 |
+
assert log(exp(x)) == x
|
96 |
+
assert exp(log(x)) == x
|
97 |
+
|
98 |
+
if not global_parameters.exp_is_pow:
|
99 |
+
assert log(x).inverse() == exp
|
100 |
+
assert exp(x).inverse() == log
|
101 |
+
|
102 |
+
y = Symbol("y", polar=True)
|
103 |
+
assert log(exp_polar(z)) == z
|
104 |
+
assert exp(log(y)) == y
|
105 |
+
|
106 |
+
|
107 |
+
@_both_exp_pow
|
108 |
+
def test_exp_expand():
|
109 |
+
e = exp(log(Rational(2))*(1 + x) - log(Rational(2))*x)
|
110 |
+
assert e.expand() == 2
|
111 |
+
assert exp(x + y) != exp(x)*exp(y)
|
112 |
+
assert exp(x + y).expand() == exp(x)*exp(y)
|
113 |
+
|
114 |
+
|
115 |
+
@_both_exp_pow
|
116 |
+
def test_exp__as_base_exp():
|
117 |
+
assert exp(x).as_base_exp() == (E, x)
|
118 |
+
assert exp(2*x).as_base_exp() == (E, 2*x)
|
119 |
+
assert exp(x*y).as_base_exp() == (E, x*y)
|
120 |
+
assert exp(-x).as_base_exp() == (E, -x)
|
121 |
+
|
122 |
+
# Pow( *expr.as_base_exp() ) == expr invariant should hold
|
123 |
+
assert E**x == exp(x)
|
124 |
+
assert E**(2*x) == exp(2*x)
|
125 |
+
assert E**(x*y) == exp(x*y)
|
126 |
+
|
127 |
+
assert exp(x).base is S.Exp1
|
128 |
+
assert exp(x).exp == x
|
129 |
+
|
130 |
+
|
131 |
+
@_both_exp_pow
|
132 |
+
def test_exp_infinity():
|
133 |
+
assert exp(I*y) != nan
|
134 |
+
assert refine(exp(I*oo)) is nan
|
135 |
+
assert refine(exp(-I*oo)) is nan
|
136 |
+
assert exp(y*I*oo) != nan
|
137 |
+
assert exp(zoo) is nan
|
138 |
+
x = Symbol('x', extended_real=True, finite=False)
|
139 |
+
assert exp(x).is_complex is None
|
140 |
+
|
141 |
+
|
142 |
+
@_both_exp_pow
|
143 |
+
def test_exp_subs():
|
144 |
+
x = Symbol('x')
|
145 |
+
e = (exp(3*log(x), evaluate=False)) # evaluates to x**3
|
146 |
+
assert e.subs(x**3, y**3) == e
|
147 |
+
assert e.subs(x**2, 5) == e
|
148 |
+
assert (x**3).subs(x**2, y) != y**Rational(3, 2)
|
149 |
+
assert exp(exp(x) + exp(x**2)).subs(exp(exp(x)), y) == y * exp(exp(x**2))
|
150 |
+
assert exp(x).subs(E, y) == y**x
|
151 |
+
x = symbols('x', real=True)
|
152 |
+
assert exp(5*x).subs(exp(7*x), y) == y**Rational(5, 7)
|
153 |
+
assert exp(2*x + 7).subs(exp(3*x), y) == y**Rational(2, 3) * exp(7)
|
154 |
+
x = symbols('x', positive=True)
|
155 |
+
assert exp(3*log(x)).subs(x**2, y) == y**Rational(3, 2)
|
156 |
+
# differentiate between E and exp
|
157 |
+
assert exp(exp(x + E)).subs(exp, 3) == 3**(3**(x + E))
|
158 |
+
assert exp(exp(x + E)).subs(exp, sin) == sin(sin(x + E))
|
159 |
+
assert exp(exp(x + E)).subs(E, 3) == 3**(3**(x + 3))
|
160 |
+
assert exp(3).subs(E, sin) == sin(3)
|
161 |
+
|
162 |
+
|
163 |
+
def test_exp_adjoint():
|
164 |
+
assert adjoint(exp(x)) == exp(adjoint(x))
|
165 |
+
|
166 |
+
|
167 |
+
def test_exp_conjugate():
|
168 |
+
assert conjugate(exp(x)) == exp(conjugate(x))
|
169 |
+
|
170 |
+
|
171 |
+
@_both_exp_pow
|
172 |
+
def test_exp_transpose():
|
173 |
+
assert transpose(exp(x)) == exp(transpose(x))
|
174 |
+
|
175 |
+
|
176 |
+
@_both_exp_pow
|
177 |
+
def test_exp_rewrite():
|
178 |
+
assert exp(x).rewrite(sin) == sinh(x) + cosh(x)
|
179 |
+
assert exp(x*I).rewrite(cos) == cos(x) + I*sin(x)
|
180 |
+
assert exp(1).rewrite(cos) == sinh(1) + cosh(1)
|
181 |
+
assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
|
182 |
+
assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
|
183 |
+
assert exp(x).rewrite(tanh) == (1 + tanh(x/2))/(1 - tanh(x/2))
|
184 |
+
assert exp(pi*I/4).rewrite(sqrt) == sqrt(2)/2 + sqrt(2)*I/2
|
185 |
+
assert exp(pi*I/3).rewrite(sqrt) == S.Half + sqrt(3)*I/2
|
186 |
+
if not global_parameters.exp_is_pow:
|
187 |
+
assert exp(x*log(y)).rewrite(Pow) == y**x
|
188 |
+
assert exp(log(x)*log(y)).rewrite(Pow) in [x**log(y), y**log(x)]
|
189 |
+
assert exp(log(log(x))*y).rewrite(Pow) == log(x)**y
|
190 |
+
|
191 |
+
n = Symbol('n', integer=True)
|
192 |
+
|
193 |
+
assert Sum((exp(pi*I/2)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == Rational(4, 5) + I*2/5
|
194 |
+
assert Sum((exp(pi*I/4)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == 1/(1 - sqrt(2)*(1 + I)/4)
|
195 |
+
assert (Sum((exp(pi*I/3)/2)**n, (n, 0, oo)).rewrite(sqrt).doit().cancel()
|
196 |
+
== 4*I/(sqrt(3) + 3*I))
|
197 |
+
|
198 |
+
|
199 |
+
@_both_exp_pow
|
200 |
+
def test_exp_leading_term():
|
201 |
+
assert exp(x).as_leading_term(x) == 1
|
202 |
+
assert exp(2 + x).as_leading_term(x) == exp(2)
|
203 |
+
assert exp((2*x + 3) / (x+1)).as_leading_term(x) == exp(3)
|
204 |
+
|
205 |
+
# The following tests are commented, since now SymPy returns the
|
206 |
+
# original function when the leading term in the series expansion does
|
207 |
+
# not exist.
|
208 |
+
# raises(NotImplementedError, lambda: exp(1/x).as_leading_term(x))
|
209 |
+
# raises(NotImplementedError, lambda: exp((x + 1) / x**2).as_leading_term(x))
|
210 |
+
# raises(NotImplementedError, lambda: exp(x + 1/x).as_leading_term(x))
|
211 |
+
|
212 |
+
|
213 |
+
@_both_exp_pow
|
214 |
+
def test_exp_taylor_term():
|
215 |
+
x = symbols('x')
|
216 |
+
assert exp(x).taylor_term(1, x) == x
|
217 |
+
assert exp(x).taylor_term(3, x) == x**3/6
|
218 |
+
assert exp(x).taylor_term(4, x) == x**4/24
|
219 |
+
assert exp(x).taylor_term(-1, x) is S.Zero
|
220 |
+
|
221 |
+
|
222 |
+
def test_exp_MatrixSymbol():
|
223 |
+
A = MatrixSymbol("A", 2, 2)
|
224 |
+
assert exp(A).has(exp)
|
225 |
+
|
226 |
+
|
227 |
+
def test_exp_fdiff():
|
228 |
+
x = Symbol('x')
|
229 |
+
raises(ArgumentIndexError, lambda: exp(x).fdiff(2))
|
230 |
+
|
231 |
+
|
232 |
+
def test_log_values():
|
233 |
+
assert log(nan) is nan
|
234 |
+
|
235 |
+
assert log(oo) is oo
|
236 |
+
assert log(-oo) is oo
|
237 |
+
|
238 |
+
assert log(zoo) is zoo
|
239 |
+
assert log(-zoo) is zoo
|
240 |
+
|
241 |
+
assert log(0) is zoo
|
242 |
+
|
243 |
+
assert log(1) == 0
|
244 |
+
assert log(-1) == I*pi
|
245 |
+
|
246 |
+
assert log(E) == 1
|
247 |
+
assert log(-E).expand() == 1 + I*pi
|
248 |
+
|
249 |
+
assert unchanged(log, pi)
|
250 |
+
assert log(-pi).expand() == log(pi) + I*pi
|
251 |
+
|
252 |
+
assert unchanged(log, 17)
|
253 |
+
assert log(-17) == log(17) + I*pi
|
254 |
+
|
255 |
+
assert log(I) == I*pi/2
|
256 |
+
assert log(-I) == -I*pi/2
|
257 |
+
|
258 |
+
assert log(17*I) == I*pi/2 + log(17)
|
259 |
+
assert log(-17*I).expand() == -I*pi/2 + log(17)
|
260 |
+
|
261 |
+
assert log(oo*I) is oo
|
262 |
+
assert log(-oo*I) is oo
|
263 |
+
assert log(0, 2) is zoo
|
264 |
+
assert log(0, 5) is zoo
|
265 |
+
|
266 |
+
assert exp(-log(3))**(-1) == 3
|
267 |
+
|
268 |
+
assert log(S.Half) == -log(2)
|
269 |
+
assert log(2*3).func is log
|
270 |
+
assert log(2*3**2).func is log
|
271 |
+
|
272 |
+
|
273 |
+
def test_match_real_imag():
|
274 |
+
x, y = symbols('x,y', real=True)
|
275 |
+
i = Symbol('i', imaginary=True)
|
276 |
+
assert match_real_imag(S.One) == (1, 0)
|
277 |
+
assert match_real_imag(I) == (0, 1)
|
278 |
+
assert match_real_imag(3 - 5*I) == (3, -5)
|
279 |
+
assert match_real_imag(-sqrt(3) + S.Half*I) == (-sqrt(3), S.Half)
|
280 |
+
assert match_real_imag(x + y*I) == (x, y)
|
281 |
+
assert match_real_imag(x*I + y*I) == (0, x + y)
|
282 |
+
assert match_real_imag((x + y)*I) == (0, x + y)
|
283 |
+
assert match_real_imag(Rational(-2, 3)*i*I) == (None, None)
|
284 |
+
assert match_real_imag(1 - 2*i) == (None, None)
|
285 |
+
assert match_real_imag(sqrt(2)*(3 - 5*I)) == (None, None)
|
286 |
+
|
287 |
+
|
288 |
+
def test_log_exact():
|
289 |
+
# check for pi/2, pi/3, pi/4, pi/6, pi/8, pi/12; pi/5, pi/10:
|
290 |
+
for n in range(-23, 24):
|
291 |
+
if gcd(n, 24) != 1:
|
292 |
+
assert log(exp(n*I*pi/24).rewrite(sqrt)) == n*I*pi/24
|
293 |
+
for n in range(-9, 10):
|
294 |
+
assert log(exp(n*I*pi/10).rewrite(sqrt)) == n*I*pi/10
|
295 |
+
|
296 |
+
assert log(S.Half - I*sqrt(3)/2) == -I*pi/3
|
297 |
+
assert log(Rational(-1, 2) + I*sqrt(3)/2) == I*pi*Rational(2, 3)
|
298 |
+
assert log(-sqrt(2)/2 - I*sqrt(2)/2) == -I*pi*Rational(3, 4)
|
299 |
+
assert log(-sqrt(3)/2 - I*S.Half) == -I*pi*Rational(5, 6)
|
300 |
+
|
301 |
+
assert log(Rational(-1, 4) + sqrt(5)/4 - I*sqrt(sqrt(5)/8 + Rational(5, 8))) == -I*pi*Rational(2, 5)
|
302 |
+
assert log(sqrt(Rational(5, 8) - sqrt(5)/8) + I*(Rational(1, 4) + sqrt(5)/4)) == I*pi*Rational(3, 10)
|
303 |
+
assert log(-sqrt(sqrt(2)/4 + S.Half) + I*sqrt(S.Half - sqrt(2)/4)) == I*pi*Rational(7, 8)
|
304 |
+
assert log(-sqrt(6)/4 - sqrt(2)/4 + I*(-sqrt(6)/4 + sqrt(2)/4)) == -I*pi*Rational(11, 12)
|
305 |
+
|
306 |
+
assert log(-1 + I*sqrt(3)) == log(2) + I*pi*Rational(2, 3)
|
307 |
+
assert log(5 + 5*I) == log(5*sqrt(2)) + I*pi/4
|
308 |
+
assert log(sqrt(-12)) == log(2*sqrt(3)) + I*pi/2
|
309 |
+
assert log(-sqrt(6) + sqrt(2) - I*sqrt(6) - I*sqrt(2)) == log(4) - I*pi*Rational(7, 12)
|
310 |
+
assert log(-sqrt(6-3*sqrt(2)) - I*sqrt(6+3*sqrt(2))) == log(2*sqrt(3)) - I*pi*Rational(5, 8)
|
311 |
+
assert log(1 + I*sqrt(2-sqrt(2))/sqrt(2+sqrt(2))) == log(2/sqrt(sqrt(2) + 2)) + I*pi/8
|
312 |
+
assert log(cos(pi*Rational(7, 12)) + I*sin(pi*Rational(7, 12))) == I*pi*Rational(7, 12)
|
313 |
+
assert log(cos(pi*Rational(6, 5)) + I*sin(pi*Rational(6, 5))) == I*pi*Rational(-4, 5)
|
314 |
+
|
315 |
+
assert log(5*(1 + I)/sqrt(2)) == log(5) + I*pi/4
|
316 |
+
assert log(sqrt(2)*(-sqrt(3) + 1 - sqrt(3)*I - I)) == log(4) - I*pi*Rational(7, 12)
|
317 |
+
assert log(-sqrt(2)*(1 - I*sqrt(3))) == log(2*sqrt(2)) + I*pi*Rational(2, 3)
|
318 |
+
assert log(sqrt(3)*I*(-sqrt(6 - 3*sqrt(2)) - I*sqrt(3*sqrt(2) + 6))) == log(6) - I*pi/8
|
319 |
+
|
320 |
+
zero = (1 + sqrt(2))**2 - 3 - 2*sqrt(2)
|
321 |
+
assert log(zero - I*sqrt(3)) == log(sqrt(3)) - I*pi/2
|
322 |
+
assert unchanged(log, zero + I*zero) or log(zero + zero*I) is zoo
|
323 |
+
|
324 |
+
# bail quickly if no obvious simplification is possible:
|
325 |
+
assert unchanged(log, (sqrt(2)-1/sqrt(sqrt(3)+I))**1000)
|
326 |
+
# beware of non-real coefficients
|
327 |
+
assert unchanged(log, sqrt(2-sqrt(5))*(1 + I))
|
328 |
+
|
329 |
+
|
330 |
+
def test_log_base():
|
331 |
+
assert log(1, 2) == 0
|
332 |
+
assert log(2, 2) == 1
|
333 |
+
assert log(3, 2) == log(3)/log(2)
|
334 |
+
assert log(6, 2) == 1 + log(3)/log(2)
|
335 |
+
assert log(6, 3) == 1 + log(2)/log(3)
|
336 |
+
assert log(2**3, 2) == 3
|
337 |
+
assert log(3**3, 3) == 3
|
338 |
+
assert log(5, 1) is zoo
|
339 |
+
assert log(1, 1) is nan
|
340 |
+
assert log(Rational(2, 3), 10) == log(Rational(2, 3))/log(10)
|
341 |
+
assert log(Rational(2, 3), Rational(1, 3)) == -log(2)/log(3) + 1
|
342 |
+
assert log(Rational(2, 3), Rational(2, 5)) == \
|
343 |
+
log(Rational(2, 3))/log(Rational(2, 5))
|
344 |
+
# issue 17148
|
345 |
+
assert log(Rational(8, 3), 2) == -log(3)/log(2) + 3
|
346 |
+
|
347 |
+
|
348 |
+
def test_log_symbolic():
|
349 |
+
assert log(x, exp(1)) == log(x)
|
350 |
+
assert log(exp(x)) != x
|
351 |
+
|
352 |
+
assert log(x, exp(1)) == log(x)
|
353 |
+
assert log(x*y) != log(x) + log(y)
|
354 |
+
assert log(x/y).expand() != log(x) - log(y)
|
355 |
+
assert log(x/y).expand(force=True) == log(x) - log(y)
|
356 |
+
assert log(x**y).expand() != y*log(x)
|
357 |
+
assert log(x**y).expand(force=True) == y*log(x)
|
358 |
+
|
359 |
+
assert log(x, 2) == log(x)/log(2)
|
360 |
+
assert log(E, 2) == 1/log(2)
|
361 |
+
|
362 |
+
p, q = symbols('p,q', positive=True)
|
363 |
+
r = Symbol('r', real=True)
|
364 |
+
|
365 |
+
assert log(p**2) != 2*log(p)
|
366 |
+
assert log(p**2).expand() == 2*log(p)
|
367 |
+
assert log(x**2).expand() != 2*log(x)
|
368 |
+
assert log(p**q) != q*log(p)
|
369 |
+
assert log(exp(p)) == p
|
370 |
+
assert log(p*q) != log(p) + log(q)
|
371 |
+
assert log(p*q).expand() == log(p) + log(q)
|
372 |
+
|
373 |
+
assert log(-sqrt(3)) == log(sqrt(3)) + I*pi
|
374 |
+
assert log(-exp(p)) != p + I*pi
|
375 |
+
assert log(-exp(x)).expand() != x + I*pi
|
376 |
+
assert log(-exp(r)).expand() == r + I*pi
|
377 |
+
|
378 |
+
assert log(x**y) != y*log(x)
|
379 |
+
|
380 |
+
assert (log(x**-5)**-1).expand() != -1/log(x)/5
|
381 |
+
assert (log(p**-5)**-1).expand() == -1/log(p)/5
|
382 |
+
assert log(-x).func is log and log(-x).args[0] == -x
|
383 |
+
assert log(-p).func is log and log(-p).args[0] == -p
|
384 |
+
|
385 |
+
|
386 |
+
def test_log_exp():
|
387 |
+
assert log(exp(4*I*pi)) == 0 # exp evaluates
|
388 |
+
assert log(exp(-5*I*pi)) == I*pi # exp evaluates
|
389 |
+
assert log(exp(I*pi*Rational(19, 4))) == I*pi*Rational(3, 4)
|
390 |
+
assert log(exp(I*pi*Rational(25, 7))) == I*pi*Rational(-3, 7)
|
391 |
+
assert log(exp(-5*I)) == -5*I + 2*I*pi
|
392 |
+
|
393 |
+
|
394 |
+
@_both_exp_pow
|
395 |
+
def test_exp_assumptions():
|
396 |
+
r = Symbol('r', real=True)
|
397 |
+
i = Symbol('i', imaginary=True)
|
398 |
+
for e in exp, exp_polar:
|
399 |
+
assert e(x).is_real is None
|
400 |
+
assert e(x).is_imaginary is None
|
401 |
+
assert e(i).is_real is None
|
402 |
+
assert e(i).is_imaginary is None
|
403 |
+
assert e(r).is_real is True
|
404 |
+
assert e(r).is_imaginary is False
|
405 |
+
assert e(re(x)).is_extended_real is True
|
406 |
+
assert e(re(x)).is_imaginary is False
|
407 |
+
|
408 |
+
assert Pow(E, I*pi, evaluate=False).is_imaginary == False
|
409 |
+
assert Pow(E, 2*I*pi, evaluate=False).is_imaginary == False
|
410 |
+
assert Pow(E, I*pi/2, evaluate=False).is_imaginary == True
|
411 |
+
assert Pow(E, I*pi/3, evaluate=False).is_imaginary is None
|
412 |
+
|
413 |
+
assert exp(0, evaluate=False).is_algebraic
|
414 |
+
|
415 |
+
a = Symbol('a', algebraic=True)
|
416 |
+
an = Symbol('an', algebraic=True, nonzero=True)
|
417 |
+
r = Symbol('r', rational=True)
|
418 |
+
rn = Symbol('rn', rational=True, nonzero=True)
|
419 |
+
assert exp(a).is_algebraic is None
|
420 |
+
assert exp(an).is_algebraic is False
|
421 |
+
assert exp(pi*r).is_algebraic is None
|
422 |
+
assert exp(pi*rn).is_algebraic is False
|
423 |
+
|
424 |
+
assert exp(0, evaluate=False).is_algebraic is True
|
425 |
+
assert exp(I*pi/3, evaluate=False).is_algebraic is True
|
426 |
+
assert exp(I*pi*r, evaluate=False).is_algebraic is True
|
427 |
+
|
428 |
+
|
429 |
+
@_both_exp_pow
|
430 |
+
def test_exp_AccumBounds():
|
431 |
+
assert exp(AccumBounds(1, 2)) == AccumBounds(E, E**2)
|
432 |
+
|
433 |
+
|
434 |
+
def test_log_assumptions():
|
435 |
+
p = symbols('p', positive=True)
|
436 |
+
n = symbols('n', negative=True)
|
437 |
+
z = symbols('z', zero=True)
|
438 |
+
x = symbols('x', infinite=True, extended_positive=True)
|
439 |
+
|
440 |
+
assert log(z).is_positive is False
|
441 |
+
assert log(x).is_extended_positive is True
|
442 |
+
assert log(2) > 0
|
443 |
+
assert log(1, evaluate=False).is_zero
|
444 |
+
assert log(1 + z).is_zero
|
445 |
+
assert log(p).is_zero is None
|
446 |
+
assert log(n).is_zero is False
|
447 |
+
assert log(0.5).is_negative is True
|
448 |
+
assert log(exp(p) + 1).is_positive
|
449 |
+
|
450 |
+
assert log(1, evaluate=False).is_algebraic
|
451 |
+
assert log(42, evaluate=False).is_algebraic is False
|
452 |
+
|
453 |
+
assert log(1 + z).is_rational
|
454 |
+
|
455 |
+
|
456 |
+
def test_log_hashing():
|
457 |
+
assert x != log(log(x))
|
458 |
+
assert hash(x) != hash(log(log(x)))
|
459 |
+
assert log(x) != log(log(log(x)))
|
460 |
+
|
461 |
+
e = 1/log(log(x) + log(log(x)))
|
462 |
+
assert e.base.func is log
|
463 |
+
e = 1/log(log(x) + log(log(log(x))))
|
464 |
+
assert e.base.func is log
|
465 |
+
|
466 |
+
e = log(log(x))
|
467 |
+
assert e.func is log
|
468 |
+
assert x.func is not log
|
469 |
+
assert hash(log(log(x))) != hash(x)
|
470 |
+
assert e != x
|
471 |
+
|
472 |
+
|
473 |
+
def test_log_sign():
|
474 |
+
assert sign(log(2)) == 1
|
475 |
+
|
476 |
+
|
477 |
+
def test_log_expand_complex():
|
478 |
+
assert log(1 + I).expand(complex=True) == log(2)/2 + I*pi/4
|
479 |
+
assert log(1 - sqrt(2)).expand(complex=True) == log(sqrt(2) - 1) + I*pi
|
480 |
+
|
481 |
+
|
482 |
+
def test_log_apply_evalf():
|
483 |
+
value = (log(3)/log(2) - 1).evalf()
|
484 |
+
assert value.epsilon_eq(Float("0.58496250072115618145373"))
|
485 |
+
|
486 |
+
|
487 |
+
def test_log_leading_term():
|
488 |
+
p = Symbol('p')
|
489 |
+
|
490 |
+
# Test for STEP 3
|
491 |
+
assert log(1 + x + x**2).as_leading_term(x, cdir=1) == x
|
492 |
+
# Test for STEP 4
|
493 |
+
assert log(2*x).as_leading_term(x, cdir=1) == log(x) + log(2)
|
494 |
+
assert log(2*x).as_leading_term(x, cdir=-1) == log(x) + log(2)
|
495 |
+
assert log(-2*x).as_leading_term(x, cdir=1, logx=p) == p + log(2) + I*pi
|
496 |
+
assert log(-2*x).as_leading_term(x, cdir=-1, logx=p) == p + log(2) - I*pi
|
497 |
+
# Test for STEP 5
|
498 |
+
assert log(-2*x + (3 - I)*x**2).as_leading_term(x, cdir=1) == log(x) + log(2) - I*pi
|
499 |
+
assert log(-2*x + (3 - I)*x**2).as_leading_term(x, cdir=-1) == log(x) + log(2) - I*pi
|
500 |
+
assert log(2*x + (3 - I)*x**2).as_leading_term(x, cdir=1) == log(x) + log(2)
|
501 |
+
assert log(2*x + (3 - I)*x**2).as_leading_term(x, cdir=-1) == log(x) + log(2) - 2*I*pi
|
502 |
+
assert log(-1 + x - I*x**2 + I*x**3).as_leading_term(x, cdir=1) == -I*pi
|
503 |
+
assert log(-1 + x - I*x**2 + I*x**3).as_leading_term(x, cdir=-1) == -I*pi
|
504 |
+
assert log(-1/(1 - x)).as_leading_term(x, cdir=1) == I*pi
|
505 |
+
assert log(-1/(1 - x)).as_leading_term(x, cdir=-1) == I*pi
|
506 |
+
|
507 |
+
|
508 |
+
def test_log_nseries():
|
509 |
+
p = Symbol('p')
|
510 |
+
assert log(1/x)._eval_nseries(x, 4, logx=-p, cdir=1) == p
|
511 |
+
assert log(1/x)._eval_nseries(x, 4, logx=-p, cdir=-1) == p + 2*I*pi
|
512 |
+
assert log(x - 1)._eval_nseries(x, 4, None, I) == I*pi - x - x**2/2 - x**3/3 + O(x**4)
|
513 |
+
assert log(x - 1)._eval_nseries(x, 4, None, -I) == -I*pi - x - x**2/2 - x**3/3 + O(x**4)
|
514 |
+
assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x + x**2/2 + O(x**3)
|
515 |
+
assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == -I*pi - I*x + x**2/2 + O(x**3)
|
516 |
+
assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x**2 + O(x**3)
|
517 |
+
assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == I*pi - I*x**2 + O(x**3)
|
518 |
+
assert log(2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, 1) == log(2) + log(x) + \
|
519 |
+
x*(S(3)/2 - I/2) + x**2*(-1 + 3*I/4) + O(x**3)
|
520 |
+
assert log(2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, -1) == -2*I*pi + log(2) + \
|
521 |
+
log(x) - x*(-S(3)/2 + I/2) + x**2*(-1 + 3*I/4) + O(x**3)
|
522 |
+
assert log(-2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, 1) == -I*pi + log(2) + log(x) + \
|
523 |
+
x*(-S(3)/2 + I/2) + x**2*(-1 + 3*I/4) + O(x**3)
|
524 |
+
assert log(-2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, -1) == -I*pi + log(2) + log(x) - \
|
525 |
+
x*(S(3)/2 - I/2) + x**2*(-1 + 3*I/4) + O(x**3)
|
526 |
+
assert log(sqrt(-I*x**2 - 3)*sqrt(-I*x**2 - 1) - 2)._eval_nseries(x, 3, None, 1) == -I*pi + \
|
527 |
+
log(sqrt(3) + 2) + I*x**2*(-2 + 4*sqrt(3)/3) + O(x**3)
|
528 |
+
assert log(-1/(1 - x))._eval_nseries(x, 3, None, 1) == I*pi + x + x**2/2 + O(x**3)
|
529 |
+
assert log(-1/(1 - x))._eval_nseries(x, 3, None, -1) == I*pi + x + x**2/2 + O(x**3)
|
530 |
+
|
531 |
+
|
532 |
+
def test_log_series():
|
533 |
+
# Note Series at infinities other than oo/-oo were introduced as a part of
|
534 |
+
# pull request 23798. Refer https://github.com/sympy/sympy/pull/23798 for
|
535 |
+
# more information.
|
536 |
+
expr1 = log(1 + x)
|
537 |
+
expr2 = log(x + sqrt(x**2 + 1))
|
538 |
+
|
539 |
+
assert expr1.series(x, x0=I*oo, n=4) == 1/(3*x**3) - 1/(2*x**2) + 1/x + \
|
540 |
+
I*pi/2 - log(I/x) + O(x**(-4), (x, oo*I))
|
541 |
+
assert expr1.series(x, x0=-I*oo, n=4) == 1/(3*x**3) - 1/(2*x**2) + 1/x - \
|
542 |
+
I*pi/2 - log(-I/x) + O(x**(-4), (x, -oo*I))
|
543 |
+
assert expr2.series(x, x0=I*oo, n=4) == 1/(4*x**2) + I*pi/2 + log(2) - \
|
544 |
+
log(I/x) + O(x**(-4), (x, oo*I))
|
545 |
+
assert expr2.series(x, x0=-I*oo, n=4) == -1/(4*x**2) - I*pi/2 - log(2) + \
|
546 |
+
log(-I/x) + O(x**(-4), (x, -oo*I))
|
547 |
+
|
548 |
+
|
549 |
+
def test_log_expand():
|
550 |
+
w = Symbol("w", positive=True)
|
551 |
+
e = log(w**(log(5)/log(3)))
|
552 |
+
assert e.expand() == log(5)/log(3) * log(w)
|
553 |
+
x, y, z = symbols('x,y,z', positive=True)
|
554 |
+
assert log(x*(y + z)).expand(mul=False) == log(x) + log(y + z)
|
555 |
+
assert log(log(x**2)*log(y*z)).expand() in [log(2*log(x)*log(y) +
|
556 |
+
2*log(x)*log(z)), log(log(x)*log(z) + log(y)*log(x)) + log(2),
|
557 |
+
log((log(y) + log(z))*log(x)) + log(2)]
|
558 |
+
assert log(x**log(x**2)).expand(deep=False) == log(x)*log(x**2)
|
559 |
+
assert log(x**log(x**2)).expand() == 2*log(x)**2
|
560 |
+
x, y = symbols('x,y')
|
561 |
+
assert log(x*y).expand(force=True) == log(x) + log(y)
|
562 |
+
assert log(x**y).expand(force=True) == y*log(x)
|
563 |
+
assert log(exp(x)).expand(force=True) == x
|
564 |
+
|
565 |
+
# there's generally no need to expand out logs since this requires
|
566 |
+
# factoring and if simplification is sought, it's cheaper to put
|
567 |
+
# logs together than it is to take them apart.
|
568 |
+
assert log(2*3**2).expand() != 2*log(3) + log(2)
|
569 |
+
|
570 |
+
|
571 |
+
@XFAIL
|
572 |
+
def test_log_expand_fail():
|
573 |
+
x, y, z = symbols('x,y,z', positive=True)
|
574 |
+
assert (log(x*(y + z))*(x + y)).expand(mul=True, log=True) == y*log(
|
575 |
+
x) + y*log(y + z) + z*log(x) + z*log(y + z)
|
576 |
+
|
577 |
+
|
578 |
+
def test_log_simplify():
|
579 |
+
x = Symbol("x", positive=True)
|
580 |
+
assert log(x**2).expand() == 2*log(x)
|
581 |
+
assert expand_log(log(x**(2 + log(2)))) == (2 + log(2))*log(x)
|
582 |
+
|
583 |
+
z = Symbol('z')
|
584 |
+
assert log(sqrt(z)).expand() == log(z)/2
|
585 |
+
assert expand_log(log(z**(log(2) - 1))) == (log(2) - 1)*log(z)
|
586 |
+
assert log(z**(-1)).expand() != -log(z)
|
587 |
+
assert log(z**(x/(x+1))).expand() == x*log(z)/(x + 1)
|
588 |
+
|
589 |
+
|
590 |
+
def test_log_AccumBounds():
|
591 |
+
assert log(AccumBounds(1, E)) == AccumBounds(0, 1)
|
592 |
+
assert log(AccumBounds(0, E)) == AccumBounds(-oo, 1)
|
593 |
+
assert log(AccumBounds(-1, E)) == S.NaN
|
594 |
+
assert log(AccumBounds(0, oo)) == AccumBounds(-oo, oo)
|
595 |
+
assert log(AccumBounds(-oo, 0)) == S.NaN
|
596 |
+
assert log(AccumBounds(-oo, oo)) == S.NaN
|
597 |
+
|
598 |
+
|
599 |
+
@_both_exp_pow
|
600 |
+
def test_lambertw():
|
601 |
+
k = Symbol('k')
|
602 |
+
|
603 |
+
assert LambertW(x, 0) == LambertW(x)
|
604 |
+
assert LambertW(x, 0, evaluate=False) != LambertW(x)
|
605 |
+
assert LambertW(0) == 0
|
606 |
+
assert LambertW(E) == 1
|
607 |
+
assert LambertW(-1/E) == -1
|
608 |
+
assert LambertW(-log(2)/2) == -log(2)
|
609 |
+
assert LambertW(oo) is oo
|
610 |
+
assert LambertW(0, 1) is -oo
|
611 |
+
assert LambertW(0, 42) is -oo
|
612 |
+
assert LambertW(-pi/2, -1) == -I*pi/2
|
613 |
+
assert LambertW(-1/E, -1) == -1
|
614 |
+
assert LambertW(-2*exp(-2), -1) == -2
|
615 |
+
assert LambertW(2*log(2)) == log(2)
|
616 |
+
assert LambertW(-pi/2) == I*pi/2
|
617 |
+
assert LambertW(exp(1 + E)) == E
|
618 |
+
|
619 |
+
assert LambertW(x**2).diff(x) == 2*LambertW(x**2)/x/(1 + LambertW(x**2))
|
620 |
+
assert LambertW(x, k).diff(x) == LambertW(x, k)/x/(1 + LambertW(x, k))
|
621 |
+
|
622 |
+
assert LambertW(sqrt(2)).evalf(30).epsilon_eq(
|
623 |
+
Float("0.701338383413663009202120278965", 30), 1e-29)
|
624 |
+
assert re(LambertW(2, -1)).evalf().epsilon_eq(Float("-0.834310366631110"))
|
625 |
+
|
626 |
+
assert LambertW(-1).is_real is False # issue 5215
|
627 |
+
assert LambertW(2, evaluate=False).is_real
|
628 |
+
p = Symbol('p', positive=True)
|
629 |
+
assert LambertW(p, evaluate=False).is_real
|
630 |
+
assert LambertW(p - 1, evaluate=False).is_real is None
|
631 |
+
assert LambertW(-p - 2/S.Exp1, evaluate=False).is_real is False
|
632 |
+
assert LambertW(S.Half, -1, evaluate=False).is_real is False
|
633 |
+
assert LambertW(Rational(-1, 10), -1, evaluate=False).is_real
|
634 |
+
assert LambertW(-10, -1, evaluate=False).is_real is False
|
635 |
+
assert LambertW(-2, 2, evaluate=False).is_real is False
|
636 |
+
|
637 |
+
assert LambertW(0, evaluate=False).is_algebraic
|
638 |
+
na = Symbol('na', nonzero=True, algebraic=True)
|
639 |
+
assert LambertW(na).is_algebraic is False
|
640 |
+
assert LambertW(p).is_zero is False
|
641 |
+
n = Symbol('n', negative=True)
|
642 |
+
assert LambertW(n).is_zero is False
|
643 |
+
|
644 |
+
|
645 |
+
def test_issue_5673():
|
646 |
+
e = LambertW(-1)
|
647 |
+
assert e.is_comparable is False
|
648 |
+
assert e.is_positive is not True
|
649 |
+
e2 = 1 - 1/(1 - exp(-1000))
|
650 |
+
assert e2.is_positive is not True
|
651 |
+
e3 = -2 + exp(exp(LambertW(log(2)))*LambertW(log(2)))
|
652 |
+
assert e3.is_nonzero is not True
|
653 |
+
|
654 |
+
|
655 |
+
def test_log_fdiff():
|
656 |
+
x = Symbol('x')
|
657 |
+
raises(ArgumentIndexError, lambda: log(x).fdiff(2))
|
658 |
+
|
659 |
+
|
660 |
+
def test_log_taylor_term():
|
661 |
+
x = symbols('x')
|
662 |
+
assert log(x).taylor_term(0, x) == x
|
663 |
+
assert log(x).taylor_term(1, x) == -x**2/2
|
664 |
+
assert log(x).taylor_term(4, x) == x**5/5
|
665 |
+
assert log(x).taylor_term(-1, x) is S.Zero
|
666 |
+
|
667 |
+
|
668 |
+
def test_exp_expand_NC():
|
669 |
+
A, B, C = symbols('A,B,C', commutative=False)
|
670 |
+
|
671 |
+
assert exp(A + B).expand() == exp(A + B)
|
672 |
+
assert exp(A + B + C).expand() == exp(A + B + C)
|
673 |
+
assert exp(x + y).expand() == exp(x)*exp(y)
|
674 |
+
assert exp(x + y + z).expand() == exp(x)*exp(y)*exp(z)
|
675 |
+
|
676 |
+
|
677 |
+
@_both_exp_pow
|
678 |
+
def test_as_numer_denom():
|
679 |
+
n = symbols('n', negative=True)
|
680 |
+
assert exp(x).as_numer_denom() == (exp(x), 1)
|
681 |
+
assert exp(-x).as_numer_denom() == (1, exp(x))
|
682 |
+
assert exp(-2*x).as_numer_denom() == (1, exp(2*x))
|
683 |
+
assert exp(-2).as_numer_denom() == (1, exp(2))
|
684 |
+
assert exp(n).as_numer_denom() == (1, exp(-n))
|
685 |
+
assert exp(-n).as_numer_denom() == (exp(-n), 1)
|
686 |
+
assert exp(-I*x).as_numer_denom() == (1, exp(I*x))
|
687 |
+
assert exp(-I*n).as_numer_denom() == (1, exp(I*n))
|
688 |
+
assert exp(-n).as_numer_denom() == (exp(-n), 1)
|
689 |
+
|
690 |
+
|
691 |
+
@_both_exp_pow
|
692 |
+
def test_polar():
|
693 |
+
x, y = symbols('x y', polar=True)
|
694 |
+
|
695 |
+
assert abs(exp_polar(I*4)) == 1
|
696 |
+
assert abs(exp_polar(0)) == 1
|
697 |
+
assert abs(exp_polar(2 + 3*I)) == exp(2)
|
698 |
+
assert exp_polar(I*10).n() == exp_polar(I*10)
|
699 |
+
|
700 |
+
assert log(exp_polar(z)) == z
|
701 |
+
assert log(x*y).expand() == log(x) + log(y)
|
702 |
+
assert log(x**z).expand() == z*log(x)
|
703 |
+
|
704 |
+
assert exp_polar(3).exp == 3
|
705 |
+
|
706 |
+
# Compare exp(1.0*pi*I).
|
707 |
+
assert (exp_polar(1.0*pi*I).n(n=5)).as_real_imag()[1] >= 0
|
708 |
+
|
709 |
+
assert exp_polar(0).is_rational is True # issue 8008
|
710 |
+
|
711 |
+
|
712 |
+
def test_exp_summation():
|
713 |
+
w = symbols("w")
|
714 |
+
m, n, i, j = symbols("m n i j")
|
715 |
+
expr = exp(Sum(w*i, (i, 0, n), (j, 0, m)))
|
716 |
+
assert expr.expand() == Product(exp(w*i), (i, 0, n), (j, 0, m))
|
717 |
+
|
718 |
+
|
719 |
+
def test_log_product():
|
720 |
+
from sympy.abc import n, m
|
721 |
+
|
722 |
+
i, j = symbols('i,j', positive=True, integer=True)
|
723 |
+
x, y = symbols('x,y', positive=True)
|
724 |
+
z = symbols('z', real=True)
|
725 |
+
w = symbols('w')
|
726 |
+
|
727 |
+
expr = log(Product(x**i, (i, 1, n)))
|
728 |
+
assert simplify(expr) == expr
|
729 |
+
assert expr.expand() == Sum(i*log(x), (i, 1, n))
|
730 |
+
expr = log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))
|
731 |
+
assert simplify(expr) == expr
|
732 |
+
assert expr.expand() == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
|
733 |
+
|
734 |
+
expr = log(Product(-2, (n, 0, 4)))
|
735 |
+
assert simplify(expr) == expr
|
736 |
+
assert expr.expand() == expr
|
737 |
+
assert expr.expand(force=True) == Sum(log(-2), (n, 0, 4))
|
738 |
+
|
739 |
+
expr = log(Product(exp(z*i), (i, 0, n)))
|
740 |
+
assert expr.expand() == Sum(z*i, (i, 0, n))
|
741 |
+
|
742 |
+
expr = log(Product(exp(w*i), (i, 0, n)))
|
743 |
+
assert expr.expand() == expr
|
744 |
+
assert expr.expand(force=True) == Sum(w*i, (i, 0, n))
|
745 |
+
|
746 |
+
expr = log(Product(i**2*abs(j), (i, 1, n), (j, 1, m)))
|
747 |
+
assert expr.expand() == Sum(2*log(i) + log(j), (i, 1, n), (j, 1, m))
|
748 |
+
|
749 |
+
|
750 |
+
@XFAIL
|
751 |
+
def test_log_product_simplify_to_sum():
|
752 |
+
from sympy.abc import n, m
|
753 |
+
i, j = symbols('i,j', positive=True, integer=True)
|
754 |
+
x, y = symbols('x,y', positive=True)
|
755 |
+
assert simplify(log(Product(x**i, (i, 1, n)))) == Sum(i*log(x), (i, 1, n))
|
756 |
+
assert simplify(log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))) == \
|
757 |
+
Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
|
758 |
+
|
759 |
+
|
760 |
+
def test_issue_8866():
|
761 |
+
assert simplify(log(x, 10, evaluate=False)) == simplify(log(x, 10))
|
762 |
+
assert expand_log(log(x, 10, evaluate=False)) == expand_log(log(x, 10))
|
763 |
+
|
764 |
+
y = Symbol('y', positive=True)
|
765 |
+
l1 = log(exp(y), exp(10))
|
766 |
+
b1 = log(exp(y), exp(5))
|
767 |
+
l2 = log(exp(y), exp(10), evaluate=False)
|
768 |
+
b2 = log(exp(y), exp(5), evaluate=False)
|
769 |
+
assert simplify(log(l1, b1)) == simplify(log(l2, b2))
|
770 |
+
assert expand_log(log(l1, b1)) == expand_log(log(l2, b2))
|
771 |
+
|
772 |
+
|
773 |
+
def test_log_expand_factor():
|
774 |
+
assert (log(18)/log(3) - 2).expand(factor=True) == log(2)/log(3)
|
775 |
+
assert (log(12)/log(2)).expand(factor=True) == log(3)/log(2) + 2
|
776 |
+
assert (log(15)/log(3)).expand(factor=True) == 1 + log(5)/log(3)
|
777 |
+
assert (log(2)/(-log(12) + log(24))).expand(factor=True) == 1
|
778 |
+
|
779 |
+
assert expand_log(log(12), factor=True) == log(3) + 2*log(2)
|
780 |
+
assert expand_log(log(21)/log(7), factor=False) == log(3)/log(7) + 1
|
781 |
+
assert expand_log(log(45)/log(5) + log(20), factor=False) == \
|
782 |
+
1 + 2*log(3)/log(5) + log(20)
|
783 |
+
assert expand_log(log(45)/log(5) + log(26), factor=True) == \
|
784 |
+
log(2) + log(13) + (log(5) + 2*log(3))/log(5)
|
785 |
+
|
786 |
+
|
787 |
+
def test_issue_9116():
|
788 |
+
n = Symbol('n', positive=True, integer=True)
|
789 |
+
assert log(n).is_nonnegative is True
|
790 |
+
|
791 |
+
|
792 |
+
def test_issue_18473():
|
793 |
+
assert exp(x*log(cos(1/x))).as_leading_term(x) == S.NaN
|
794 |
+
assert exp(x*log(tan(1/x))).as_leading_term(x) == S.NaN
|
795 |
+
assert log(cos(1/x)).as_leading_term(x) == S.NaN
|
796 |
+
assert log(tan(1/x)).as_leading_term(x) == S.NaN
|
797 |
+
assert log(cos(1/x) + 2).as_leading_term(x) == AccumBounds(0, log(3))
|
798 |
+
assert exp(x*log(cos(1/x) + 2)).as_leading_term(x) == 1
|
799 |
+
assert log(cos(1/x) - 2).as_leading_term(x) == S.NaN
|
800 |
+
assert exp(x*log(cos(1/x) - 2)).as_leading_term(x) == S.NaN
|
801 |
+
assert log(cos(1/x) + 1).as_leading_term(x) == AccumBounds(-oo, log(2))
|
802 |
+
assert exp(x*log(cos(1/x) + 1)).as_leading_term(x) == AccumBounds(0, 1)
|
803 |
+
assert log(sin(1/x)**2).as_leading_term(x) == AccumBounds(-oo, 0)
|
804 |
+
assert exp(x*log(sin(1/x)**2)).as_leading_term(x) == AccumBounds(0, 1)
|
805 |
+
assert log(tan(1/x)**2).as_leading_term(x) == AccumBounds(-oo, oo)
|
806 |
+
assert exp(2*x*(log(tan(1/x)**2))).as_leading_term(x) == AccumBounds(0, oo)
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_interface.py
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This test file tests the SymPy function interface, that people use to create
|
2 |
+
# their own new functions. It should be as easy as possible.
|
3 |
+
from sympy.core.function import Function
|
4 |
+
from sympy.core.sympify import sympify
|
5 |
+
from sympy.functions.elementary.hyperbolic import tanh
|
6 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
7 |
+
from sympy.series.limits import limit
|
8 |
+
from sympy.abc import x
|
9 |
+
|
10 |
+
|
11 |
+
def test_function_series1():
|
12 |
+
"""Create our new "sin" function."""
|
13 |
+
|
14 |
+
class my_function(Function):
|
15 |
+
|
16 |
+
def fdiff(self, argindex=1):
|
17 |
+
return cos(self.args[0])
|
18 |
+
|
19 |
+
@classmethod
|
20 |
+
def eval(cls, arg):
|
21 |
+
arg = sympify(arg)
|
22 |
+
if arg == 0:
|
23 |
+
return sympify(0)
|
24 |
+
|
25 |
+
#Test that the taylor series is correct
|
26 |
+
assert my_function(x).series(x, 0, 10) == sin(x).series(x, 0, 10)
|
27 |
+
assert limit(my_function(x)/x, x, 0) == 1
|
28 |
+
|
29 |
+
|
30 |
+
def test_function_series2():
|
31 |
+
"""Create our new "cos" function."""
|
32 |
+
|
33 |
+
class my_function2(Function):
|
34 |
+
|
35 |
+
def fdiff(self, argindex=1):
|
36 |
+
return -sin(self.args[0])
|
37 |
+
|
38 |
+
@classmethod
|
39 |
+
def eval(cls, arg):
|
40 |
+
arg = sympify(arg)
|
41 |
+
if arg == 0:
|
42 |
+
return sympify(1)
|
43 |
+
|
44 |
+
#Test that the taylor series is correct
|
45 |
+
assert my_function2(x).series(x, 0, 10) == cos(x).series(x, 0, 10)
|
46 |
+
|
47 |
+
|
48 |
+
def test_function_series3():
|
49 |
+
"""
|
50 |
+
Test our easy "tanh" function.
|
51 |
+
|
52 |
+
This test tests two things:
|
53 |
+
* that the Function interface works as expected and it's easy to use
|
54 |
+
* that the general algorithm for the series expansion works even when the
|
55 |
+
derivative is defined recursively in terms of the original function,
|
56 |
+
since tanh(x).diff(x) == 1-tanh(x)**2
|
57 |
+
"""
|
58 |
+
|
59 |
+
class mytanh(Function):
|
60 |
+
|
61 |
+
def fdiff(self, argindex=1):
|
62 |
+
return 1 - mytanh(self.args[0])**2
|
63 |
+
|
64 |
+
@classmethod
|
65 |
+
def eval(cls, arg):
|
66 |
+
arg = sympify(arg)
|
67 |
+
if arg == 0:
|
68 |
+
return sympify(0)
|
69 |
+
|
70 |
+
e = tanh(x)
|
71 |
+
f = mytanh(x)
|
72 |
+
assert e.series(x, 0, 6) == f.series(x, 0, 6)
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_miscellaneous.py
ADDED
@@ -0,0 +1,504 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import itertools as it
|
2 |
+
|
3 |
+
from sympy.core.expr import unchanged
|
4 |
+
from sympy.core.function import Function
|
5 |
+
from sympy.core.numbers import I, oo, Rational
|
6 |
+
from sympy.core.power import Pow
|
7 |
+
from sympy.core.singleton import S
|
8 |
+
from sympy.core.symbol import Symbol
|
9 |
+
from sympy.external import import_module
|
10 |
+
from sympy.functions.elementary.exponential import log
|
11 |
+
from sympy.functions.elementary.integers import floor, ceiling
|
12 |
+
from sympy.functions.elementary.miscellaneous import (sqrt, cbrt, root, Min,
|
13 |
+
Max, real_root, Rem)
|
14 |
+
from sympy.functions.elementary.trigonometric import cos, sin
|
15 |
+
from sympy.functions.special.delta_functions import Heaviside
|
16 |
+
|
17 |
+
from sympy.utilities.lambdify import lambdify
|
18 |
+
from sympy.testing.pytest import raises, skip, ignore_warnings
|
19 |
+
|
20 |
+
def test_Min():
|
21 |
+
from sympy.abc import x, y, z
|
22 |
+
n = Symbol('n', negative=True)
|
23 |
+
n_ = Symbol('n_', negative=True)
|
24 |
+
nn = Symbol('nn', nonnegative=True)
|
25 |
+
nn_ = Symbol('nn_', nonnegative=True)
|
26 |
+
p = Symbol('p', positive=True)
|
27 |
+
p_ = Symbol('p_', positive=True)
|
28 |
+
np = Symbol('np', nonpositive=True)
|
29 |
+
np_ = Symbol('np_', nonpositive=True)
|
30 |
+
r = Symbol('r', real=True)
|
31 |
+
|
32 |
+
assert Min(5, 4) == 4
|
33 |
+
assert Min(-oo, -oo) is -oo
|
34 |
+
assert Min(-oo, n) is -oo
|
35 |
+
assert Min(n, -oo) is -oo
|
36 |
+
assert Min(-oo, np) is -oo
|
37 |
+
assert Min(np, -oo) is -oo
|
38 |
+
assert Min(-oo, 0) is -oo
|
39 |
+
assert Min(0, -oo) is -oo
|
40 |
+
assert Min(-oo, nn) is -oo
|
41 |
+
assert Min(nn, -oo) is -oo
|
42 |
+
assert Min(-oo, p) is -oo
|
43 |
+
assert Min(p, -oo) is -oo
|
44 |
+
assert Min(-oo, oo) is -oo
|
45 |
+
assert Min(oo, -oo) is -oo
|
46 |
+
assert Min(n, n) == n
|
47 |
+
assert unchanged(Min, n, np)
|
48 |
+
assert Min(np, n) == Min(n, np)
|
49 |
+
assert Min(n, 0) == n
|
50 |
+
assert Min(0, n) == n
|
51 |
+
assert Min(n, nn) == n
|
52 |
+
assert Min(nn, n) == n
|
53 |
+
assert Min(n, p) == n
|
54 |
+
assert Min(p, n) == n
|
55 |
+
assert Min(n, oo) == n
|
56 |
+
assert Min(oo, n) == n
|
57 |
+
assert Min(np, np) == np
|
58 |
+
assert Min(np, 0) == np
|
59 |
+
assert Min(0, np) == np
|
60 |
+
assert Min(np, nn) == np
|
61 |
+
assert Min(nn, np) == np
|
62 |
+
assert Min(np, p) == np
|
63 |
+
assert Min(p, np) == np
|
64 |
+
assert Min(np, oo) == np
|
65 |
+
assert Min(oo, np) == np
|
66 |
+
assert Min(0, 0) == 0
|
67 |
+
assert Min(0, nn) == 0
|
68 |
+
assert Min(nn, 0) == 0
|
69 |
+
assert Min(0, p) == 0
|
70 |
+
assert Min(p, 0) == 0
|
71 |
+
assert Min(0, oo) == 0
|
72 |
+
assert Min(oo, 0) == 0
|
73 |
+
assert Min(nn, nn) == nn
|
74 |
+
assert unchanged(Min, nn, p)
|
75 |
+
assert Min(p, nn) == Min(nn, p)
|
76 |
+
assert Min(nn, oo) == nn
|
77 |
+
assert Min(oo, nn) == nn
|
78 |
+
assert Min(p, p) == p
|
79 |
+
assert Min(p, oo) == p
|
80 |
+
assert Min(oo, p) == p
|
81 |
+
assert Min(oo, oo) is oo
|
82 |
+
|
83 |
+
assert Min(n, n_).func is Min
|
84 |
+
assert Min(nn, nn_).func is Min
|
85 |
+
assert Min(np, np_).func is Min
|
86 |
+
assert Min(p, p_).func is Min
|
87 |
+
|
88 |
+
# lists
|
89 |
+
assert Min() is S.Infinity
|
90 |
+
assert Min(x) == x
|
91 |
+
assert Min(x, y) == Min(y, x)
|
92 |
+
assert Min(x, y, z) == Min(z, y, x)
|
93 |
+
assert Min(x, Min(y, z)) == Min(z, y, x)
|
94 |
+
assert Min(x, Max(y, -oo)) == Min(x, y)
|
95 |
+
assert Min(p, oo, n, p, p, p_) == n
|
96 |
+
assert Min(p_, n_, p) == n_
|
97 |
+
assert Min(n, oo, -7, p, p, 2) == Min(n, -7)
|
98 |
+
assert Min(2, x, p, n, oo, n_, p, 2, -2, -2) == Min(-2, x, n, n_)
|
99 |
+
assert Min(0, x, 1, y) == Min(0, x, y)
|
100 |
+
assert Min(1000, 100, -100, x, p, n) == Min(n, x, -100)
|
101 |
+
assert unchanged(Min, sin(x), cos(x))
|
102 |
+
assert Min(sin(x), cos(x)) == Min(cos(x), sin(x))
|
103 |
+
assert Min(cos(x), sin(x)).subs(x, 1) == cos(1)
|
104 |
+
assert Min(cos(x), sin(x)).subs(x, S.Half) == sin(S.Half)
|
105 |
+
raises(ValueError, lambda: Min(cos(x), sin(x)).subs(x, I))
|
106 |
+
raises(ValueError, lambda: Min(I))
|
107 |
+
raises(ValueError, lambda: Min(I, x))
|
108 |
+
raises(ValueError, lambda: Min(S.ComplexInfinity, x))
|
109 |
+
|
110 |
+
assert Min(1, x).diff(x) == Heaviside(1 - x)
|
111 |
+
assert Min(x, 1).diff(x) == Heaviside(1 - x)
|
112 |
+
assert Min(0, -x, 1 - 2*x).diff(x) == -Heaviside(x + Min(0, -2*x + 1)) \
|
113 |
+
- 2*Heaviside(2*x + Min(0, -x) - 1)
|
114 |
+
|
115 |
+
# issue 7619
|
116 |
+
f = Function('f')
|
117 |
+
assert Min(1, 2*Min(f(1), 2)) # doesn't fail
|
118 |
+
|
119 |
+
# issue 7233
|
120 |
+
e = Min(0, x)
|
121 |
+
assert e.n().args == (0, x)
|
122 |
+
|
123 |
+
# issue 8643
|
124 |
+
m = Min(n, p_, n_, r)
|
125 |
+
assert m.is_positive is False
|
126 |
+
assert m.is_nonnegative is False
|
127 |
+
assert m.is_negative is True
|
128 |
+
|
129 |
+
m = Min(p, p_)
|
130 |
+
assert m.is_positive is True
|
131 |
+
assert m.is_nonnegative is True
|
132 |
+
assert m.is_negative is False
|
133 |
+
|
134 |
+
m = Min(p, nn_, p_)
|
135 |
+
assert m.is_positive is None
|
136 |
+
assert m.is_nonnegative is True
|
137 |
+
assert m.is_negative is False
|
138 |
+
|
139 |
+
m = Min(nn, p, r)
|
140 |
+
assert m.is_positive is None
|
141 |
+
assert m.is_nonnegative is None
|
142 |
+
assert m.is_negative is None
|
143 |
+
|
144 |
+
|
145 |
+
def test_Max():
|
146 |
+
from sympy.abc import x, y, z
|
147 |
+
n = Symbol('n', negative=True)
|
148 |
+
n_ = Symbol('n_', negative=True)
|
149 |
+
nn = Symbol('nn', nonnegative=True)
|
150 |
+
p = Symbol('p', positive=True)
|
151 |
+
p_ = Symbol('p_', positive=True)
|
152 |
+
r = Symbol('r', real=True)
|
153 |
+
|
154 |
+
assert Max(5, 4) == 5
|
155 |
+
|
156 |
+
# lists
|
157 |
+
|
158 |
+
assert Max() is S.NegativeInfinity
|
159 |
+
assert Max(x) == x
|
160 |
+
assert Max(x, y) == Max(y, x)
|
161 |
+
assert Max(x, y, z) == Max(z, y, x)
|
162 |
+
assert Max(x, Max(y, z)) == Max(z, y, x)
|
163 |
+
assert Max(x, Min(y, oo)) == Max(x, y)
|
164 |
+
assert Max(n, -oo, n_, p, 2) == Max(p, 2)
|
165 |
+
assert Max(n, -oo, n_, p) == p
|
166 |
+
assert Max(2, x, p, n, -oo, S.NegativeInfinity, n_, p, 2) == Max(2, x, p)
|
167 |
+
assert Max(0, x, 1, y) == Max(1, x, y)
|
168 |
+
assert Max(r, r + 1, r - 1) == 1 + r
|
169 |
+
assert Max(1000, 100, -100, x, p, n) == Max(p, x, 1000)
|
170 |
+
assert Max(cos(x), sin(x)) == Max(sin(x), cos(x))
|
171 |
+
assert Max(cos(x), sin(x)).subs(x, 1) == sin(1)
|
172 |
+
assert Max(cos(x), sin(x)).subs(x, S.Half) == cos(S.Half)
|
173 |
+
raises(ValueError, lambda: Max(cos(x), sin(x)).subs(x, I))
|
174 |
+
raises(ValueError, lambda: Max(I))
|
175 |
+
raises(ValueError, lambda: Max(I, x))
|
176 |
+
raises(ValueError, lambda: Max(S.ComplexInfinity, 1))
|
177 |
+
assert Max(n, -oo, n_, p, 2) == Max(p, 2)
|
178 |
+
assert Max(n, -oo, n_, p, 1000) == Max(p, 1000)
|
179 |
+
|
180 |
+
assert Max(1, x).diff(x) == Heaviside(x - 1)
|
181 |
+
assert Max(x, 1).diff(x) == Heaviside(x - 1)
|
182 |
+
assert Max(x**2, 1 + x, 1).diff(x) == \
|
183 |
+
2*x*Heaviside(x**2 - Max(1, x + 1)) \
|
184 |
+
+ Heaviside(x - Max(1, x**2) + 1)
|
185 |
+
|
186 |
+
e = Max(0, x)
|
187 |
+
assert e.n().args == (0, x)
|
188 |
+
|
189 |
+
# issue 8643
|
190 |
+
m = Max(p, p_, n, r)
|
191 |
+
assert m.is_positive is True
|
192 |
+
assert m.is_nonnegative is True
|
193 |
+
assert m.is_negative is False
|
194 |
+
|
195 |
+
m = Max(n, n_)
|
196 |
+
assert m.is_positive is False
|
197 |
+
assert m.is_nonnegative is False
|
198 |
+
assert m.is_negative is True
|
199 |
+
|
200 |
+
m = Max(n, n_, r)
|
201 |
+
assert m.is_positive is None
|
202 |
+
assert m.is_nonnegative is None
|
203 |
+
assert m.is_negative is None
|
204 |
+
|
205 |
+
m = Max(n, nn, r)
|
206 |
+
assert m.is_positive is None
|
207 |
+
assert m.is_nonnegative is True
|
208 |
+
assert m.is_negative is False
|
209 |
+
|
210 |
+
|
211 |
+
def test_minmax_assumptions():
|
212 |
+
r = Symbol('r', real=True)
|
213 |
+
a = Symbol('a', real=True, algebraic=True)
|
214 |
+
t = Symbol('t', real=True, transcendental=True)
|
215 |
+
q = Symbol('q', rational=True)
|
216 |
+
p = Symbol('p', irrational=True)
|
217 |
+
n = Symbol('n', rational=True, integer=False)
|
218 |
+
i = Symbol('i', integer=True)
|
219 |
+
o = Symbol('o', odd=True)
|
220 |
+
e = Symbol('e', even=True)
|
221 |
+
k = Symbol('k', prime=True)
|
222 |
+
reals = [r, a, t, q, p, n, i, o, e, k]
|
223 |
+
|
224 |
+
for ext in (Max, Min):
|
225 |
+
for x, y in it.product(reals, repeat=2):
|
226 |
+
|
227 |
+
# Must be real
|
228 |
+
assert ext(x, y).is_real
|
229 |
+
|
230 |
+
# Algebraic?
|
231 |
+
if x.is_algebraic and y.is_algebraic:
|
232 |
+
assert ext(x, y).is_algebraic
|
233 |
+
elif x.is_transcendental and y.is_transcendental:
|
234 |
+
assert ext(x, y).is_transcendental
|
235 |
+
else:
|
236 |
+
assert ext(x, y).is_algebraic is None
|
237 |
+
|
238 |
+
# Rational?
|
239 |
+
if x.is_rational and y.is_rational:
|
240 |
+
assert ext(x, y).is_rational
|
241 |
+
elif x.is_irrational and y.is_irrational:
|
242 |
+
assert ext(x, y).is_irrational
|
243 |
+
else:
|
244 |
+
assert ext(x, y).is_rational is None
|
245 |
+
|
246 |
+
# Integer?
|
247 |
+
if x.is_integer and y.is_integer:
|
248 |
+
assert ext(x, y).is_integer
|
249 |
+
elif x.is_noninteger and y.is_noninteger:
|
250 |
+
assert ext(x, y).is_noninteger
|
251 |
+
else:
|
252 |
+
assert ext(x, y).is_integer is None
|
253 |
+
|
254 |
+
# Odd?
|
255 |
+
if x.is_odd and y.is_odd:
|
256 |
+
assert ext(x, y).is_odd
|
257 |
+
elif x.is_odd is False and y.is_odd is False:
|
258 |
+
assert ext(x, y).is_odd is False
|
259 |
+
else:
|
260 |
+
assert ext(x, y).is_odd is None
|
261 |
+
|
262 |
+
# Even?
|
263 |
+
if x.is_even and y.is_even:
|
264 |
+
assert ext(x, y).is_even
|
265 |
+
elif x.is_even is False and y.is_even is False:
|
266 |
+
assert ext(x, y).is_even is False
|
267 |
+
else:
|
268 |
+
assert ext(x, y).is_even is None
|
269 |
+
|
270 |
+
# Prime?
|
271 |
+
if x.is_prime and y.is_prime:
|
272 |
+
assert ext(x, y).is_prime
|
273 |
+
elif x.is_prime is False and y.is_prime is False:
|
274 |
+
assert ext(x, y).is_prime is False
|
275 |
+
else:
|
276 |
+
assert ext(x, y).is_prime is None
|
277 |
+
|
278 |
+
|
279 |
+
def test_issue_8413():
|
280 |
+
x = Symbol('x', real=True)
|
281 |
+
# we can't evaluate in general because non-reals are not
|
282 |
+
# comparable: Min(floor(3.2 + I), 3.2 + I) -> ValueError
|
283 |
+
assert Min(floor(x), x) == floor(x)
|
284 |
+
assert Min(ceiling(x), x) == x
|
285 |
+
assert Max(floor(x), x) == x
|
286 |
+
assert Max(ceiling(x), x) == ceiling(x)
|
287 |
+
|
288 |
+
|
289 |
+
def test_root():
|
290 |
+
from sympy.abc import x
|
291 |
+
n = Symbol('n', integer=True)
|
292 |
+
k = Symbol('k', integer=True)
|
293 |
+
|
294 |
+
assert root(2, 2) == sqrt(2)
|
295 |
+
assert root(2, 1) == 2
|
296 |
+
assert root(2, 3) == 2**Rational(1, 3)
|
297 |
+
assert root(2, 3) == cbrt(2)
|
298 |
+
assert root(2, -5) == 2**Rational(4, 5)/2
|
299 |
+
|
300 |
+
assert root(-2, 1) == -2
|
301 |
+
|
302 |
+
assert root(-2, 2) == sqrt(2)*I
|
303 |
+
assert root(-2, 1) == -2
|
304 |
+
|
305 |
+
assert root(x, 2) == sqrt(x)
|
306 |
+
assert root(x, 1) == x
|
307 |
+
assert root(x, 3) == x**Rational(1, 3)
|
308 |
+
assert root(x, 3) == cbrt(x)
|
309 |
+
assert root(x, -5) == x**Rational(-1, 5)
|
310 |
+
|
311 |
+
assert root(x, n) == x**(1/n)
|
312 |
+
assert root(x, -n) == x**(-1/n)
|
313 |
+
|
314 |
+
assert root(x, n, k) == (-1)**(2*k/n)*x**(1/n)
|
315 |
+
|
316 |
+
|
317 |
+
def test_real_root():
|
318 |
+
assert real_root(-8, 3) == -2
|
319 |
+
assert real_root(-16, 4) == root(-16, 4)
|
320 |
+
r = root(-7, 4)
|
321 |
+
assert real_root(r) == r
|
322 |
+
r1 = root(-1, 3)
|
323 |
+
r2 = r1**2
|
324 |
+
r3 = root(-1, 4)
|
325 |
+
assert real_root(r1 + r2 + r3) == -1 + r2 + r3
|
326 |
+
assert real_root(root(-2, 3)) == -root(2, 3)
|
327 |
+
assert real_root(-8., 3) == -2.0
|
328 |
+
x = Symbol('x')
|
329 |
+
n = Symbol('n')
|
330 |
+
g = real_root(x, n)
|
331 |
+
assert g.subs({"x": -8, "n": 3}) == -2
|
332 |
+
assert g.subs({"x": 8, "n": 3}) == 2
|
333 |
+
# give principle root if there is no real root -- if this is not desired
|
334 |
+
# then maybe a Root class is needed to raise an error instead
|
335 |
+
assert g.subs({"x": I, "n": 3}) == cbrt(I)
|
336 |
+
assert g.subs({"x": -8, "n": 2}) == sqrt(-8)
|
337 |
+
assert g.subs({"x": I, "n": 2}) == sqrt(I)
|
338 |
+
|
339 |
+
|
340 |
+
def test_issue_11463():
|
341 |
+
numpy = import_module('numpy')
|
342 |
+
if not numpy:
|
343 |
+
skip("numpy not installed.")
|
344 |
+
x = Symbol('x')
|
345 |
+
f = lambdify(x, real_root((log(x/(x-2))), 3), 'numpy')
|
346 |
+
# numpy.select evaluates all options before considering conditions,
|
347 |
+
# so it raises a warning about root of negative number which does
|
348 |
+
# not affect the outcome. This warning is suppressed here
|
349 |
+
with ignore_warnings(RuntimeWarning):
|
350 |
+
assert f(numpy.array(-1)) < -1
|
351 |
+
|
352 |
+
|
353 |
+
def test_rewrite_MaxMin_as_Heaviside():
|
354 |
+
from sympy.abc import x
|
355 |
+
assert Max(0, x).rewrite(Heaviside) == x*Heaviside(x)
|
356 |
+
assert Max(3, x).rewrite(Heaviside) == x*Heaviside(x - 3) + \
|
357 |
+
3*Heaviside(-x + 3)
|
358 |
+
assert Max(0, x+2, 2*x).rewrite(Heaviside) == \
|
359 |
+
2*x*Heaviside(2*x)*Heaviside(x - 2) + \
|
360 |
+
(x + 2)*Heaviside(-x + 2)*Heaviside(x + 2)
|
361 |
+
|
362 |
+
assert Min(0, x).rewrite(Heaviside) == x*Heaviside(-x)
|
363 |
+
assert Min(3, x).rewrite(Heaviside) == x*Heaviside(-x + 3) + \
|
364 |
+
3*Heaviside(x - 3)
|
365 |
+
assert Min(x, -x, -2).rewrite(Heaviside) == \
|
366 |
+
x*Heaviside(-2*x)*Heaviside(-x - 2) - \
|
367 |
+
x*Heaviside(2*x)*Heaviside(x - 2) \
|
368 |
+
- 2*Heaviside(-x + 2)*Heaviside(x + 2)
|
369 |
+
|
370 |
+
|
371 |
+
def test_rewrite_MaxMin_as_Piecewise():
|
372 |
+
from sympy.core.symbol import symbols
|
373 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
374 |
+
x, y, z, a, b = symbols('x y z a b', real=True)
|
375 |
+
vx, vy, va = symbols('vx vy va')
|
376 |
+
assert Max(a, b).rewrite(Piecewise) == Piecewise((a, a >= b), (b, True))
|
377 |
+
assert Max(x, y, z).rewrite(Piecewise) == Piecewise((x, (x >= y) & (x >= z)), (y, y >= z), (z, True))
|
378 |
+
assert Max(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a >= b) & (a >= x) & (a >= y)),
|
379 |
+
(b, (b >= x) & (b >= y)), (x, x >= y), (y, True))
|
380 |
+
assert Min(a, b).rewrite(Piecewise) == Piecewise((a, a <= b), (b, True))
|
381 |
+
assert Min(x, y, z).rewrite(Piecewise) == Piecewise((x, (x <= y) & (x <= z)), (y, y <= z), (z, True))
|
382 |
+
assert Min(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a <= b) & (a <= x) & (a <= y)),
|
383 |
+
(b, (b <= x) & (b <= y)), (x, x <= y), (y, True))
|
384 |
+
|
385 |
+
# Piecewise rewriting of Min/Max does also takes place for not explicitly real arguments
|
386 |
+
assert Max(vx, vy).rewrite(Piecewise) == Piecewise((vx, vx >= vy), (vy, True))
|
387 |
+
assert Min(va, vx, vy).rewrite(Piecewise) == Piecewise((va, (va <= vx) & (va <= vy)), (vx, vx <= vy), (vy, True))
|
388 |
+
|
389 |
+
|
390 |
+
def test_issue_11099():
|
391 |
+
from sympy.abc import x, y
|
392 |
+
# some fixed value tests
|
393 |
+
fixed_test_data = {x: -2, y: 3}
|
394 |
+
assert Min(x, y).evalf(subs=fixed_test_data) == \
|
395 |
+
Min(x, y).subs(fixed_test_data).evalf()
|
396 |
+
assert Max(x, y).evalf(subs=fixed_test_data) == \
|
397 |
+
Max(x, y).subs(fixed_test_data).evalf()
|
398 |
+
# randomly generate some test data
|
399 |
+
from sympy.core.random import randint
|
400 |
+
for i in range(20):
|
401 |
+
random_test_data = {x: randint(-100, 100), y: randint(-100, 100)}
|
402 |
+
assert Min(x, y).evalf(subs=random_test_data) == \
|
403 |
+
Min(x, y).subs(random_test_data).evalf()
|
404 |
+
assert Max(x, y).evalf(subs=random_test_data) == \
|
405 |
+
Max(x, y).subs(random_test_data).evalf()
|
406 |
+
|
407 |
+
|
408 |
+
def test_issue_12638():
|
409 |
+
from sympy.abc import a, b, c
|
410 |
+
assert Min(a, b, c, Max(a, b)) == Min(a, b, c)
|
411 |
+
assert Min(a, b, Max(a, b, c)) == Min(a, b)
|
412 |
+
assert Min(a, b, Max(a, c)) == Min(a, b)
|
413 |
+
|
414 |
+
def test_issue_21399():
|
415 |
+
from sympy.abc import a, b, c
|
416 |
+
assert Max(Min(a, b), Min(a, b, c)) == Min(a, b)
|
417 |
+
|
418 |
+
|
419 |
+
def test_instantiation_evaluation():
|
420 |
+
from sympy.abc import v, w, x, y, z
|
421 |
+
assert Min(1, Max(2, x)) == 1
|
422 |
+
assert Max(3, Min(2, x)) == 3
|
423 |
+
assert Min(Max(x, y), Max(x, z)) == Max(x, Min(y, z))
|
424 |
+
assert set(Min(Max(w, x), Max(y, z)).args) == {
|
425 |
+
Max(w, x), Max(y, z)}
|
426 |
+
assert Min(Max(x, y), Max(x, z), w) == Min(
|
427 |
+
w, Max(x, Min(y, z)))
|
428 |
+
A, B = Min, Max
|
429 |
+
for i in range(2):
|
430 |
+
assert A(x, B(x, y)) == x
|
431 |
+
assert A(x, B(y, A(x, w, z))) == A(x, B(y, A(w, z)))
|
432 |
+
A, B = B, A
|
433 |
+
assert Min(w, Max(x, y), Max(v, x, z)) == Min(
|
434 |
+
w, Max(x, Min(y, Max(v, z))))
|
435 |
+
|
436 |
+
def test_rewrite_as_Abs():
|
437 |
+
from itertools import permutations
|
438 |
+
from sympy.functions.elementary.complexes import Abs
|
439 |
+
from sympy.abc import x, y, z, w
|
440 |
+
def test(e):
|
441 |
+
free = e.free_symbols
|
442 |
+
a = e.rewrite(Abs)
|
443 |
+
assert not a.has(Min, Max)
|
444 |
+
for i in permutations(range(len(free))):
|
445 |
+
reps = dict(zip(free, i))
|
446 |
+
assert a.xreplace(reps) == e.xreplace(reps)
|
447 |
+
test(Min(x, y))
|
448 |
+
test(Max(x, y))
|
449 |
+
test(Min(x, y, z))
|
450 |
+
test(Min(Max(w, x), Max(y, z)))
|
451 |
+
|
452 |
+
def test_issue_14000():
|
453 |
+
assert isinstance(sqrt(4, evaluate=False), Pow) == True
|
454 |
+
assert isinstance(cbrt(3.5, evaluate=False), Pow) == True
|
455 |
+
assert isinstance(root(16, 4, evaluate=False), Pow) == True
|
456 |
+
|
457 |
+
assert sqrt(4, evaluate=False) == Pow(4, S.Half, evaluate=False)
|
458 |
+
assert cbrt(3.5, evaluate=False) == Pow(3.5, Rational(1, 3), evaluate=False)
|
459 |
+
assert root(4, 2, evaluate=False) == Pow(4, S.Half, evaluate=False)
|
460 |
+
|
461 |
+
assert root(16, 4, 2, evaluate=False).has(Pow) == True
|
462 |
+
assert real_root(-8, 3, evaluate=False).has(Pow) == True
|
463 |
+
|
464 |
+
def test_issue_6899():
|
465 |
+
from sympy.core.function import Lambda
|
466 |
+
x = Symbol('x')
|
467 |
+
eqn = Lambda(x, x)
|
468 |
+
assert eqn.func(*eqn.args) == eqn
|
469 |
+
|
470 |
+
def test_Rem():
|
471 |
+
from sympy.abc import x, y
|
472 |
+
assert Rem(5, 3) == 2
|
473 |
+
assert Rem(-5, 3) == -2
|
474 |
+
assert Rem(5, -3) == 2
|
475 |
+
assert Rem(-5, -3) == -2
|
476 |
+
assert Rem(x**3, y) == Rem(x**3, y)
|
477 |
+
assert Rem(Rem(-5, 3) + 3, 3) == 1
|
478 |
+
|
479 |
+
|
480 |
+
def test_minmax_no_evaluate():
|
481 |
+
from sympy import evaluate
|
482 |
+
p = Symbol('p', positive=True)
|
483 |
+
|
484 |
+
assert Max(1, 3) == 3
|
485 |
+
assert Max(1, 3).args == ()
|
486 |
+
assert Max(0, p) == p
|
487 |
+
assert Max(0, p).args == ()
|
488 |
+
assert Min(0, p) == 0
|
489 |
+
assert Min(0, p).args == ()
|
490 |
+
|
491 |
+
assert Max(1, 3, evaluate=False) != 3
|
492 |
+
assert Max(1, 3, evaluate=False).args == (1, 3)
|
493 |
+
assert Max(0, p, evaluate=False) != p
|
494 |
+
assert Max(0, p, evaluate=False).args == (0, p)
|
495 |
+
assert Min(0, p, evaluate=False) != 0
|
496 |
+
assert Min(0, p, evaluate=False).args == (0, p)
|
497 |
+
|
498 |
+
with evaluate(False):
|
499 |
+
assert Max(1, 3) != 3
|
500 |
+
assert Max(1, 3).args == (1, 3)
|
501 |
+
assert Max(0, p) != p
|
502 |
+
assert Max(0, p).args == (0, p)
|
503 |
+
assert Min(0, p) != 0
|
504 |
+
assert Min(0, p).args == (0, p)
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_piecewise.py
ADDED
@@ -0,0 +1,1606 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.concrete.summations import Sum
|
2 |
+
from sympy.core.add import Add
|
3 |
+
from sympy.core.basic import Basic
|
4 |
+
from sympy.core.containers import Tuple
|
5 |
+
from sympy.core.expr import unchanged
|
6 |
+
from sympy.core.function import (Function, diff, expand)
|
7 |
+
from sympy.core.mul import Mul
|
8 |
+
from sympy.core.mod import Mod
|
9 |
+
from sympy.core.numbers import (Float, I, Rational, oo, pi, zoo)
|
10 |
+
from sympy.core.relational import (Eq, Ge, Gt, Ne)
|
11 |
+
from sympy.core.singleton import S
|
12 |
+
from sympy.core.symbol import (Symbol, symbols)
|
13 |
+
from sympy.functions.combinatorial.factorials import factorial
|
14 |
+
from sympy.functions.elementary.complexes import (Abs, adjoint, arg, conjugate, im, re, transpose)
|
15 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
16 |
+
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
|
17 |
+
from sympy.functions.elementary.piecewise import (Piecewise,
|
18 |
+
piecewise_fold, piecewise_exclusive, Undefined, ExprCondPair)
|
19 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
20 |
+
from sympy.functions.special.delta_functions import (DiracDelta, Heaviside)
|
21 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
22 |
+
from sympy.integrals.integrals import (Integral, integrate)
|
23 |
+
from sympy.logic.boolalg import (And, ITE, Not, Or)
|
24 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
25 |
+
from sympy.printing import srepr
|
26 |
+
from sympy.sets.contains import Contains
|
27 |
+
from sympy.sets.sets import Interval
|
28 |
+
from sympy.solvers.solvers import solve
|
29 |
+
from sympy.testing.pytest import raises, slow
|
30 |
+
from sympy.utilities.lambdify import lambdify
|
31 |
+
|
32 |
+
a, b, c, d, x, y = symbols('a:d, x, y')
|
33 |
+
z = symbols('z', nonzero=True)
|
34 |
+
|
35 |
+
|
36 |
+
def test_piecewise1():
|
37 |
+
|
38 |
+
# Test canonicalization
|
39 |
+
assert unchanged(Piecewise, ExprCondPair(x, x < 1), ExprCondPair(0, True))
|
40 |
+
assert Piecewise((x, x < 1), (0, True)) == Piecewise(ExprCondPair(x, x < 1),
|
41 |
+
ExprCondPair(0, True))
|
42 |
+
assert Piecewise((x, x < 1), (0, True), (1, True)) == \
|
43 |
+
Piecewise((x, x < 1), (0, True))
|
44 |
+
assert Piecewise((x, x < 1), (0, False), (-1, 1 > 2)) == \
|
45 |
+
Piecewise((x, x < 1))
|
46 |
+
assert Piecewise((x, x < 1), (0, x < 1), (0, True)) == \
|
47 |
+
Piecewise((x, x < 1), (0, True))
|
48 |
+
assert Piecewise((x, x < 1), (0, x < 2), (0, True)) == \
|
49 |
+
Piecewise((x, x < 1), (0, True))
|
50 |
+
assert Piecewise((x, x < 1), (x, x < 2), (0, True)) == \
|
51 |
+
Piecewise((x, Or(x < 1, x < 2)), (0, True))
|
52 |
+
assert Piecewise((x, x < 1), (x, x < 2), (x, True)) == x
|
53 |
+
assert Piecewise((x, True)) == x
|
54 |
+
# Explicitly constructed empty Piecewise not accepted
|
55 |
+
raises(TypeError, lambda: Piecewise())
|
56 |
+
# False condition is never retained
|
57 |
+
assert Piecewise((2*x, x < 0), (x, False)) == \
|
58 |
+
Piecewise((2*x, x < 0), (x, False), evaluate=False) == \
|
59 |
+
Piecewise((2*x, x < 0))
|
60 |
+
assert Piecewise((x, False)) == Undefined
|
61 |
+
raises(TypeError, lambda: Piecewise(x))
|
62 |
+
assert Piecewise((x, 1)) == x # 1 and 0 are accepted as True/False
|
63 |
+
raises(TypeError, lambda: Piecewise((x, 2)))
|
64 |
+
raises(TypeError, lambda: Piecewise((x, x**2)))
|
65 |
+
raises(TypeError, lambda: Piecewise(([1], True)))
|
66 |
+
assert Piecewise(((1, 2), True)) == Tuple(1, 2)
|
67 |
+
cond = (Piecewise((1, x < 0), (2, True)) < y)
|
68 |
+
assert Piecewise((1, cond)
|
69 |
+
) == Piecewise((1, ITE(x < 0, y > 1, y > 2)))
|
70 |
+
|
71 |
+
assert Piecewise((1, x > 0), (2, And(x <= 0, x > -1))
|
72 |
+
) == Piecewise((1, x > 0), (2, x > -1))
|
73 |
+
assert Piecewise((1, x <= 0), (2, (x < 0) & (x > -1))
|
74 |
+
) == Piecewise((1, x <= 0))
|
75 |
+
|
76 |
+
# test for supporting Contains in Piecewise
|
77 |
+
pwise = Piecewise(
|
78 |
+
(1, And(x <= 6, x > 1, Contains(x, S.Integers))),
|
79 |
+
(0, True))
|
80 |
+
assert pwise.subs(x, pi) == 0
|
81 |
+
assert pwise.subs(x, 2) == 1
|
82 |
+
assert pwise.subs(x, 7) == 0
|
83 |
+
|
84 |
+
# Test subs
|
85 |
+
p = Piecewise((-1, x < -1), (x**2, x < 0), (log(x), x >= 0))
|
86 |
+
p_x2 = Piecewise((-1, x**2 < -1), (x**4, x**2 < 0), (log(x**2), x**2 >= 0))
|
87 |
+
assert p.subs(x, x**2) == p_x2
|
88 |
+
assert p.subs(x, -5) == -1
|
89 |
+
assert p.subs(x, -1) == 1
|
90 |
+
assert p.subs(x, 1) == log(1)
|
91 |
+
|
92 |
+
# More subs tests
|
93 |
+
p2 = Piecewise((1, x < pi), (-1, x < 2*pi), (0, x > 2*pi))
|
94 |
+
p3 = Piecewise((1, Eq(x, 0)), (1/x, True))
|
95 |
+
p4 = Piecewise((1, Eq(x, 0)), (2, 1/x>2))
|
96 |
+
assert p2.subs(x, 2) == 1
|
97 |
+
assert p2.subs(x, 4) == -1
|
98 |
+
assert p2.subs(x, 10) == 0
|
99 |
+
assert p3.subs(x, 0.0) == 1
|
100 |
+
assert p4.subs(x, 0.0) == 1
|
101 |
+
|
102 |
+
|
103 |
+
f, g, h = symbols('f,g,h', cls=Function)
|
104 |
+
pf = Piecewise((f(x), x < -1), (f(x) + h(x) + 2, x <= 1))
|
105 |
+
pg = Piecewise((g(x), x < -1), (g(x) + h(x) + 2, x <= 1))
|
106 |
+
assert pg.subs(g, f) == pf
|
107 |
+
|
108 |
+
assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 0) == 1
|
109 |
+
assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 1) == 0
|
110 |
+
assert Piecewise((1, Eq(x, y)), (0, True)).subs(x, y) == 1
|
111 |
+
assert Piecewise((1, Eq(x, z)), (0, True)).subs(x, z) == 1
|
112 |
+
assert Piecewise((1, Eq(exp(x), cos(z))), (0, True)).subs(x, z) == \
|
113 |
+
Piecewise((1, Eq(exp(z), cos(z))), (0, True))
|
114 |
+
|
115 |
+
p5 = Piecewise( (0, Eq(cos(x) + y, 0)), (1, True))
|
116 |
+
assert p5.subs(y, 0) == Piecewise( (0, Eq(cos(x), 0)), (1, True))
|
117 |
+
|
118 |
+
assert Piecewise((-1, y < 1), (0, x < 0), (1, Eq(x, 0)), (2, True)
|
119 |
+
).subs(x, 1) == Piecewise((-1, y < 1), (2, True))
|
120 |
+
assert Piecewise((1, Eq(x**2, -1)), (2, x < 0)).subs(x, I) == 1
|
121 |
+
|
122 |
+
p6 = Piecewise((x, x > 0))
|
123 |
+
n = symbols('n', negative=True)
|
124 |
+
assert p6.subs(x, n) == Undefined
|
125 |
+
|
126 |
+
# Test evalf
|
127 |
+
assert p.evalf() == Piecewise((-1.0, x < -1), (x**2, x < 0), (log(x), True))
|
128 |
+
assert p.evalf(subs={x: -2}) == -1.0
|
129 |
+
assert p.evalf(subs={x: -1}) == 1.0
|
130 |
+
assert p.evalf(subs={x: 1}) == log(1)
|
131 |
+
assert p6.evalf(subs={x: -5}) == Undefined
|
132 |
+
|
133 |
+
# Test doit
|
134 |
+
f_int = Piecewise((Integral(x, (x, 0, 1)), x < 1))
|
135 |
+
assert f_int.doit() == Piecewise( (S.Half, x < 1) )
|
136 |
+
|
137 |
+
# Test differentiation
|
138 |
+
f = x
|
139 |
+
fp = x*p
|
140 |
+
dp = Piecewise((0, x < -1), (2*x, x < 0), (1/x, x >= 0))
|
141 |
+
fp_dx = x*dp + p
|
142 |
+
assert diff(p, x) == dp
|
143 |
+
assert diff(f*p, x) == fp_dx
|
144 |
+
|
145 |
+
# Test simple arithmetic
|
146 |
+
assert x*p == fp
|
147 |
+
assert x*p + p == p + x*p
|
148 |
+
assert p + f == f + p
|
149 |
+
assert p + dp == dp + p
|
150 |
+
assert p - dp == -(dp - p)
|
151 |
+
|
152 |
+
# Test power
|
153 |
+
dp2 = Piecewise((0, x < -1), (4*x**2, x < 0), (1/x**2, x >= 0))
|
154 |
+
assert dp**2 == dp2
|
155 |
+
|
156 |
+
# Test _eval_interval
|
157 |
+
f1 = x*y + 2
|
158 |
+
f2 = x*y**2 + 3
|
159 |
+
peval = Piecewise((f1, x < 0), (f2, x > 0))
|
160 |
+
peval_interval = f1.subs(
|
161 |
+
x, 0) - f1.subs(x, -1) + f2.subs(x, 1) - f2.subs(x, 0)
|
162 |
+
assert peval._eval_interval(x, 0, 0) == 0
|
163 |
+
assert peval._eval_interval(x, -1, 1) == peval_interval
|
164 |
+
peval2 = Piecewise((f1, x < 0), (f2, True))
|
165 |
+
assert peval2._eval_interval(x, 0, 0) == 0
|
166 |
+
assert peval2._eval_interval(x, 1, -1) == -peval_interval
|
167 |
+
assert peval2._eval_interval(x, -1, -2) == f1.subs(x, -2) - f1.subs(x, -1)
|
168 |
+
assert peval2._eval_interval(x, -1, 1) == peval_interval
|
169 |
+
assert peval2._eval_interval(x, None, 0) == peval2.subs(x, 0)
|
170 |
+
assert peval2._eval_interval(x, -1, None) == -peval2.subs(x, -1)
|
171 |
+
|
172 |
+
# Test integration
|
173 |
+
assert p.integrate() == Piecewise(
|
174 |
+
(-x, x < -1),
|
175 |
+
(x**3/3 + Rational(4, 3), x < 0),
|
176 |
+
(x*log(x) - x + Rational(4, 3), True))
|
177 |
+
p = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x))
|
178 |
+
assert integrate(p, (x, -2, 2)) == Rational(5, 6)
|
179 |
+
assert integrate(p, (x, 2, -2)) == Rational(-5, 6)
|
180 |
+
p = Piecewise((0, x < 0), (1, x < 1), (0, x < 2), (1, x < 3), (0, True))
|
181 |
+
assert integrate(p, (x, -oo, oo)) == 2
|
182 |
+
p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x))
|
183 |
+
assert integrate(p, (x, -2, 2)) == Undefined
|
184 |
+
|
185 |
+
# Test commutativity
|
186 |
+
assert isinstance(p, Piecewise) and p.is_commutative is True
|
187 |
+
|
188 |
+
|
189 |
+
def test_piecewise_free_symbols():
|
190 |
+
f = Piecewise((x, a < 0), (y, True))
|
191 |
+
assert f.free_symbols == {x, y, a}
|
192 |
+
|
193 |
+
|
194 |
+
def test_piecewise_integrate1():
|
195 |
+
x, y = symbols('x y', real=True)
|
196 |
+
|
197 |
+
f = Piecewise(((x - 2)**2, x >= 0), (1, True))
|
198 |
+
assert integrate(f, (x, -2, 2)) == Rational(14, 3)
|
199 |
+
|
200 |
+
g = Piecewise(((x - 5)**5, x >= 4), (f, True))
|
201 |
+
assert integrate(g, (x, -2, 2)) == Rational(14, 3)
|
202 |
+
assert integrate(g, (x, -2, 5)) == Rational(43, 6)
|
203 |
+
|
204 |
+
assert g == Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
|
205 |
+
|
206 |
+
g = Piecewise(((x - 5)**5, 2 <= x), (f, x < 2))
|
207 |
+
assert integrate(g, (x, -2, 2)) == Rational(14, 3)
|
208 |
+
assert integrate(g, (x, -2, 5)) == Rational(-701, 6)
|
209 |
+
|
210 |
+
assert g == Piecewise(((x - 5)**5, 2 <= x), (f, True))
|
211 |
+
|
212 |
+
g = Piecewise(((x - 5)**5, 2 <= x), (2*f, True))
|
213 |
+
assert integrate(g, (x, -2, 2)) == Rational(28, 3)
|
214 |
+
assert integrate(g, (x, -2, 5)) == Rational(-673, 6)
|
215 |
+
|
216 |
+
|
217 |
+
def test_piecewise_integrate1b():
|
218 |
+
g = Piecewise((1, x > 0), (0, Eq(x, 0)), (-1, x < 0))
|
219 |
+
assert integrate(g, (x, -1, 1)) == 0
|
220 |
+
|
221 |
+
g = Piecewise((1, x - y < 0), (0, True))
|
222 |
+
assert integrate(g, (y, -oo, 0)) == -Min(0, x)
|
223 |
+
assert g.subs(x, -3).integrate((y, -oo, 0)) == 3
|
224 |
+
assert integrate(g, (y, 0, -oo)) == Min(0, x)
|
225 |
+
assert integrate(g, (y, 0, oo)) == -Max(0, x) + oo
|
226 |
+
assert integrate(g, (y, -oo, 42)) == -Min(42, x) + 42
|
227 |
+
assert integrate(g, (y, -oo, oo)) == -x + oo
|
228 |
+
|
229 |
+
g = Piecewise((0, x < 0), (x, x <= 1), (1, True))
|
230 |
+
gy1 = g.integrate((x, y, 1))
|
231 |
+
g1y = g.integrate((x, 1, y))
|
232 |
+
for yy in (-1, S.Half, 2):
|
233 |
+
assert g.integrate((x, yy, 1)) == gy1.subs(y, yy)
|
234 |
+
assert g.integrate((x, 1, yy)) == g1y.subs(y, yy)
|
235 |
+
assert gy1 == Piecewise(
|
236 |
+
(-Min(1, Max(0, y))**2/2 + S.Half, y < 1),
|
237 |
+
(-y + 1, True))
|
238 |
+
assert g1y == Piecewise(
|
239 |
+
(Min(1, Max(0, y))**2/2 - S.Half, y < 1),
|
240 |
+
(y - 1, True))
|
241 |
+
|
242 |
+
|
243 |
+
@slow
|
244 |
+
def test_piecewise_integrate1ca():
|
245 |
+
y = symbols('y', real=True)
|
246 |
+
g = Piecewise(
|
247 |
+
(1 - x, Interval(0, 1).contains(x)),
|
248 |
+
(1 + x, Interval(-1, 0).contains(x)),
|
249 |
+
(0, True)
|
250 |
+
)
|
251 |
+
gy1 = g.integrate((x, y, 1))
|
252 |
+
g1y = g.integrate((x, 1, y))
|
253 |
+
|
254 |
+
assert g.integrate((x, -2, 1)) == gy1.subs(y, -2)
|
255 |
+
assert g.integrate((x, 1, -2)) == g1y.subs(y, -2)
|
256 |
+
assert g.integrate((x, 0, 1)) == gy1.subs(y, 0)
|
257 |
+
assert g.integrate((x, 1, 0)) == g1y.subs(y, 0)
|
258 |
+
assert g.integrate((x, 2, 1)) == gy1.subs(y, 2)
|
259 |
+
assert g.integrate((x, 1, 2)) == g1y.subs(y, 2)
|
260 |
+
assert piecewise_fold(gy1.rewrite(Piecewise)
|
261 |
+
).simplify() == Piecewise(
|
262 |
+
(1, y <= -1),
|
263 |
+
(-y**2/2 - y + S.Half, y <= 0),
|
264 |
+
(y**2/2 - y + S.Half, y < 1),
|
265 |
+
(0, True))
|
266 |
+
assert piecewise_fold(g1y.rewrite(Piecewise)
|
267 |
+
).simplify() == Piecewise(
|
268 |
+
(-1, y <= -1),
|
269 |
+
(y**2/2 + y - S.Half, y <= 0),
|
270 |
+
(-y**2/2 + y - S.Half, y < 1),
|
271 |
+
(0, True))
|
272 |
+
assert gy1 == Piecewise(
|
273 |
+
(
|
274 |
+
-Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) +
|
275 |
+
Min(1, Max(0, y))**2 + S.Half, y < 1),
|
276 |
+
(0, True)
|
277 |
+
)
|
278 |
+
assert g1y == Piecewise(
|
279 |
+
(
|
280 |
+
Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) -
|
281 |
+
Min(1, Max(0, y))**2 - S.Half, y < 1),
|
282 |
+
(0, True))
|
283 |
+
|
284 |
+
|
285 |
+
@slow
|
286 |
+
def test_piecewise_integrate1cb():
|
287 |
+
y = symbols('y', real=True)
|
288 |
+
g = Piecewise(
|
289 |
+
(0, Or(x <= -1, x >= 1)),
|
290 |
+
(1 - x, x > 0),
|
291 |
+
(1 + x, True)
|
292 |
+
)
|
293 |
+
gy1 = g.integrate((x, y, 1))
|
294 |
+
g1y = g.integrate((x, 1, y))
|
295 |
+
|
296 |
+
assert g.integrate((x, -2, 1)) == gy1.subs(y, -2)
|
297 |
+
assert g.integrate((x, 1, -2)) == g1y.subs(y, -2)
|
298 |
+
assert g.integrate((x, 0, 1)) == gy1.subs(y, 0)
|
299 |
+
assert g.integrate((x, 1, 0)) == g1y.subs(y, 0)
|
300 |
+
assert g.integrate((x, 2, 1)) == gy1.subs(y, 2)
|
301 |
+
assert g.integrate((x, 1, 2)) == g1y.subs(y, 2)
|
302 |
+
|
303 |
+
assert piecewise_fold(gy1.rewrite(Piecewise)
|
304 |
+
).simplify() == Piecewise(
|
305 |
+
(1, y <= -1),
|
306 |
+
(-y**2/2 - y + S.Half, y <= 0),
|
307 |
+
(y**2/2 - y + S.Half, y < 1),
|
308 |
+
(0, True))
|
309 |
+
assert piecewise_fold(g1y.rewrite(Piecewise)
|
310 |
+
).simplify() == Piecewise(
|
311 |
+
(-1, y <= -1),
|
312 |
+
(y**2/2 + y - S.Half, y <= 0),
|
313 |
+
(-y**2/2 + y - S.Half, y < 1),
|
314 |
+
(0, True))
|
315 |
+
|
316 |
+
# g1y and gy1 should simplify if the condition that y < 1
|
317 |
+
# is applied, e.g. Min(1, Max(-1, y)) --> Max(-1, y)
|
318 |
+
assert gy1 == Piecewise(
|
319 |
+
(
|
320 |
+
-Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) +
|
321 |
+
Min(1, Max(0, y))**2 + S.Half, y < 1),
|
322 |
+
(0, True)
|
323 |
+
)
|
324 |
+
assert g1y == Piecewise(
|
325 |
+
(
|
326 |
+
Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) -
|
327 |
+
Min(1, Max(0, y))**2 - S.Half, y < 1),
|
328 |
+
(0, True))
|
329 |
+
|
330 |
+
|
331 |
+
def test_piecewise_integrate2():
|
332 |
+
from itertools import permutations
|
333 |
+
lim = Tuple(x, c, d)
|
334 |
+
p = Piecewise((1, x < a), (2, x > b), (3, True))
|
335 |
+
q = p.integrate(lim)
|
336 |
+
assert q == Piecewise(
|
337 |
+
(-c + 2*d - 2*Min(d, Max(a, c)) + Min(d, Max(a, b, c)), c < d),
|
338 |
+
(-2*c + d + 2*Min(c, Max(a, d)) - Min(c, Max(a, b, d)), True))
|
339 |
+
for v in permutations((1, 2, 3, 4)):
|
340 |
+
r = dict(zip((a, b, c, d), v))
|
341 |
+
assert p.subs(r).integrate(lim.subs(r)) == q.subs(r)
|
342 |
+
|
343 |
+
|
344 |
+
def test_meijer_bypass():
|
345 |
+
# totally bypass meijerg machinery when dealing
|
346 |
+
# with Piecewise in integrate
|
347 |
+
assert Piecewise((1, x < 4), (0, True)).integrate((x, oo, 1)) == -3
|
348 |
+
|
349 |
+
|
350 |
+
def test_piecewise_integrate3_inequality_conditions():
|
351 |
+
from sympy.utilities.iterables import cartes
|
352 |
+
lim = (x, 0, 5)
|
353 |
+
# set below includes two pts below range, 2 pts in range,
|
354 |
+
# 2 pts above range, and the boundaries
|
355 |
+
N = (-2, -1, 0, 1, 2, 5, 6, 7)
|
356 |
+
|
357 |
+
p = Piecewise((1, x > a), (2, x > b), (0, True))
|
358 |
+
ans = p.integrate(lim)
|
359 |
+
for i, j in cartes(N, repeat=2):
|
360 |
+
reps = dict(zip((a, b), (i, j)))
|
361 |
+
assert ans.subs(reps) == p.subs(reps).integrate(lim)
|
362 |
+
assert ans.subs(a, 4).subs(b, 1) == 0 + 2*3 + 1
|
363 |
+
|
364 |
+
p = Piecewise((1, x > a), (2, x < b), (0, True))
|
365 |
+
ans = p.integrate(lim)
|
366 |
+
for i, j in cartes(N, repeat=2):
|
367 |
+
reps = dict(zip((a, b), (i, j)))
|
368 |
+
assert ans.subs(reps) == p.subs(reps).integrate(lim)
|
369 |
+
|
370 |
+
# delete old tests that involved c1 and c2 since those
|
371 |
+
# reduce to the above except that a value of 0 was used
|
372 |
+
# for two expressions whereas the above uses 3 different
|
373 |
+
# values
|
374 |
+
|
375 |
+
|
376 |
+
@slow
|
377 |
+
def test_piecewise_integrate4_symbolic_conditions():
|
378 |
+
a = Symbol('a', real=True)
|
379 |
+
b = Symbol('b', real=True)
|
380 |
+
x = Symbol('x', real=True)
|
381 |
+
y = Symbol('y', real=True)
|
382 |
+
p0 = Piecewise((0, Or(x < a, x > b)), (1, True))
|
383 |
+
p1 = Piecewise((0, x < a), (0, x > b), (1, True))
|
384 |
+
p2 = Piecewise((0, x > b), (0, x < a), (1, True))
|
385 |
+
p3 = Piecewise((0, x < a), (1, x < b), (0, True))
|
386 |
+
p4 = Piecewise((0, x > b), (1, x > a), (0, True))
|
387 |
+
p5 = Piecewise((1, And(a < x, x < b)), (0, True))
|
388 |
+
|
389 |
+
# check values of a=1, b=3 (and reversed) with values
|
390 |
+
# of y of 0, 1, 2, 3, 4
|
391 |
+
lim = Tuple(x, -oo, y)
|
392 |
+
for p in (p0, p1, p2, p3, p4, p5):
|
393 |
+
ans = p.integrate(lim)
|
394 |
+
for i in range(5):
|
395 |
+
reps = {a:1, b:3, y:i}
|
396 |
+
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
|
397 |
+
reps = {a: 3, b:1, y:i}
|
398 |
+
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
|
399 |
+
lim = Tuple(x, y, oo)
|
400 |
+
for p in (p0, p1, p2, p3, p4, p5):
|
401 |
+
ans = p.integrate(lim)
|
402 |
+
for i in range(5):
|
403 |
+
reps = {a:1, b:3, y:i}
|
404 |
+
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
|
405 |
+
reps = {a:3, b:1, y:i}
|
406 |
+
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
|
407 |
+
|
408 |
+
ans = Piecewise(
|
409 |
+
(0, x <= Min(a, b)),
|
410 |
+
(x - Min(a, b), x <= b),
|
411 |
+
(b - Min(a, b), True))
|
412 |
+
for i in (p0, p1, p2, p4):
|
413 |
+
assert i.integrate(x) == ans
|
414 |
+
assert p3.integrate(x) == Piecewise(
|
415 |
+
(0, x < a),
|
416 |
+
(-a + x, x <= Max(a, b)),
|
417 |
+
(-a + Max(a, b), True))
|
418 |
+
assert p5.integrate(x) == Piecewise(
|
419 |
+
(0, x <= a),
|
420 |
+
(-a + x, x <= Max(a, b)),
|
421 |
+
(-a + Max(a, b), True))
|
422 |
+
|
423 |
+
p1 = Piecewise((0, x < a), (S.Half, x > b), (1, True))
|
424 |
+
p2 = Piecewise((S.Half, x > b), (0, x < a), (1, True))
|
425 |
+
p3 = Piecewise((0, x < a), (1, x < b), (S.Half, True))
|
426 |
+
p4 = Piecewise((S.Half, x > b), (1, x > a), (0, True))
|
427 |
+
p5 = Piecewise((1, And(a < x, x < b)), (S.Half, x > b), (0, True))
|
428 |
+
|
429 |
+
# check values of a=1, b=3 (and reversed) with values
|
430 |
+
# of y of 0, 1, 2, 3, 4
|
431 |
+
lim = Tuple(x, -oo, y)
|
432 |
+
for p in (p1, p2, p3, p4, p5):
|
433 |
+
ans = p.integrate(lim)
|
434 |
+
for i in range(5):
|
435 |
+
reps = {a:1, b:3, y:i}
|
436 |
+
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
|
437 |
+
reps = {a: 3, b:1, y:i}
|
438 |
+
assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
|
439 |
+
|
440 |
+
|
441 |
+
def test_piecewise_integrate5_independent_conditions():
|
442 |
+
p = Piecewise((0, Eq(y, 0)), (x*y, True))
|
443 |
+
assert integrate(p, (x, 1, 3)) == Piecewise((0, Eq(y, 0)), (4*y, True))
|
444 |
+
|
445 |
+
|
446 |
+
def test_issue_22917():
|
447 |
+
p = (Piecewise((0, ITE((x - y > 1) | (2 * x - 2 * y > 1), False,
|
448 |
+
ITE(x - y > 1, 2 * y - 2 < -1, 2 * x - 2 * y > 1))),
|
449 |
+
(Piecewise((0, ITE(x - y > 1, True, 2 * x - 2 * y > 1)),
|
450 |
+
(2 * Piecewise((0, x - y > 1), (y, True)), True)), True))
|
451 |
+
+ 2 * Piecewise((1, ITE((x - y > 1) | (2 * x - 2 * y > 1), False,
|
452 |
+
ITE(x - y > 1, 2 * y - 2 < -1, 2 * x - 2 * y > 1))),
|
453 |
+
(Piecewise((1, ITE(x - y > 1, True, 2 * x - 2 * y > 1)),
|
454 |
+
(2 * Piecewise((1, x - y > 1), (x, True)), True)), True)))
|
455 |
+
assert piecewise_fold(p) == Piecewise((2, (x - y > S.Half) | (x - y > 1)),
|
456 |
+
(2*y + 4, x - y > 1),
|
457 |
+
(4*x + 2*y, True))
|
458 |
+
assert piecewise_fold(p > 1).rewrite(ITE) == ITE((x - y > S.Half) | (x - y > 1), True,
|
459 |
+
ITE(x - y > 1, 2*y + 4 > 1, 4*x + 2*y > 1))
|
460 |
+
|
461 |
+
|
462 |
+
def test_piecewise_simplify():
|
463 |
+
p = Piecewise(((x**2 + 1)/x**2, Eq(x*(1 + x) - x**2, 0)),
|
464 |
+
((-1)**x*(-1), True))
|
465 |
+
assert p.simplify() == \
|
466 |
+
Piecewise((zoo, Eq(x, 0)), ((-1)**(x + 1), True))
|
467 |
+
# simplify when there are Eq in conditions
|
468 |
+
assert Piecewise(
|
469 |
+
(a, And(Eq(a, 0), Eq(a + b, 0))), (1, True)).simplify(
|
470 |
+
) == Piecewise(
|
471 |
+
(0, And(Eq(a, 0), Eq(b, 0))), (1, True))
|
472 |
+
assert Piecewise((2*x*factorial(a)/(factorial(y)*factorial(-y + a)),
|
473 |
+
Eq(y, 0) & Eq(-y + a, 0)), (2*factorial(a)/(factorial(y)*factorial(-y
|
474 |
+
+ a)), Eq(y, 0) & Eq(-y + a, 1)), (0, True)).simplify(
|
475 |
+
) == Piecewise(
|
476 |
+
(2*x, And(Eq(a, 0), Eq(y, 0))),
|
477 |
+
(2, And(Eq(a, 1), Eq(y, 0))),
|
478 |
+
(0, True))
|
479 |
+
args = (2, And(Eq(x, 2), Ge(y, 0))), (x, True)
|
480 |
+
assert Piecewise(*args).simplify() == Piecewise(*args)
|
481 |
+
args = (1, Eq(x, 0)), (sin(x)/x, True)
|
482 |
+
assert Piecewise(*args).simplify() == Piecewise(*args)
|
483 |
+
assert Piecewise((2 + y, And(Eq(x, 2), Eq(y, 0))), (x, True)
|
484 |
+
).simplify() == x
|
485 |
+
# check that x or f(x) are recognized as being Symbol-like for lhs
|
486 |
+
args = Tuple((1, Eq(x, 0)), (sin(x) + 1 + x, True))
|
487 |
+
ans = x + sin(x) + 1
|
488 |
+
f = Function('f')
|
489 |
+
assert Piecewise(*args).simplify() == ans
|
490 |
+
assert Piecewise(*args.subs(x, f(x))).simplify() == ans.subs(x, f(x))
|
491 |
+
|
492 |
+
# issue 18634
|
493 |
+
d = Symbol("d", integer=True)
|
494 |
+
n = Symbol("n", integer=True)
|
495 |
+
t = Symbol("t", positive=True)
|
496 |
+
expr = Piecewise((-d + 2*n, Eq(1/t, 1)), (t**(1 - 4*n)*t**(4*n - 1)*(-d + 2*n), True))
|
497 |
+
assert expr.simplify() == -d + 2*n
|
498 |
+
|
499 |
+
# issue 22747
|
500 |
+
p = Piecewise((0, (t < -2) & (t < -1) & (t < 0)), ((t/2 + 1)*(t +
|
501 |
+
1)*(t + 2), (t < -1) & (t < 0)), ((S.Half - t/2)*(1 - t)*(t + 1),
|
502 |
+
(t < -2) & (t < -1) & (t < 1)), ((t + 1)*(-t*(t/2 + 1) + (S.Half
|
503 |
+
- t/2)*(1 - t)), (t < -2) & (t < -1) & (t < 0) & (t < 1)), ((t +
|
504 |
+
1)*((S.Half - t/2)*(1 - t) + (t/2 + 1)*(t + 2)), (t < -1) & (t <
|
505 |
+
1)), ((t + 1)*(-t*(t/2 + 1) + (S.Half - t/2)*(1 - t)), (t < -1) &
|
506 |
+
(t < 0) & (t < 1)), (0, (t < -2) & (t < -1)), ((t/2 + 1)*(t +
|
507 |
+
1)*(t + 2), t < -1), ((t + 1)*(-t*(t/2 + 1) + (S.Half - t/2)*(t +
|
508 |
+
1)), (t < 0) & ((t < -2) | (t < 0))), ((S.Half - t/2)*(1 - t)*(t
|
509 |
+
+ 1), (t < 1) & ((t < -2) | (t < 1))), (0, True)) + Piecewise((0,
|
510 |
+
(t < -1) & (t < 0) & (t < 1)), ((1 - t)*(t/2 + S.Half)*(t + 1),
|
511 |
+
(t < 0) & (t < 1)), ((1 - t)*(1 - t/2)*(2 - t), (t < -1) & (t <
|
512 |
+
0) & (t < 2)), ((1 - t)*((1 - t)*(t/2 + S.Half) + (1 - t/2)*(2 -
|
513 |
+
t)), (t < -1) & (t < 0) & (t < 1) & (t < 2)), ((1 - t)*((1 -
|
514 |
+
t/2)*(2 - t) + (t/2 + S.Half)*(t + 1)), (t < 0) & (t < 2)), ((1 -
|
515 |
+
t)*((1 - t)*(t/2 + S.Half) + (1 - t/2)*(2 - t)), (t < 0) & (t <
|
516 |
+
1) & (t < 2)), (0, (t < -1) & (t < 0)), ((1 - t)*(t/2 +
|
517 |
+
S.Half)*(t + 1), t < 0), ((1 - t)*(t*(1 - t/2) + (1 - t)*(t/2 +
|
518 |
+
S.Half)), (t < 1) & ((t < -1) | (t < 1))), ((1 - t)*(1 - t/2)*(2
|
519 |
+
- t), (t < 2) & ((t < -1) | (t < 2))), (0, True))
|
520 |
+
assert p.simplify() == Piecewise(
|
521 |
+
(0, t < -2), ((t + 1)*(t + 2)**2/2, t < -1), (-3*t**3/2
|
522 |
+
- 5*t**2/2 + 1, t < 0), (3*t**3/2 - 5*t**2/2 + 1, t < 1), ((1 -
|
523 |
+
t)*(t - 2)**2/2, t < 2), (0, True))
|
524 |
+
|
525 |
+
# coverage
|
526 |
+
nan = Undefined
|
527 |
+
covered = Piecewise((1, x > 3), (2, x < 2), (3, x > 1))
|
528 |
+
assert covered.simplify().args == covered.args
|
529 |
+
assert Piecewise((1, x < 2), (2, x < 1), (3, True)).simplify(
|
530 |
+
) == Piecewise((1, x < 2), (3, True))
|
531 |
+
assert Piecewise((1, x > 2)).simplify() == Piecewise((1, x > 2),
|
532 |
+
(nan, True))
|
533 |
+
assert Piecewise((1, (x >= 2) & (x < oo))
|
534 |
+
).simplify() == Piecewise((1, (x >= 2) & (x < oo)), (nan, True))
|
535 |
+
assert Piecewise((1, x < 2), (2, (x > 1) & (x < 3)), (3, True)
|
536 |
+
). simplify() == Piecewise((1, x < 2), (2, x < 3), (3, True))
|
537 |
+
assert Piecewise((1, x < 2), (2, (x <= 3) & (x > 1)), (3, True)
|
538 |
+
).simplify() == Piecewise((1, x < 2), (2, x <= 3), (3, True))
|
539 |
+
assert Piecewise((1, x < 2), (2, (x > 2) & (x < 3)), (3, True)
|
540 |
+
).simplify() == Piecewise((1, x < 2), (2, (x > 2) & (x < 3)),
|
541 |
+
(3, True))
|
542 |
+
assert Piecewise((1, x < 2), (2, (x >= 1) & (x <= 3)), (3, True)
|
543 |
+
).simplify() == Piecewise((1, x < 2), (2, x <= 3), (3, True))
|
544 |
+
assert Piecewise((1, x < 1), (2, (x >= 2) & (x <= 3)), (3, True)
|
545 |
+
).simplify() == Piecewise((1, x < 1), (2, (x >= 2) & (x <= 3)),
|
546 |
+
(3, True))
|
547 |
+
|
548 |
+
|
549 |
+
def test_piecewise_solve():
|
550 |
+
abs2 = Piecewise((-x, x <= 0), (x, x > 0))
|
551 |
+
f = abs2.subs(x, x - 2)
|
552 |
+
assert solve(f, x) == [2]
|
553 |
+
assert solve(f - 1, x) == [1, 3]
|
554 |
+
|
555 |
+
f = Piecewise(((x - 2)**2, x >= 0), (1, True))
|
556 |
+
assert solve(f, x) == [2]
|
557 |
+
|
558 |
+
g = Piecewise(((x - 5)**5, x >= 4), (f, True))
|
559 |
+
assert solve(g, x) == [2, 5]
|
560 |
+
|
561 |
+
g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
|
562 |
+
assert solve(g, x) == [2, 5]
|
563 |
+
|
564 |
+
g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2))
|
565 |
+
assert solve(g, x) == [5]
|
566 |
+
|
567 |
+
g = Piecewise(((x - 5)**5, x >= 2), (f, True))
|
568 |
+
assert solve(g, x) == [5]
|
569 |
+
|
570 |
+
g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False))
|
571 |
+
assert solve(g, x) == [5]
|
572 |
+
|
573 |
+
g = Piecewise(((x - 5)**5, x >= 2),
|
574 |
+
(-x + 2, x - 2 <= 0), (x - 2, x - 2 > 0))
|
575 |
+
assert solve(g, x) == [5]
|
576 |
+
|
577 |
+
# if no symbol is given the piecewise detection must still work
|
578 |
+
assert solve(Piecewise((x - 2, x > 2), (2 - x, True)) - 3) == [-1, 5]
|
579 |
+
|
580 |
+
f = Piecewise(((x - 2)**2, x >= 0), (0, True))
|
581 |
+
raises(NotImplementedError, lambda: solve(f, x))
|
582 |
+
|
583 |
+
def nona(ans):
|
584 |
+
return list(filter(lambda x: x is not S.NaN, ans))
|
585 |
+
p = Piecewise((x**2 - 4, x < y), (x - 2, True))
|
586 |
+
ans = solve(p, x)
|
587 |
+
assert nona([i.subs(y, -2) for i in ans]) == [2]
|
588 |
+
assert nona([i.subs(y, 2) for i in ans]) == [-2, 2]
|
589 |
+
assert nona([i.subs(y, 3) for i in ans]) == [-2, 2]
|
590 |
+
assert ans == [
|
591 |
+
Piecewise((-2, y > -2), (S.NaN, True)),
|
592 |
+
Piecewise((2, y <= 2), (S.NaN, True)),
|
593 |
+
Piecewise((2, y > 2), (S.NaN, True))]
|
594 |
+
|
595 |
+
# issue 6060
|
596 |
+
absxm3 = Piecewise(
|
597 |
+
(x - 3, 0 <= x - 3),
|
598 |
+
(3 - x, 0 > x - 3)
|
599 |
+
)
|
600 |
+
assert solve(absxm3 - y, x) == [
|
601 |
+
Piecewise((-y + 3, -y < 0), (S.NaN, True)),
|
602 |
+
Piecewise((y + 3, y >= 0), (S.NaN, True))]
|
603 |
+
p = Symbol('p', positive=True)
|
604 |
+
assert solve(absxm3 - p, x) == [-p + 3, p + 3]
|
605 |
+
|
606 |
+
# issue 6989
|
607 |
+
f = Function('f')
|
608 |
+
assert solve(Eq(-f(x), Piecewise((1, x > 0), (0, True))), f(x)) == \
|
609 |
+
[Piecewise((-1, x > 0), (0, True))]
|
610 |
+
|
611 |
+
# issue 8587
|
612 |
+
f = Piecewise((2*x**2, And(0 < x, x < 1)), (2, True))
|
613 |
+
assert solve(f - 1) == [1/sqrt(2)]
|
614 |
+
|
615 |
+
|
616 |
+
def test_piecewise_fold():
|
617 |
+
p = Piecewise((x, x < 1), (1, 1 <= x))
|
618 |
+
|
619 |
+
assert piecewise_fold(x*p) == Piecewise((x**2, x < 1), (x, 1 <= x))
|
620 |
+
assert piecewise_fold(p + p) == Piecewise((2*x, x < 1), (2, 1 <= x))
|
621 |
+
assert piecewise_fold(Piecewise((1, x < 0), (2, True))
|
622 |
+
+ Piecewise((10, x < 0), (-10, True))) == \
|
623 |
+
Piecewise((11, x < 0), (-8, True))
|
624 |
+
|
625 |
+
p1 = Piecewise((0, x < 0), (x, x <= 1), (0, True))
|
626 |
+
p2 = Piecewise((0, x < 0), (1 - x, x <= 1), (0, True))
|
627 |
+
|
628 |
+
p = 4*p1 + 2*p2
|
629 |
+
assert integrate(
|
630 |
+
piecewise_fold(p), (x, -oo, oo)) == integrate(2*x + 2, (x, 0, 1))
|
631 |
+
|
632 |
+
assert piecewise_fold(
|
633 |
+
Piecewise((1, y <= 0), (-Piecewise((2, y >= 0)), True)
|
634 |
+
)) == Piecewise((1, y <= 0), (-2, y >= 0))
|
635 |
+
|
636 |
+
assert piecewise_fold(Piecewise((x, ITE(x > 0, y < 1, y > 1)))
|
637 |
+
) == Piecewise((x, ((x <= 0) | (y < 1)) & ((x > 0) | (y > 1))))
|
638 |
+
|
639 |
+
a, b = (Piecewise((2, Eq(x, 0)), (0, True)),
|
640 |
+
Piecewise((x, Eq(-x + y, 0)), (1, Eq(-x + y, 1)), (0, True)))
|
641 |
+
assert piecewise_fold(Mul(a, b, evaluate=False)
|
642 |
+
) == piecewise_fold(Mul(b, a, evaluate=False))
|
643 |
+
|
644 |
+
|
645 |
+
def test_piecewise_fold_piecewise_in_cond():
|
646 |
+
p1 = Piecewise((cos(x), x < 0), (0, True))
|
647 |
+
p2 = Piecewise((0, Eq(p1, 0)), (p1 / Abs(p1), True))
|
648 |
+
assert p2.subs(x, -pi/2) == 0
|
649 |
+
assert p2.subs(x, 1) == 0
|
650 |
+
assert p2.subs(x, -pi/4) == 1
|
651 |
+
p4 = Piecewise((0, Eq(p1, 0)), (1,True))
|
652 |
+
ans = piecewise_fold(p4)
|
653 |
+
for i in range(-1, 1):
|
654 |
+
assert ans.subs(x, i) == p4.subs(x, i)
|
655 |
+
|
656 |
+
r1 = 1 < Piecewise((1, x < 1), (3, True))
|
657 |
+
ans = piecewise_fold(r1)
|
658 |
+
for i in range(2):
|
659 |
+
assert ans.subs(x, i) == r1.subs(x, i)
|
660 |
+
|
661 |
+
p5 = Piecewise((1, x < 0), (3, True))
|
662 |
+
p6 = Piecewise((1, x < 1), (3, True))
|
663 |
+
p7 = Piecewise((1, p5 < p6), (0, True))
|
664 |
+
ans = piecewise_fold(p7)
|
665 |
+
for i in range(-1, 2):
|
666 |
+
assert ans.subs(x, i) == p7.subs(x, i)
|
667 |
+
|
668 |
+
|
669 |
+
def test_piecewise_fold_piecewise_in_cond_2():
|
670 |
+
p1 = Piecewise((cos(x), x < 0), (0, True))
|
671 |
+
p2 = Piecewise((0, Eq(p1, 0)), (1 / p1, True))
|
672 |
+
p3 = Piecewise(
|
673 |
+
(0, (x >= 0) | Eq(cos(x), 0)),
|
674 |
+
(1/cos(x), x < 0),
|
675 |
+
(zoo, True)) # redundant b/c all x are already covered
|
676 |
+
assert(piecewise_fold(p2) == p3)
|
677 |
+
|
678 |
+
|
679 |
+
def test_piecewise_fold_expand():
|
680 |
+
p1 = Piecewise((1, Interval(0, 1, False, True).contains(x)), (0, True))
|
681 |
+
|
682 |
+
p2 = piecewise_fold(expand((1 - x)*p1))
|
683 |
+
cond = ((x >= 0) & (x < 1))
|
684 |
+
assert piecewise_fold(expand((1 - x)*p1), evaluate=False
|
685 |
+
) == Piecewise((1 - x, cond), (-x, cond), (1, cond), (0, True), evaluate=False)
|
686 |
+
assert piecewise_fold(expand((1 - x)*p1), evaluate=None
|
687 |
+
) == Piecewise((1 - x, cond), (0, True))
|
688 |
+
assert p2 == Piecewise((1 - x, cond), (0, True))
|
689 |
+
assert p2 == expand(piecewise_fold((1 - x)*p1))
|
690 |
+
|
691 |
+
|
692 |
+
def test_piecewise_duplicate():
|
693 |
+
p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x))
|
694 |
+
assert p == Piecewise(*p.args)
|
695 |
+
|
696 |
+
|
697 |
+
def test_doit():
|
698 |
+
p1 = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x))
|
699 |
+
p2 = Piecewise((x, x < 1), (Integral(2 * x), -1 <= x), (x, 3 < x))
|
700 |
+
assert p2.doit() == p1
|
701 |
+
assert p2.doit(deep=False) == p2
|
702 |
+
# issue 17165
|
703 |
+
p1 = Sum(y**x, (x, -1, oo)).doit()
|
704 |
+
assert p1.doit() == p1
|
705 |
+
|
706 |
+
|
707 |
+
def test_piecewise_interval():
|
708 |
+
p1 = Piecewise((x, Interval(0, 1).contains(x)), (0, True))
|
709 |
+
assert p1.subs(x, -0.5) == 0
|
710 |
+
assert p1.subs(x, 0.5) == 0.5
|
711 |
+
assert p1.diff(x) == Piecewise((1, Interval(0, 1).contains(x)), (0, True))
|
712 |
+
assert integrate(p1, x) == Piecewise(
|
713 |
+
(0, x <= 0),
|
714 |
+
(x**2/2, x <= 1),
|
715 |
+
(S.Half, True))
|
716 |
+
|
717 |
+
|
718 |
+
def test_piecewise_exclusive():
|
719 |
+
p = Piecewise((0, x < 0), (S.Half, x <= 0), (1, True))
|
720 |
+
assert piecewise_exclusive(p) == Piecewise((0, x < 0), (S.Half, Eq(x, 0)),
|
721 |
+
(1, x > 0), evaluate=False)
|
722 |
+
assert piecewise_exclusive(p + 2) == Piecewise((0, x < 0), (S.Half, Eq(x, 0)),
|
723 |
+
(1, x > 0), evaluate=False) + 2
|
724 |
+
assert piecewise_exclusive(Piecewise((1, y <= 0),
|
725 |
+
(-Piecewise((2, y >= 0)), True))) == \
|
726 |
+
Piecewise((1, y <= 0),
|
727 |
+
(-Piecewise((2, y >= 0),
|
728 |
+
(S.NaN, y < 0), evaluate=False), y > 0), evaluate=False)
|
729 |
+
assert piecewise_exclusive(Piecewise((1, x > y))) == Piecewise((1, x > y),
|
730 |
+
(S.NaN, x <= y),
|
731 |
+
evaluate=False)
|
732 |
+
assert piecewise_exclusive(Piecewise((1, x > y)),
|
733 |
+
skip_nan=True) == Piecewise((1, x > y))
|
734 |
+
|
735 |
+
xr, yr = symbols('xr, yr', real=True)
|
736 |
+
|
737 |
+
p1 = Piecewise((1, xr < 0), (2, True), evaluate=False)
|
738 |
+
p1x = Piecewise((1, xr < 0), (2, xr >= 0), evaluate=False)
|
739 |
+
|
740 |
+
p2 = Piecewise((p1, yr < 0), (3, True), evaluate=False)
|
741 |
+
p2x = Piecewise((p1, yr < 0), (3, yr >= 0), evaluate=False)
|
742 |
+
p2xx = Piecewise((p1x, yr < 0), (3, yr >= 0), evaluate=False)
|
743 |
+
|
744 |
+
assert piecewise_exclusive(p2) == p2xx
|
745 |
+
assert piecewise_exclusive(p2, deep=False) == p2x
|
746 |
+
|
747 |
+
|
748 |
+
def test_piecewise_collapse():
|
749 |
+
assert Piecewise((x, True)) == x
|
750 |
+
a = x < 1
|
751 |
+
assert Piecewise((x, a), (x + 1, a)) == Piecewise((x, a))
|
752 |
+
assert Piecewise((x, a), (x + 1, a.reversed)) == Piecewise((x, a))
|
753 |
+
b = x < 5
|
754 |
+
def canonical(i):
|
755 |
+
if isinstance(i, Piecewise):
|
756 |
+
return Piecewise(*i.args)
|
757 |
+
return i
|
758 |
+
for args in [
|
759 |
+
((1, a), (Piecewise((2, a), (3, b)), b)),
|
760 |
+
((1, a), (Piecewise((2, a), (3, b.reversed)), b)),
|
761 |
+
((1, a), (Piecewise((2, a), (3, b)), b), (4, True)),
|
762 |
+
((1, a), (Piecewise((2, a), (3, b), (4, True)), b)),
|
763 |
+
((1, a), (Piecewise((2, a), (3, b), (4, True)), b), (5, True))]:
|
764 |
+
for i in (0, 2, 10):
|
765 |
+
assert canonical(
|
766 |
+
Piecewise(*args, evaluate=False).subs(x, i)
|
767 |
+
) == canonical(Piecewise(*args).subs(x, i))
|
768 |
+
r1, r2, r3, r4 = symbols('r1:5')
|
769 |
+
a = x < r1
|
770 |
+
b = x < r2
|
771 |
+
c = x < r3
|
772 |
+
d = x < r4
|
773 |
+
assert Piecewise((1, a), (Piecewise(
|
774 |
+
(2, a), (3, b), (4, c)), b), (5, c)
|
775 |
+
) == Piecewise((1, a), (3, b), (5, c))
|
776 |
+
assert Piecewise((1, a), (Piecewise(
|
777 |
+
(2, a), (3, b), (4, c), (6, True)), c), (5, d)
|
778 |
+
) == Piecewise((1, a), (Piecewise(
|
779 |
+
(3, b), (4, c)), c), (5, d))
|
780 |
+
assert Piecewise((1, Or(a, d)), (Piecewise(
|
781 |
+
(2, d), (3, b), (4, c)), b), (5, c)
|
782 |
+
) == Piecewise((1, Or(a, d)), (Piecewise(
|
783 |
+
(2, d), (3, b)), b), (5, c))
|
784 |
+
assert Piecewise((1, c), (2, ~c), (3, S.true)
|
785 |
+
) == Piecewise((1, c), (2, S.true))
|
786 |
+
assert Piecewise((1, c), (2, And(~c, b)), (3,True)
|
787 |
+
) == Piecewise((1, c), (2, b), (3, True))
|
788 |
+
assert Piecewise((1, c), (2, Or(~c, b)), (3,True)
|
789 |
+
).subs(dict(zip((r1, r2, r3, r4, x), (1, 2, 3, 4, 3.5)))) == 2
|
790 |
+
assert Piecewise((1, c), (2, ~c)) == Piecewise((1, c), (2, True))
|
791 |
+
|
792 |
+
|
793 |
+
def test_piecewise_lambdify():
|
794 |
+
p = Piecewise(
|
795 |
+
(x**2, x < 0),
|
796 |
+
(x, Interval(0, 1, False, True).contains(x)),
|
797 |
+
(2 - x, x >= 1),
|
798 |
+
(0, True)
|
799 |
+
)
|
800 |
+
|
801 |
+
f = lambdify(x, p)
|
802 |
+
assert f(-2.0) == 4.0
|
803 |
+
assert f(0.0) == 0.0
|
804 |
+
assert f(0.5) == 0.5
|
805 |
+
assert f(2.0) == 0.0
|
806 |
+
|
807 |
+
|
808 |
+
def test_piecewise_series():
|
809 |
+
from sympy.series.order import O
|
810 |
+
p1 = Piecewise((sin(x), x < 0), (cos(x), x > 0))
|
811 |
+
p2 = Piecewise((x + O(x**2), x < 0), (1 + O(x**2), x > 0))
|
812 |
+
assert p1.nseries(x, n=2) == p2
|
813 |
+
|
814 |
+
|
815 |
+
def test_piecewise_as_leading_term():
|
816 |
+
p1 = Piecewise((1/x, x > 1), (0, True))
|
817 |
+
p2 = Piecewise((x, x > 1), (0, True))
|
818 |
+
p3 = Piecewise((1/x, x > 1), (x, True))
|
819 |
+
p4 = Piecewise((x, x > 1), (1/x, True))
|
820 |
+
p5 = Piecewise((1/x, x > 1), (x, True))
|
821 |
+
p6 = Piecewise((1/x, x < 1), (x, True))
|
822 |
+
p7 = Piecewise((x, x < 1), (1/x, True))
|
823 |
+
p8 = Piecewise((x, x > 1), (1/x, True))
|
824 |
+
assert p1.as_leading_term(x) == 0
|
825 |
+
assert p2.as_leading_term(x) == 0
|
826 |
+
assert p3.as_leading_term(x) == x
|
827 |
+
assert p4.as_leading_term(x) == 1/x
|
828 |
+
assert p5.as_leading_term(x) == x
|
829 |
+
assert p6.as_leading_term(x) == 1/x
|
830 |
+
assert p7.as_leading_term(x) == x
|
831 |
+
assert p8.as_leading_term(x) == 1/x
|
832 |
+
|
833 |
+
|
834 |
+
def test_piecewise_complex():
|
835 |
+
p1 = Piecewise((2, x < 0), (1, 0 <= x))
|
836 |
+
p2 = Piecewise((2*I, x < 0), (I, 0 <= x))
|
837 |
+
p3 = Piecewise((I*x, x > 1), (1 + I, True))
|
838 |
+
p4 = Piecewise((-I*conjugate(x), x > 1), (1 - I, True))
|
839 |
+
|
840 |
+
assert conjugate(p1) == p1
|
841 |
+
assert conjugate(p2) == piecewise_fold(-p2)
|
842 |
+
assert conjugate(p3) == p4
|
843 |
+
|
844 |
+
assert p1.is_imaginary is False
|
845 |
+
assert p1.is_real is True
|
846 |
+
assert p2.is_imaginary is True
|
847 |
+
assert p2.is_real is False
|
848 |
+
assert p3.is_imaginary is None
|
849 |
+
assert p3.is_real is None
|
850 |
+
|
851 |
+
assert p1.as_real_imag() == (p1, 0)
|
852 |
+
assert p2.as_real_imag() == (0, -I*p2)
|
853 |
+
|
854 |
+
|
855 |
+
def test_conjugate_transpose():
|
856 |
+
A, B = symbols("A B", commutative=False)
|
857 |
+
p = Piecewise((A*B**2, x > 0), (A**2*B, True))
|
858 |
+
assert p.adjoint() == \
|
859 |
+
Piecewise((adjoint(A*B**2), x > 0), (adjoint(A**2*B), True))
|
860 |
+
assert p.conjugate() == \
|
861 |
+
Piecewise((conjugate(A*B**2), x > 0), (conjugate(A**2*B), True))
|
862 |
+
assert p.transpose() == \
|
863 |
+
Piecewise((transpose(A*B**2), x > 0), (transpose(A**2*B), True))
|
864 |
+
|
865 |
+
|
866 |
+
def test_piecewise_evaluate():
|
867 |
+
assert Piecewise((x, True)) == x
|
868 |
+
assert Piecewise((x, True), evaluate=True) == x
|
869 |
+
assert Piecewise((1, Eq(1, x))).args == ((1, Eq(x, 1)),)
|
870 |
+
assert Piecewise((1, Eq(1, x)), evaluate=False).args == (
|
871 |
+
(1, Eq(1, x)),)
|
872 |
+
# like the additive and multiplicative identities that
|
873 |
+
# cannot be kept in Add/Mul, we also do not keep a single True
|
874 |
+
p = Piecewise((x, True), evaluate=False)
|
875 |
+
assert p == x
|
876 |
+
|
877 |
+
|
878 |
+
def test_as_expr_set_pairs():
|
879 |
+
assert Piecewise((x, x > 0), (-x, x <= 0)).as_expr_set_pairs() == \
|
880 |
+
[(x, Interval(0, oo, True, True)), (-x, Interval(-oo, 0))]
|
881 |
+
|
882 |
+
assert Piecewise(((x - 2)**2, x >= 0), (0, True)).as_expr_set_pairs() == \
|
883 |
+
[((x - 2)**2, Interval(0, oo)), (0, Interval(-oo, 0, True, True))]
|
884 |
+
|
885 |
+
|
886 |
+
def test_S_srepr_is_identity():
|
887 |
+
p = Piecewise((10, Eq(x, 0)), (12, True))
|
888 |
+
q = S(srepr(p))
|
889 |
+
assert p == q
|
890 |
+
|
891 |
+
|
892 |
+
def test_issue_12587():
|
893 |
+
# sort holes into intervals
|
894 |
+
p = Piecewise((1, x > 4), (2, Not((x <= 3) & (x > -1))), (3, True))
|
895 |
+
assert p.integrate((x, -5, 5)) == 23
|
896 |
+
p = Piecewise((1, x > 1), (2, x < y), (3, True))
|
897 |
+
lim = x, -3, 3
|
898 |
+
ans = p.integrate(lim)
|
899 |
+
for i in range(-1, 3):
|
900 |
+
assert ans.subs(y, i) == p.subs(y, i).integrate(lim)
|
901 |
+
|
902 |
+
|
903 |
+
def test_issue_11045():
|
904 |
+
assert integrate(1/(x*sqrt(x**2 - 1)), (x, 1, 2)) == pi/3
|
905 |
+
|
906 |
+
# handle And with Or arguments
|
907 |
+
assert Piecewise((1, And(Or(x < 1, x > 3), x < 2)), (0, True)
|
908 |
+
).integrate((x, 0, 3)) == 1
|
909 |
+
|
910 |
+
# hidden false
|
911 |
+
assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)
|
912 |
+
).integrate((x, 0, 3)) == 5
|
913 |
+
# targetcond is Eq
|
914 |
+
assert Piecewise((1, x > 1), (2, Eq(1, x)), (3, True)
|
915 |
+
).integrate((x, 0, 4)) == 6
|
916 |
+
# And has Relational needing to be solved
|
917 |
+
assert Piecewise((1, And(2*x > x + 1, x < 2)), (0, True)
|
918 |
+
).integrate((x, 0, 3)) == 1
|
919 |
+
# Or has Relational needing to be solved
|
920 |
+
assert Piecewise((1, Or(2*x > x + 2, x < 1)), (0, True)
|
921 |
+
).integrate((x, 0, 3)) == 2
|
922 |
+
# ignore hidden false (handled in canonicalization)
|
923 |
+
assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)
|
924 |
+
).integrate((x, 0, 3)) == 5
|
925 |
+
# watch for hidden True Piecewise
|
926 |
+
assert Piecewise((2, Eq(1 - x, x*(1/x - 1))), (0, True)
|
927 |
+
).integrate((x, 0, 3)) == 6
|
928 |
+
|
929 |
+
# overlapping conditions of targetcond are recognized and ignored;
|
930 |
+
# the condition x > 3 will be pre-empted by the first condition
|
931 |
+
assert Piecewise((1, Or(x < 1, x > 2)), (2, x > 3), (3, True)
|
932 |
+
).integrate((x, 0, 4)) == 6
|
933 |
+
|
934 |
+
# convert Ne to Or
|
935 |
+
assert Piecewise((1, Ne(x, 0)), (2, True)
|
936 |
+
).integrate((x, -1, 1)) == 2
|
937 |
+
|
938 |
+
# no default but well defined
|
939 |
+
assert Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))
|
940 |
+
).integrate((x, 1, 4)) == 5
|
941 |
+
|
942 |
+
p = Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4)))
|
943 |
+
nan = Undefined
|
944 |
+
i = p.integrate((x, 1, y))
|
945 |
+
assert i == Piecewise(
|
946 |
+
(y - 1, y < 1),
|
947 |
+
(Min(3, y)**2/2 - Min(3, y) + Min(4, y) - S.Half,
|
948 |
+
y <= Min(4, y)),
|
949 |
+
(nan, True))
|
950 |
+
assert p.integrate((x, 1, -1)) == i.subs(y, -1)
|
951 |
+
assert p.integrate((x, 1, 4)) == 5
|
952 |
+
assert p.integrate((x, 1, 5)) is nan
|
953 |
+
|
954 |
+
# handle Not
|
955 |
+
p = Piecewise((1, x > 1), (2, Not(And(x > 1, x< 3))), (3, True))
|
956 |
+
assert p.integrate((x, 0, 3)) == 4
|
957 |
+
|
958 |
+
# handle updating of int_expr when there is overlap
|
959 |
+
p = Piecewise(
|
960 |
+
(1, And(5 > x, x > 1)),
|
961 |
+
(2, Or(x < 3, x > 7)),
|
962 |
+
(4, x < 8))
|
963 |
+
assert p.integrate((x, 0, 10)) == 20
|
964 |
+
|
965 |
+
# And with Eq arg handling
|
966 |
+
assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1))
|
967 |
+
).integrate((x, 0, 3)) is S.NaN
|
968 |
+
assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)), (3, True)
|
969 |
+
).integrate((x, 0, 3)) == 7
|
970 |
+
assert Piecewise((1, x < 0), (2, And(Eq(x, 3), x < 1)), (3, True)
|
971 |
+
).integrate((x, -1, 1)) == 4
|
972 |
+
# middle condition doesn't matter: it's a zero width interval
|
973 |
+
assert Piecewise((1, x < 1), (2, Eq(x, 3) & (y < x)), (3, True)
|
974 |
+
).integrate((x, 0, 3)) == 7
|
975 |
+
|
976 |
+
|
977 |
+
def test_holes():
|
978 |
+
nan = Undefined
|
979 |
+
assert Piecewise((1, x < 2)).integrate(x) == Piecewise(
|
980 |
+
(x, x < 2), (nan, True))
|
981 |
+
assert Piecewise((1, And(x > 1, x < 2))).integrate(x) == Piecewise(
|
982 |
+
(nan, x < 1), (x, x < 2), (nan, True))
|
983 |
+
assert Piecewise((1, And(x > 1, x < 2))).integrate((x, 0, 3)) is nan
|
984 |
+
assert Piecewise((1, And(x > 0, x < 4))).integrate((x, 1, 3)) == 2
|
985 |
+
|
986 |
+
# this also tests that the integrate method is used on non-Piecwise
|
987 |
+
# arguments in _eval_integral
|
988 |
+
A, B = symbols("A B")
|
989 |
+
a, b = symbols('a b', real=True)
|
990 |
+
assert Piecewise((A, And(x < 0, a < 1)), (B, Or(x < 1, a > 2))
|
991 |
+
).integrate(x) == Piecewise(
|
992 |
+
(B*x, (a > 2)),
|
993 |
+
(Piecewise((A*x, x < 0), (B*x, x < 1), (nan, True)), a < 1),
|
994 |
+
(Piecewise((B*x, x < 1), (nan, True)), True))
|
995 |
+
|
996 |
+
|
997 |
+
def test_issue_11922():
|
998 |
+
def f(x):
|
999 |
+
return Piecewise((0, x < -1), (1 - x**2, x < 1), (0, True))
|
1000 |
+
autocorr = lambda k: (
|
1001 |
+
f(x) * f(x + k)).integrate((x, -1, 1))
|
1002 |
+
assert autocorr(1.9) > 0
|
1003 |
+
k = symbols('k')
|
1004 |
+
good_autocorr = lambda k: (
|
1005 |
+
(1 - x**2) * f(x + k)).integrate((x, -1, 1))
|
1006 |
+
a = good_autocorr(k)
|
1007 |
+
assert a.subs(k, 3) == 0
|
1008 |
+
k = symbols('k', positive=True)
|
1009 |
+
a = good_autocorr(k)
|
1010 |
+
assert a.subs(k, 3) == 0
|
1011 |
+
assert Piecewise((0, x < 1), (10, (x >= 1))
|
1012 |
+
).integrate() == Piecewise((0, x < 1), (10*x - 10, True))
|
1013 |
+
|
1014 |
+
|
1015 |
+
def test_issue_5227():
|
1016 |
+
f = 0.0032513612725229*Piecewise((0, x < -80.8461538461539),
|
1017 |
+
(-0.0160799238820171*x + 1.33215984776403, x < 2),
|
1018 |
+
(Piecewise((0.3, x > 123), (0.7, True)) +
|
1019 |
+
Piecewise((0.4, x > 2), (0.6, True)), x <=
|
1020 |
+
123), (-0.00817409766454352*x + 2.10541401273885, x <
|
1021 |
+
380.571428571429), (0, True))
|
1022 |
+
i = integrate(f, (x, -oo, oo))
|
1023 |
+
assert i == Integral(f, (x, -oo, oo)).doit()
|
1024 |
+
assert str(i) == '1.00195081676351'
|
1025 |
+
assert Piecewise((1, x - y < 0), (0, True)
|
1026 |
+
).integrate(y) == Piecewise((0, y <= x), (-x + y, True))
|
1027 |
+
|
1028 |
+
|
1029 |
+
def test_issue_10137():
|
1030 |
+
a = Symbol('a', real=True)
|
1031 |
+
b = Symbol('b', real=True)
|
1032 |
+
x = Symbol('x', real=True)
|
1033 |
+
y = Symbol('y', real=True)
|
1034 |
+
p0 = Piecewise((0, Or(x < a, x > b)), (1, True))
|
1035 |
+
p1 = Piecewise((0, Or(a > x, b < x)), (1, True))
|
1036 |
+
assert integrate(p0, (x, y, oo)) == integrate(p1, (x, y, oo))
|
1037 |
+
p3 = Piecewise((1, And(0 < x, x < a)), (0, True))
|
1038 |
+
p4 = Piecewise((1, And(a > x, x > 0)), (0, True))
|
1039 |
+
ip3 = integrate(p3, x)
|
1040 |
+
assert ip3 == Piecewise(
|
1041 |
+
(0, x <= 0),
|
1042 |
+
(x, x <= Max(0, a)),
|
1043 |
+
(Max(0, a), True))
|
1044 |
+
ip4 = integrate(p4, x)
|
1045 |
+
assert ip4 == ip3
|
1046 |
+
assert p3.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2
|
1047 |
+
assert p4.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2
|
1048 |
+
|
1049 |
+
|
1050 |
+
def test_stackoverflow_43852159():
|
1051 |
+
f = lambda x: Piecewise((1, (x >= -1) & (x <= 1)), (0, True))
|
1052 |
+
Conv = lambda x: integrate(f(x - y)*f(y), (y, -oo, +oo))
|
1053 |
+
cx = Conv(x)
|
1054 |
+
assert cx.subs(x, -1.5) == cx.subs(x, 1.5)
|
1055 |
+
assert cx.subs(x, 3) == 0
|
1056 |
+
assert piecewise_fold(f(x - y)*f(y)) == Piecewise(
|
1057 |
+
(1, (y >= -1) & (y <= 1) & (x - y >= -1) & (x - y <= 1)),
|
1058 |
+
(0, True))
|
1059 |
+
|
1060 |
+
|
1061 |
+
def test_issue_12557():
|
1062 |
+
'''
|
1063 |
+
# 3200 seconds to compute the fourier part of issue
|
1064 |
+
import sympy as sym
|
1065 |
+
x,y,z,t = sym.symbols('x y z t')
|
1066 |
+
k = sym.symbols("k", integer=True)
|
1067 |
+
fourier = sym.fourier_series(sym.cos(k*x)*sym.sqrt(x**2),
|
1068 |
+
(x, -sym.pi, sym.pi))
|
1069 |
+
assert fourier == FourierSeries(
|
1070 |
+
sqrt(x**2)*cos(k*x), (x, -pi, pi), (Piecewise((pi**2,
|
1071 |
+
Eq(k, 0)), (2*(-1)**k/k**2 - 2/k**2, True))/(2*pi),
|
1072 |
+
SeqFormula(Piecewise((pi**2, (Eq(_n, 0) & Eq(k, 0)) | (Eq(_n, 0) &
|
1073 |
+
Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(k, 0) & Eq(_n, -k)) | (Eq(_n,
|
1074 |
+
0) & Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), (pi**2/2, Eq(_n, k) | Eq(_n,
|
1075 |
+
-k) | (Eq(_n, 0) & Eq(_n, k)) | (Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) &
|
1076 |
+
Eq(_n, -k)) | (Eq(_n, k) & Eq(_n, -k)) | (Eq(k, 0) & Eq(_n, -k)) |
|
1077 |
+
(Eq(_n, 0) & Eq(_n, k) & Eq(_n, -k)) | (Eq(_n, k) & Eq(k, 0) & Eq(_n,
|
1078 |
+
-k))), ((-1)**k*pi**2*_n**3*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
|
1079 |
+
pi*k**4) - (-1)**k*pi**2*_n**3*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2
|
1080 |
+
- pi*k**4) + (-1)**k*pi*_n**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
|
1081 |
+
pi*k**4) - (-1)**k*pi*_n**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
|
1082 |
+
pi*k**4) - (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(pi*_n**4 -
|
1083 |
+
2*pi*_n**2*k**2 + pi*k**4) +
|
1084 |
+
(-1)**k*pi**2*_n*k**2*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
|
1085 |
+
pi*k**4) + (-1)**k*pi*k**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
|
1086 |
+
pi*k**4) - (-1)**k*pi*k**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
|
1087 |
+
pi*k**4) - (2*_n**2 + 2*k**2)/(_n**4 - 2*_n**2*k**2 + k**4),
|
1088 |
+
True))*cos(_n*x)/pi, (_n, 1, oo)), SeqFormula(0, (_k, 1, oo))))
|
1089 |
+
'''
|
1090 |
+
x = symbols("x", real=True)
|
1091 |
+
k = symbols('k', integer=True, finite=True)
|
1092 |
+
abs2 = lambda x: Piecewise((-x, x <= 0), (x, x > 0))
|
1093 |
+
assert integrate(abs2(x), (x, -pi, pi)) == pi**2
|
1094 |
+
func = cos(k*x)*sqrt(x**2)
|
1095 |
+
assert integrate(func, (x, -pi, pi)) == Piecewise(
|
1096 |
+
(2*(-1)**k/k**2 - 2/k**2, Ne(k, 0)), (pi**2, True))
|
1097 |
+
|
1098 |
+
def test_issue_6900():
|
1099 |
+
from itertools import permutations
|
1100 |
+
t0, t1, T, t = symbols('t0, t1 T t')
|
1101 |
+
f = Piecewise((0, t < t0), (x, And(t0 <= t, t < t1)), (0, t >= t1))
|
1102 |
+
g = f.integrate(t)
|
1103 |
+
assert g == Piecewise(
|
1104 |
+
(0, t <= t0),
|
1105 |
+
(t*x - t0*x, t <= Max(t0, t1)),
|
1106 |
+
(-t0*x + x*Max(t0, t1), True))
|
1107 |
+
for i in permutations(range(2)):
|
1108 |
+
reps = dict(zip((t0,t1), i))
|
1109 |
+
for tt in range(-1,3):
|
1110 |
+
assert (g.xreplace(reps).subs(t,tt) ==
|
1111 |
+
f.xreplace(reps).integrate(t).subs(t,tt))
|
1112 |
+
lim = Tuple(t, t0, T)
|
1113 |
+
g = f.integrate(lim)
|
1114 |
+
ans = Piecewise(
|
1115 |
+
(-t0*x + x*Min(T, Max(t0, t1)), T > t0),
|
1116 |
+
(0, True))
|
1117 |
+
for i in permutations(range(3)):
|
1118 |
+
reps = dict(zip((t0,t1,T), i))
|
1119 |
+
tru = f.xreplace(reps).integrate(lim.xreplace(reps))
|
1120 |
+
assert tru == ans.xreplace(reps)
|
1121 |
+
assert g == ans
|
1122 |
+
|
1123 |
+
|
1124 |
+
def test_issue_10122():
|
1125 |
+
assert solve(abs(x) + abs(x - 1) - 1 > 0, x
|
1126 |
+
) == Or(And(-oo < x, x < S.Zero), And(S.One < x, x < oo))
|
1127 |
+
|
1128 |
+
|
1129 |
+
def test_issue_4313():
|
1130 |
+
u = Piecewise((0, x <= 0), (1, x >= a), (x/a, True))
|
1131 |
+
e = (u - u.subs(x, y))**2/(x - y)**2
|
1132 |
+
M = Max(0, a)
|
1133 |
+
assert integrate(e, x).expand() == Piecewise(
|
1134 |
+
(Piecewise(
|
1135 |
+
(0, x <= 0),
|
1136 |
+
(-y**2/(a**2*x - a**2*y) + x/a**2 - 2*y*log(-y)/a**2 +
|
1137 |
+
2*y*log(x - y)/a**2 - y/a**2, x <= M),
|
1138 |
+
(-y**2/(-a**2*y + a**2*M) + 1/(-y + M) -
|
1139 |
+
1/(x - y) - 2*y*log(-y)/a**2 + 2*y*log(-y +
|
1140 |
+
M)/a**2 - y/a**2 + M/a**2, True)),
|
1141 |
+
((a <= y) & (y <= 0)) | ((y <= 0) & (y > -oo))),
|
1142 |
+
(Piecewise(
|
1143 |
+
(-1/(x - y), x <= 0),
|
1144 |
+
(-a**2/(a**2*x - a**2*y) + 2*a*y/(a**2*x - a**2*y) -
|
1145 |
+
y**2/(a**2*x - a**2*y) + 2*log(-y)/a - 2*log(x - y)/a +
|
1146 |
+
2/a + x/a**2 - 2*y*log(-y)/a**2 + 2*y*log(x - y)/a**2 -
|
1147 |
+
y/a**2, x <= M),
|
1148 |
+
(-a**2/(-a**2*y + a**2*M) + 2*a*y/(-a**2*y +
|
1149 |
+
a**2*M) - y**2/(-a**2*y + a**2*M) +
|
1150 |
+
2*log(-y)/a - 2*log(-y + M)/a + 2/a -
|
1151 |
+
2*y*log(-y)/a**2 + 2*y*log(-y + M)/a**2 -
|
1152 |
+
y/a**2 + M/a**2, True)),
|
1153 |
+
a <= y),
|
1154 |
+
(Piecewise(
|
1155 |
+
(-y**2/(a**2*x - a**2*y), x <= 0),
|
1156 |
+
(x/a**2 + y/a**2, x <= M),
|
1157 |
+
(a**2/(-a**2*y + a**2*M) -
|
1158 |
+
a**2/(a**2*x - a**2*y) - 2*a*y/(-a**2*y + a**2*M) +
|
1159 |
+
2*a*y/(a**2*x - a**2*y) + y**2/(-a**2*y + a**2*M) -
|
1160 |
+
y**2/(a**2*x - a**2*y) + y/a**2 + M/a**2, True)),
|
1161 |
+
True))
|
1162 |
+
|
1163 |
+
|
1164 |
+
def test__intervals():
|
1165 |
+
assert Piecewise((x + 2, Eq(x, 3)))._intervals(x) == (True, [])
|
1166 |
+
assert Piecewise(
|
1167 |
+
(1, x > x + 1),
|
1168 |
+
(Piecewise((1, x < x + 1)), 2*x < 2*x + 1),
|
1169 |
+
(1, True))._intervals(x) == (True, [(-oo, oo, 1, 1)])
|
1170 |
+
assert Piecewise((1, Ne(x, I)), (0, True))._intervals(x) == (True,
|
1171 |
+
[(-oo, oo, 1, 0)])
|
1172 |
+
assert Piecewise((-cos(x), sin(x) >= 0), (cos(x), True)
|
1173 |
+
)._intervals(x) == (True,
|
1174 |
+
[(0, pi, -cos(x), 0), (-oo, oo, cos(x), 1)])
|
1175 |
+
# the following tests that duplicates are removed and that non-Eq
|
1176 |
+
# generated zero-width intervals are removed
|
1177 |
+
assert Piecewise((1, Abs(x**(-2)) > 1), (0, True)
|
1178 |
+
)._intervals(x) == (True,
|
1179 |
+
[(-1, 0, 1, 0), (0, 1, 1, 0), (-oo, oo, 0, 1)])
|
1180 |
+
|
1181 |
+
|
1182 |
+
def test_containment():
|
1183 |
+
a, b, c, d, e = [1, 2, 3, 4, 5]
|
1184 |
+
p = (Piecewise((d, x > 1), (e, True))*
|
1185 |
+
Piecewise((a, Abs(x - 1) < 1), (b, Abs(x - 2) < 2), (c, True)))
|
1186 |
+
assert p.integrate(x).diff(x) == Piecewise(
|
1187 |
+
(c*e, x <= 0),
|
1188 |
+
(a*e, x <= 1),
|
1189 |
+
(a*d, x < 2), # this is what we want to get right
|
1190 |
+
(b*d, x < 4),
|
1191 |
+
(c*d, True))
|
1192 |
+
|
1193 |
+
|
1194 |
+
def test_piecewise_with_DiracDelta():
|
1195 |
+
d1 = DiracDelta(x - 1)
|
1196 |
+
assert integrate(d1, (x, -oo, oo)) == 1
|
1197 |
+
assert integrate(d1, (x, 0, 2)) == 1
|
1198 |
+
assert Piecewise((d1, Eq(x, 2)), (0, True)).integrate(x) == 0
|
1199 |
+
assert Piecewise((d1, x < 2), (0, True)).integrate(x) == Piecewise(
|
1200 |
+
(Heaviside(x - 1), x < 2), (1, True))
|
1201 |
+
# TODO raise error if function is discontinuous at limit of
|
1202 |
+
# integration, e.g. integrate(d1, (x, -2, 1)) or Piecewise(
|
1203 |
+
# (d1, Eq(x, 1)
|
1204 |
+
|
1205 |
+
|
1206 |
+
def test_issue_10258():
|
1207 |
+
assert Piecewise((0, x < 1), (1, True)).is_zero is None
|
1208 |
+
assert Piecewise((-1, x < 1), (1, True)).is_zero is False
|
1209 |
+
a = Symbol('a', zero=True)
|
1210 |
+
assert Piecewise((0, x < 1), (a, True)).is_zero
|
1211 |
+
assert Piecewise((1, x < 1), (a, x < 3)).is_zero is None
|
1212 |
+
a = Symbol('a')
|
1213 |
+
assert Piecewise((0, x < 1), (a, True)).is_zero is None
|
1214 |
+
assert Piecewise((0, x < 1), (1, True)).is_nonzero is None
|
1215 |
+
assert Piecewise((1, x < 1), (2, True)).is_nonzero
|
1216 |
+
assert Piecewise((0, x < 1), (oo, True)).is_finite is None
|
1217 |
+
assert Piecewise((0, x < 1), (1, True)).is_finite
|
1218 |
+
b = Basic()
|
1219 |
+
assert Piecewise((b, x < 1)).is_finite is None
|
1220 |
+
|
1221 |
+
# 10258
|
1222 |
+
c = Piecewise((1, x < 0), (2, True)) < 3
|
1223 |
+
assert c != True
|
1224 |
+
assert piecewise_fold(c) == True
|
1225 |
+
|
1226 |
+
|
1227 |
+
def test_issue_10087():
|
1228 |
+
a, b = Piecewise((x, x > 1), (2, True)), Piecewise((x, x > 3), (3, True))
|
1229 |
+
m = a*b
|
1230 |
+
f = piecewise_fold(m)
|
1231 |
+
for i in (0, 2, 4):
|
1232 |
+
assert m.subs(x, i) == f.subs(x, i)
|
1233 |
+
m = a + b
|
1234 |
+
f = piecewise_fold(m)
|
1235 |
+
for i in (0, 2, 4):
|
1236 |
+
assert m.subs(x, i) == f.subs(x, i)
|
1237 |
+
|
1238 |
+
|
1239 |
+
def test_issue_8919():
|
1240 |
+
c = symbols('c:5')
|
1241 |
+
x = symbols("x")
|
1242 |
+
f1 = Piecewise((c[1], x < 1), (c[2], True))
|
1243 |
+
f2 = Piecewise((c[3], x < Rational(1, 3)), (c[4], True))
|
1244 |
+
assert integrate(f1*f2, (x, 0, 2)
|
1245 |
+
) == c[1]*c[3]/3 + 2*c[1]*c[4]/3 + c[2]*c[4]
|
1246 |
+
f1 = Piecewise((0, x < 1), (2, True))
|
1247 |
+
f2 = Piecewise((3, x < 2), (0, True))
|
1248 |
+
assert integrate(f1*f2, (x, 0, 3)) == 6
|
1249 |
+
|
1250 |
+
y = symbols("y", positive=True)
|
1251 |
+
a, b, c, x, z = symbols("a,b,c,x,z", real=True)
|
1252 |
+
I = Integral(Piecewise(
|
1253 |
+
(0, (x >= y) | (x < 0) | (b > c)),
|
1254 |
+
(a, True)), (x, 0, z))
|
1255 |
+
ans = I.doit()
|
1256 |
+
assert ans == Piecewise((0, b > c), (a*Min(y, z) - a*Min(0, z), True))
|
1257 |
+
for cond in (True, False):
|
1258 |
+
for yy in range(1, 3):
|
1259 |
+
for zz in range(-yy, 0, yy):
|
1260 |
+
reps = [(b > c, cond), (y, yy), (z, zz)]
|
1261 |
+
assert ans.subs(reps) == I.subs(reps).doit()
|
1262 |
+
|
1263 |
+
|
1264 |
+
def test_unevaluated_integrals():
|
1265 |
+
f = Function('f')
|
1266 |
+
p = Piecewise((1, Eq(f(x) - 1, 0)), (2, x - 10 < 0), (0, True))
|
1267 |
+
assert p.integrate(x) == Integral(p, x)
|
1268 |
+
assert p.integrate((x, 0, 5)) == Integral(p, (x, 0, 5))
|
1269 |
+
# test it by replacing f(x) with x%2 which will not
|
1270 |
+
# affect the answer: the integrand is essentially 2 over
|
1271 |
+
# the domain of integration
|
1272 |
+
assert Integral(p, (x, 0, 5)).subs(f(x), x%2).n() == 10.0
|
1273 |
+
|
1274 |
+
# this is a test of using _solve_inequality when
|
1275 |
+
# solve_univariate_inequality fails
|
1276 |
+
assert p.integrate(y) == Piecewise(
|
1277 |
+
(y, Eq(f(x), 1) | ((x < 10) & Eq(f(x), 1))),
|
1278 |
+
(2*y, (x > -oo) & (x < 10)), (0, True))
|
1279 |
+
|
1280 |
+
|
1281 |
+
def test_conditions_as_alternate_booleans():
|
1282 |
+
a, b, c = symbols('a:c')
|
1283 |
+
assert Piecewise((x, Piecewise((y < 1, x > 0), (y > 1, True)))
|
1284 |
+
) == Piecewise((x, ITE(x > 0, y < 1, y > 1)))
|
1285 |
+
|
1286 |
+
|
1287 |
+
def test_Piecewise_rewrite_as_ITE():
|
1288 |
+
a, b, c, d = symbols('a:d')
|
1289 |
+
|
1290 |
+
def _ITE(*args):
|
1291 |
+
return Piecewise(*args).rewrite(ITE)
|
1292 |
+
|
1293 |
+
assert _ITE((a, x < 1), (b, x >= 1)) == ITE(x < 1, a, b)
|
1294 |
+
assert _ITE((a, x < 1), (b, x < oo)) == ITE(x < 1, a, b)
|
1295 |
+
assert _ITE((a, x < 1), (b, Or(y < 1, x < oo)), (c, y > 0)
|
1296 |
+
) == ITE(x < 1, a, b)
|
1297 |
+
assert _ITE((a, x < 1), (b, True)) == ITE(x < 1, a, b)
|
1298 |
+
assert _ITE((a, x < 1), (b, x < 2), (c, True)
|
1299 |
+
) == ITE(x < 1, a, ITE(x < 2, b, c))
|
1300 |
+
assert _ITE((a, x < 1), (b, y < 2), (c, True)
|
1301 |
+
) == ITE(x < 1, a, ITE(y < 2, b, c))
|
1302 |
+
assert _ITE((a, x < 1), (b, x < oo), (c, y < 1)
|
1303 |
+
) == ITE(x < 1, a, b)
|
1304 |
+
assert _ITE((a, x < 1), (c, y < 1), (b, x < oo), (d, True)
|
1305 |
+
) == ITE(x < 1, a, ITE(y < 1, c, b))
|
1306 |
+
assert _ITE((a, x < 0), (b, Or(x < oo, y < 1))
|
1307 |
+
) == ITE(x < 0, a, b)
|
1308 |
+
raises(TypeError, lambda: _ITE((x + 1, x < 1), (x, True)))
|
1309 |
+
# if `a` in the following were replaced with y then the coverage
|
1310 |
+
# is complete but something other than as_set would need to be
|
1311 |
+
# used to detect this
|
1312 |
+
raises(NotImplementedError, lambda: _ITE((x, x < y), (y, x >= a)))
|
1313 |
+
raises(ValueError, lambda: _ITE((a, x < 2), (b, x > 3)))
|
1314 |
+
|
1315 |
+
|
1316 |
+
def test_issue_14052():
|
1317 |
+
assert integrate(abs(sin(x)), (x, 0, 2*pi)) == 4
|
1318 |
+
|
1319 |
+
|
1320 |
+
def test_issue_14240():
|
1321 |
+
assert piecewise_fold(
|
1322 |
+
Piecewise((1, a), (2, b), (4, True)) +
|
1323 |
+
Piecewise((8, a), (16, True))
|
1324 |
+
) == Piecewise((9, a), (18, b), (20, True))
|
1325 |
+
assert piecewise_fold(
|
1326 |
+
Piecewise((2, a), (3, b), (5, True)) *
|
1327 |
+
Piecewise((7, a), (11, True))
|
1328 |
+
) == Piecewise((14, a), (33, b), (55, True))
|
1329 |
+
# these will hang if naive folding is used
|
1330 |
+
assert piecewise_fold(Add(*[
|
1331 |
+
Piecewise((i, a), (0, True)) for i in range(40)])
|
1332 |
+
) == Piecewise((780, a), (0, True))
|
1333 |
+
assert piecewise_fold(Mul(*[
|
1334 |
+
Piecewise((i, a), (0, True)) for i in range(1, 41)])
|
1335 |
+
) == Piecewise((factorial(40), a), (0, True))
|
1336 |
+
|
1337 |
+
|
1338 |
+
def test_issue_14787():
|
1339 |
+
x = Symbol('x')
|
1340 |
+
f = Piecewise((x, x < 1), ((S(58) / 7), True))
|
1341 |
+
assert str(f.evalf()) == "Piecewise((x, x < 1), (8.28571428571429, True))"
|
1342 |
+
|
1343 |
+
def test_issue_21481():
|
1344 |
+
b, e = symbols('b e')
|
1345 |
+
C = Piecewise(
|
1346 |
+
(2,
|
1347 |
+
((b > 1) & (e > 0)) |
|
1348 |
+
((b > 0) & (b < 1) & (e < 0)) |
|
1349 |
+
((e >= 2) & (b < -1) & Eq(Mod(e, 2), 0)) |
|
1350 |
+
((e <= -2) & (b > -1) & (b < 0) & Eq(Mod(e, 2), 0))),
|
1351 |
+
(S.Half,
|
1352 |
+
((b > 1) & (e < 0)) |
|
1353 |
+
((b > 0) & (e > 0) & (b < 1)) |
|
1354 |
+
((e <= -2) & (b < -1) & Eq(Mod(e, 2), 0)) |
|
1355 |
+
((e >= 2) & (b > -1) & (b < 0) & Eq(Mod(e, 2), 0))),
|
1356 |
+
(-S.Half,
|
1357 |
+
Eq(Mod(e, 2), 1) &
|
1358 |
+
(((e <= -1) & (b < -1)) | ((e >= 1) & (b > -1) & (b < 0)))),
|
1359 |
+
(-2,
|
1360 |
+
((e >= 1) & (b < -1) & Eq(Mod(e, 2), 1)) |
|
1361 |
+
((e <= -1) & (b > -1) & (b < 0) & Eq(Mod(e, 2), 1)))
|
1362 |
+
)
|
1363 |
+
A = Piecewise(
|
1364 |
+
(1, Eq(b, 1) | Eq(e, 0) | (Eq(b, -1) & Eq(Mod(e, 2), 0))),
|
1365 |
+
(0, Eq(b, 0) & (e > 0)),
|
1366 |
+
(-1, Eq(b, -1) & Eq(Mod(e, 2), 1)),
|
1367 |
+
(C, Eq(im(b), 0) & Eq(im(e), 0))
|
1368 |
+
)
|
1369 |
+
|
1370 |
+
B = piecewise_fold(A)
|
1371 |
+
sa = A.simplify()
|
1372 |
+
sb = B.simplify()
|
1373 |
+
v = (-2, -1, -S.Half, 0, S.Half, 1, 2)
|
1374 |
+
for i in v:
|
1375 |
+
for j in v:
|
1376 |
+
r = {b:i, e:j}
|
1377 |
+
ok = [k.xreplace(r) for k in (A, B, sa, sb)]
|
1378 |
+
assert len(set(ok)) == 1
|
1379 |
+
|
1380 |
+
|
1381 |
+
def test_issue_8458():
|
1382 |
+
x, y = symbols('x y')
|
1383 |
+
# Original issue
|
1384 |
+
p1 = Piecewise((0, Eq(x, 0)), (sin(x), True))
|
1385 |
+
assert p1.simplify() == sin(x)
|
1386 |
+
# Slightly larger variant
|
1387 |
+
p2 = Piecewise((x, Eq(x, 0)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True))
|
1388 |
+
assert p2.simplify() == sin(x)
|
1389 |
+
# Test for problem highlighted during review
|
1390 |
+
p3 = Piecewise((x+1, Eq(x, -1)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True))
|
1391 |
+
assert p3.simplify() == Piecewise((0, Eq(x, -1)), (sin(x), True))
|
1392 |
+
|
1393 |
+
|
1394 |
+
def test_issue_16417():
|
1395 |
+
z = Symbol('z')
|
1396 |
+
assert unchanged(Piecewise, (1, Or(Eq(im(z), 0), Gt(re(z), 0))), (2, True))
|
1397 |
+
|
1398 |
+
x = Symbol('x')
|
1399 |
+
assert unchanged(Piecewise, (S.Pi, re(x) < 0),
|
1400 |
+
(0, Or(re(x) > 0, Ne(im(x), 0))),
|
1401 |
+
(S.NaN, True))
|
1402 |
+
r = Symbol('r', real=True)
|
1403 |
+
p = Piecewise((S.Pi, re(r) < 0),
|
1404 |
+
(0, Or(re(r) > 0, Ne(im(r), 0))),
|
1405 |
+
(S.NaN, True))
|
1406 |
+
assert p == Piecewise((S.Pi, r < 0),
|
1407 |
+
(0, r > 0),
|
1408 |
+
(S.NaN, True), evaluate=False)
|
1409 |
+
# Does not work since imaginary != 0...
|
1410 |
+
#i = Symbol('i', imaginary=True)
|
1411 |
+
#p = Piecewise((S.Pi, re(i) < 0),
|
1412 |
+
# (0, Or(re(i) > 0, Ne(im(i), 0))),
|
1413 |
+
# (S.NaN, True))
|
1414 |
+
#assert p == Piecewise((0, Ne(im(i), 0)),
|
1415 |
+
# (S.NaN, True), evaluate=False)
|
1416 |
+
i = I*r
|
1417 |
+
p = Piecewise((S.Pi, re(i) < 0),
|
1418 |
+
(0, Or(re(i) > 0, Ne(im(i), 0))),
|
1419 |
+
(S.NaN, True))
|
1420 |
+
assert p == Piecewise((0, Ne(im(i), 0)),
|
1421 |
+
(S.NaN, True), evaluate=False)
|
1422 |
+
assert p == Piecewise((0, Ne(r, 0)),
|
1423 |
+
(S.NaN, True), evaluate=False)
|
1424 |
+
|
1425 |
+
|
1426 |
+
def test_eval_rewrite_as_KroneckerDelta():
|
1427 |
+
x, y, z, n, t, m = symbols('x y z n t m')
|
1428 |
+
K = KroneckerDelta
|
1429 |
+
f = lambda p: expand(p.rewrite(K))
|
1430 |
+
|
1431 |
+
p1 = Piecewise((0, Eq(x, y)), (1, True))
|
1432 |
+
assert f(p1) == 1 - K(x, y)
|
1433 |
+
|
1434 |
+
p2 = Piecewise((x, Eq(y,0)), (z, Eq(t,0)), (n, True))
|
1435 |
+
assert f(p2) == n*K(0, t)*K(0, y) - n*K(0, t) - n*K(0, y) + n + \
|
1436 |
+
x*K(0, y) - z*K(0, t)*K(0, y) + z*K(0, t)
|
1437 |
+
|
1438 |
+
p3 = Piecewise((1, Ne(x, y)), (0, True))
|
1439 |
+
assert f(p3) == 1 - K(x, y)
|
1440 |
+
|
1441 |
+
p4 = Piecewise((1, Eq(x, 3)), (4, True), (5, True))
|
1442 |
+
assert f(p4) == 4 - 3*K(3, x)
|
1443 |
+
|
1444 |
+
p5 = Piecewise((3, Ne(x, 2)), (4, Eq(y, 2)), (5, True))
|
1445 |
+
assert f(p5) == -K(2, x)*K(2, y) + 2*K(2, x) + 3
|
1446 |
+
|
1447 |
+
p6 = Piecewise((0, Ne(x, 1) & Ne(y, 4)), (1, True))
|
1448 |
+
assert f(p6) == -K(1, x)*K(4, y) + K(1, x) + K(4, y)
|
1449 |
+
|
1450 |
+
p7 = Piecewise((2, Eq(y, 3) & Ne(x, 2)), (1, True))
|
1451 |
+
assert f(p7) == -K(2, x)*K(3, y) + K(3, y) + 1
|
1452 |
+
|
1453 |
+
p8 = Piecewise((4, Eq(x, 3) & Ne(y, 2)), (1, True))
|
1454 |
+
assert f(p8) == -3*K(2, y)*K(3, x) + 3*K(3, x) + 1
|
1455 |
+
|
1456 |
+
p9 = Piecewise((6, Eq(x, 4) & Eq(y, 1)), (1, True))
|
1457 |
+
assert f(p9) == 5 * K(1, y) * K(4, x) + 1
|
1458 |
+
|
1459 |
+
p10 = Piecewise((4, Ne(x, -4) | Ne(y, 1)), (1, True))
|
1460 |
+
assert f(p10) == -3 * K(-4, x) * K(1, y) + 4
|
1461 |
+
|
1462 |
+
p11 = Piecewise((1, Eq(y, 2) | Ne(x, -3)), (2, True))
|
1463 |
+
assert f(p11) == -K(-3, x)*K(2, y) + K(-3, x) + 1
|
1464 |
+
|
1465 |
+
p12 = Piecewise((-1, Eq(x, 1) | Ne(y, 3)), (1, True))
|
1466 |
+
assert f(p12) == -2*K(1, x)*K(3, y) + 2*K(3, y) - 1
|
1467 |
+
|
1468 |
+
p13 = Piecewise((3, Eq(x, 2) | Eq(y, 4)), (1, True))
|
1469 |
+
assert f(p13) == -2*K(2, x)*K(4, y) + 2*K(2, x) + 2*K(4, y) + 1
|
1470 |
+
|
1471 |
+
p14 = Piecewise((1, Ne(x, 0) | Ne(y, 1)), (3, True))
|
1472 |
+
assert f(p14) == 2 * K(0, x) * K(1, y) + 1
|
1473 |
+
|
1474 |
+
p15 = Piecewise((2, Eq(x, 3) | Ne(y, 2)), (3, Eq(x, 4) & Eq(y, 5)), (1, True))
|
1475 |
+
assert f(p15) == -2*K(2, y)*K(3, x)*K(4, x)*K(5, y) + K(2, y)*K(3, x) + \
|
1476 |
+
2*K(2, y)*K(4, x)*K(5, y) - K(2, y) + 2
|
1477 |
+
|
1478 |
+
p16 = Piecewise((0, Ne(m, n)), (1, True))*Piecewise((0, Ne(n, t)), (1, True))\
|
1479 |
+
*Piecewise((0, Ne(n, x)), (1, True)) - Piecewise((0, Ne(t, x)), (1, True))
|
1480 |
+
assert f(p16) == K(m, n)*K(n, t)*K(n, x) - K(t, x)
|
1481 |
+
|
1482 |
+
p17 = Piecewise((0, Ne(t, x) & (Ne(m, n) | Ne(n, t) | Ne(n, x))),
|
1483 |
+
(1, Ne(t, x)), (-1, Ne(m, n) | Ne(n, t) | Ne(n, x)), (0, True))
|
1484 |
+
assert f(p17) == K(m, n)*K(n, t)*K(n, x) - K(t, x)
|
1485 |
+
|
1486 |
+
p18 = Piecewise((-4, Eq(y, 1) | (Eq(x, -5) & Eq(x, z))), (4, True))
|
1487 |
+
assert f(p18) == 8*K(-5, x)*K(1, y)*K(x, z) - 8*K(-5, x)*K(x, z) - 8*K(1, y) + 4
|
1488 |
+
|
1489 |
+
p19 = Piecewise((0, x > 2), (1, True))
|
1490 |
+
assert f(p19) == p19
|
1491 |
+
|
1492 |
+
p20 = Piecewise((0, And(x < 2, x > -5)), (1, True))
|
1493 |
+
assert f(p20) == p20
|
1494 |
+
|
1495 |
+
p21 = Piecewise((0, Or(x > 1, x < 0)), (1, True))
|
1496 |
+
assert f(p21) == p21
|
1497 |
+
|
1498 |
+
p22 = Piecewise((0, ~((Eq(y, -1) | Ne(x, 0)) & (Ne(x, 1) | Ne(y, -1)))), (1, True))
|
1499 |
+
assert f(p22) == K(-1, y)*K(0, x) - K(-1, y)*K(1, x) - K(0, x) + 1
|
1500 |
+
|
1501 |
+
|
1502 |
+
@slow
|
1503 |
+
def test_identical_conds_issue():
|
1504 |
+
from sympy.stats import Uniform, density
|
1505 |
+
u1 = Uniform('u1', 0, 1)
|
1506 |
+
u2 = Uniform('u2', 0, 1)
|
1507 |
+
# Result is quite big, so not really important here (and should ideally be
|
1508 |
+
# simpler). Should not give an exception though.
|
1509 |
+
density(u1 + u2)
|
1510 |
+
|
1511 |
+
|
1512 |
+
def test_issue_7370():
|
1513 |
+
f = Piecewise((1, x <= 2400))
|
1514 |
+
v = integrate(f, (x, 0, Float("252.4", 30)))
|
1515 |
+
assert str(v) == '252.400000000000000000000000000'
|
1516 |
+
|
1517 |
+
|
1518 |
+
def test_issue_14933():
|
1519 |
+
x = Symbol('x')
|
1520 |
+
y = Symbol('y')
|
1521 |
+
|
1522 |
+
inp = MatrixSymbol('inp', 1, 1)
|
1523 |
+
rep_dict = {y: inp[0, 0], x: inp[0, 0]}
|
1524 |
+
|
1525 |
+
p = Piecewise((1, ITE(y > 0, x < 0, True)))
|
1526 |
+
assert p.xreplace(rep_dict) == Piecewise((1, ITE(inp[0, 0] > 0, inp[0, 0] < 0, True)))
|
1527 |
+
|
1528 |
+
|
1529 |
+
def test_issue_16715():
|
1530 |
+
raises(NotImplementedError, lambda: Piecewise((x, x<0), (0, y>1)).as_expr_set_pairs())
|
1531 |
+
|
1532 |
+
|
1533 |
+
def test_issue_20360():
|
1534 |
+
t, tau = symbols("t tau", real=True)
|
1535 |
+
n = symbols("n", integer=True)
|
1536 |
+
lam = pi * (n - S.Half)
|
1537 |
+
eq = integrate(exp(lam * tau), (tau, 0, t))
|
1538 |
+
assert eq.simplify() == (2*exp(pi*t*(2*n - 1)/2) - 2)/(pi*(2*n - 1))
|
1539 |
+
|
1540 |
+
|
1541 |
+
def test_piecewise_eval():
|
1542 |
+
# XXX these tests might need modification if this
|
1543 |
+
# simplification is moved out of eval and into
|
1544 |
+
# boolalg or Piecewise simplification functions
|
1545 |
+
f = lambda x: x.args[0].cond
|
1546 |
+
# unsimplified
|
1547 |
+
assert f(Piecewise((x, (x > -oo) & (x < 3)))
|
1548 |
+
) == ((x > -oo) & (x < 3))
|
1549 |
+
assert f(Piecewise((x, (x > -oo) & (x < oo)))
|
1550 |
+
) == ((x > -oo) & (x < oo))
|
1551 |
+
assert f(Piecewise((x, (x > -3) & (x < 3)))
|
1552 |
+
) == ((x > -3) & (x < 3))
|
1553 |
+
assert f(Piecewise((x, (x > -3) & (x < oo)))
|
1554 |
+
) == ((x > -3) & (x < oo))
|
1555 |
+
assert f(Piecewise((x, (x <= 3) & (x > -oo)))
|
1556 |
+
) == ((x <= 3) & (x > -oo))
|
1557 |
+
assert f(Piecewise((x, (x <= 3) & (x > -3)))
|
1558 |
+
) == ((x <= 3) & (x > -3))
|
1559 |
+
assert f(Piecewise((x, (x >= -3) & (x < 3)))
|
1560 |
+
) == ((x >= -3) & (x < 3))
|
1561 |
+
assert f(Piecewise((x, (x >= -3) & (x < oo)))
|
1562 |
+
) == ((x >= -3) & (x < oo))
|
1563 |
+
assert f(Piecewise((x, (x >= -3) & (x <= 3)))
|
1564 |
+
) == ((x >= -3) & (x <= 3))
|
1565 |
+
# could simplify by keeping only the first
|
1566 |
+
# arg of result
|
1567 |
+
assert f(Piecewise((x, (x <= oo) & (x > -oo)))
|
1568 |
+
) == (x > -oo) & (x <= oo)
|
1569 |
+
assert f(Piecewise((x, (x <= oo) & (x > -3)))
|
1570 |
+
) == (x > -3) & (x <= oo)
|
1571 |
+
assert f(Piecewise((x, (x >= -oo) & (x < 3)))
|
1572 |
+
) == (x < 3) & (x >= -oo)
|
1573 |
+
assert f(Piecewise((x, (x >= -oo) & (x < oo)))
|
1574 |
+
) == (x < oo) & (x >= -oo)
|
1575 |
+
assert f(Piecewise((x, (x >= -oo) & (x <= 3)))
|
1576 |
+
) == (x <= 3) & (x >= -oo)
|
1577 |
+
assert f(Piecewise((x, (x >= -oo) & (x <= oo)))
|
1578 |
+
) == (x <= oo) & (x >= -oo) # but cannot be True unless x is real
|
1579 |
+
assert f(Piecewise((x, (x >= -3) & (x <= oo)))
|
1580 |
+
) == (x >= -3) & (x <= oo)
|
1581 |
+
assert f(Piecewise((x, (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1)))
|
1582 |
+
) == (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1)
|
1583 |
+
|
1584 |
+
|
1585 |
+
def test_issue_22533():
|
1586 |
+
x = Symbol('x', real=True)
|
1587 |
+
f = Piecewise((-1 / x, x <= 0), (1 / x, True))
|
1588 |
+
assert integrate(f, x) == Piecewise((-log(x), x <= 0), (log(x), True))
|
1589 |
+
|
1590 |
+
|
1591 |
+
def test_issue_24072():
|
1592 |
+
assert Piecewise((1, x > 1), (2, x <= 1), (3, x <= 1)
|
1593 |
+
) == Piecewise((1, x > 1), (2, True))
|
1594 |
+
|
1595 |
+
|
1596 |
+
def test_piecewise__eval_is_meromorphic():
|
1597 |
+
""" Issue 24127: Tests eval_is_meromorphic auxiliary method """
|
1598 |
+
x = symbols('x', real=True)
|
1599 |
+
f = Piecewise((1, x < 0), (sqrt(1 - x), True))
|
1600 |
+
assert f.is_meromorphic(x, I) is None
|
1601 |
+
assert f.is_meromorphic(x, -1) == True
|
1602 |
+
assert f.is_meromorphic(x, 0) == None
|
1603 |
+
assert f.is_meromorphic(x, 1) == False
|
1604 |
+
assert f.is_meromorphic(x, 2) == True
|
1605 |
+
assert f.is_meromorphic(x, Symbol('a')) == None
|
1606 |
+
assert f.is_meromorphic(x, Symbol('a', real=True)) == None
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_trigonometric.py
ADDED
@@ -0,0 +1,2162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
2 |
+
from sympy.core.add import Add
|
3 |
+
from sympy.core.function import (Lambda, diff)
|
4 |
+
from sympy.core.mod import Mod
|
5 |
+
from sympy.core.mul import Mul
|
6 |
+
from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
|
7 |
+
from sympy.core.power import Pow
|
8 |
+
from sympy.core.singleton import S
|
9 |
+
from sympy.core.symbol import (Symbol, symbols)
|
10 |
+
from sympy.functions.elementary.complexes import (arg, conjugate, im, re)
|
11 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
12 |
+
from sympy.functions.elementary.hyperbolic import (acoth, asinh, atanh, cosh, coth, sinh, tanh)
|
13 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
14 |
+
from sympy.functions.elementary.trigonometric import (acos, acot, acsc, asec, asin, atan, atan2,
|
15 |
+
cos, cot, csc, sec, sin, sinc, tan)
|
16 |
+
from sympy.functions.special.bessel import (besselj, jn)
|
17 |
+
from sympy.functions.special.delta_functions import Heaviside
|
18 |
+
from sympy.matrices.dense import Matrix
|
19 |
+
from sympy.polys.polytools import (cancel, gcd)
|
20 |
+
from sympy.series.limits import limit
|
21 |
+
from sympy.series.order import O
|
22 |
+
from sympy.series.series import series
|
23 |
+
from sympy.sets.fancysets import ImageSet
|
24 |
+
from sympy.sets.sets import (FiniteSet, Interval)
|
25 |
+
from sympy.simplify.simplify import simplify
|
26 |
+
from sympy.core.expr import unchanged
|
27 |
+
from sympy.core.function import ArgumentIndexError
|
28 |
+
from sympy.core.relational import Ne, Eq
|
29 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
30 |
+
from sympy.sets.setexpr import SetExpr
|
31 |
+
from sympy.testing.pytest import XFAIL, slow, raises
|
32 |
+
|
33 |
+
|
34 |
+
x, y, z = symbols('x y z')
|
35 |
+
r = Symbol('r', real=True)
|
36 |
+
k, m = symbols('k m', integer=True)
|
37 |
+
p = Symbol('p', positive=True)
|
38 |
+
n = Symbol('n', negative=True)
|
39 |
+
np = Symbol('p', nonpositive=True)
|
40 |
+
nn = Symbol('n', nonnegative=True)
|
41 |
+
nz = Symbol('nz', nonzero=True)
|
42 |
+
ep = Symbol('ep', extended_positive=True)
|
43 |
+
en = Symbol('en', extended_negative=True)
|
44 |
+
enp = Symbol('ep', extended_nonpositive=True)
|
45 |
+
enn = Symbol('en', extended_nonnegative=True)
|
46 |
+
enz = Symbol('enz', extended_nonzero=True)
|
47 |
+
a = Symbol('a', algebraic=True)
|
48 |
+
na = Symbol('na', nonzero=True, algebraic=True)
|
49 |
+
|
50 |
+
|
51 |
+
def test_sin():
|
52 |
+
x, y = symbols('x y')
|
53 |
+
z = symbols('z', imaginary=True)
|
54 |
+
|
55 |
+
assert sin.nargs == FiniteSet(1)
|
56 |
+
assert sin(nan) is nan
|
57 |
+
assert sin(zoo) is nan
|
58 |
+
|
59 |
+
assert sin(oo) == AccumBounds(-1, 1)
|
60 |
+
assert sin(oo) - sin(oo) == AccumBounds(-2, 2)
|
61 |
+
assert sin(oo*I) == oo*I
|
62 |
+
assert sin(-oo*I) == -oo*I
|
63 |
+
assert 0*sin(oo) is S.Zero
|
64 |
+
assert 0/sin(oo) is S.Zero
|
65 |
+
assert 0 + sin(oo) == AccumBounds(-1, 1)
|
66 |
+
assert 5 + sin(oo) == AccumBounds(4, 6)
|
67 |
+
|
68 |
+
assert sin(0) == 0
|
69 |
+
|
70 |
+
assert sin(z*I) == I*sinh(z)
|
71 |
+
assert sin(asin(x)) == x
|
72 |
+
assert sin(atan(x)) == x / sqrt(1 + x**2)
|
73 |
+
assert sin(acos(x)) == sqrt(1 - x**2)
|
74 |
+
assert sin(acot(x)) == 1 / (sqrt(1 + 1 / x**2) * x)
|
75 |
+
assert sin(acsc(x)) == 1 / x
|
76 |
+
assert sin(asec(x)) == sqrt(1 - 1 / x**2)
|
77 |
+
assert sin(atan2(y, x)) == y / sqrt(x**2 + y**2)
|
78 |
+
|
79 |
+
assert sin(pi*I) == sinh(pi)*I
|
80 |
+
assert sin(-pi*I) == -sinh(pi)*I
|
81 |
+
assert sin(-2*I) == -sinh(2)*I
|
82 |
+
|
83 |
+
assert sin(pi) == 0
|
84 |
+
assert sin(-pi) == 0
|
85 |
+
assert sin(2*pi) == 0
|
86 |
+
assert sin(-2*pi) == 0
|
87 |
+
assert sin(-3*10**73*pi) == 0
|
88 |
+
assert sin(7*10**103*pi) == 0
|
89 |
+
|
90 |
+
assert sin(pi/2) == 1
|
91 |
+
assert sin(-pi/2) == -1
|
92 |
+
assert sin(pi*Rational(5, 2)) == 1
|
93 |
+
assert sin(pi*Rational(7, 2)) == -1
|
94 |
+
|
95 |
+
ne = symbols('ne', integer=True, even=False)
|
96 |
+
e = symbols('e', even=True)
|
97 |
+
assert sin(pi*ne/2) == (-1)**(ne/2 - S.Half)
|
98 |
+
assert sin(pi*k/2).func == sin
|
99 |
+
assert sin(pi*e/2) == 0
|
100 |
+
assert sin(pi*k) == 0
|
101 |
+
assert sin(pi*k).subs(k, 3) == sin(pi*k/2).subs(k, 6) # issue 8298
|
102 |
+
|
103 |
+
assert sin(pi/3) == S.Half*sqrt(3)
|
104 |
+
assert sin(pi*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3)
|
105 |
+
|
106 |
+
assert sin(pi/4) == S.Half*sqrt(2)
|
107 |
+
assert sin(-pi/4) == Rational(-1, 2)*sqrt(2)
|
108 |
+
assert sin(pi*Rational(17, 4)) == S.Half*sqrt(2)
|
109 |
+
assert sin(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
|
110 |
+
|
111 |
+
assert sin(pi/6) == S.Half
|
112 |
+
assert sin(-pi/6) == Rational(-1, 2)
|
113 |
+
assert sin(pi*Rational(7, 6)) == Rational(-1, 2)
|
114 |
+
assert sin(pi*Rational(-5, 6)) == Rational(-1, 2)
|
115 |
+
|
116 |
+
assert sin(pi*Rational(1, 5)) == sqrt((5 - sqrt(5)) / 8)
|
117 |
+
assert sin(pi*Rational(2, 5)) == sqrt((5 + sqrt(5)) / 8)
|
118 |
+
assert sin(pi*Rational(3, 5)) == sin(pi*Rational(2, 5))
|
119 |
+
assert sin(pi*Rational(4, 5)) == sin(pi*Rational(1, 5))
|
120 |
+
assert sin(pi*Rational(6, 5)) == -sin(pi*Rational(1, 5))
|
121 |
+
assert sin(pi*Rational(8, 5)) == -sin(pi*Rational(2, 5))
|
122 |
+
|
123 |
+
assert sin(pi*Rational(-1273, 5)) == -sin(pi*Rational(2, 5))
|
124 |
+
|
125 |
+
assert sin(pi/8) == sqrt((2 - sqrt(2))/4)
|
126 |
+
|
127 |
+
assert sin(pi/10) == Rational(-1, 4) + sqrt(5)/4
|
128 |
+
|
129 |
+
assert sin(pi/12) == -sqrt(2)/4 + sqrt(6)/4
|
130 |
+
assert sin(pi*Rational(5, 12)) == sqrt(2)/4 + sqrt(6)/4
|
131 |
+
assert sin(pi*Rational(-7, 12)) == -sqrt(2)/4 - sqrt(6)/4
|
132 |
+
assert sin(pi*Rational(-11, 12)) == sqrt(2)/4 - sqrt(6)/4
|
133 |
+
|
134 |
+
assert sin(pi*Rational(104, 105)) == sin(pi/105)
|
135 |
+
assert sin(pi*Rational(106, 105)) == -sin(pi/105)
|
136 |
+
|
137 |
+
assert sin(pi*Rational(-104, 105)) == -sin(pi/105)
|
138 |
+
assert sin(pi*Rational(-106, 105)) == sin(pi/105)
|
139 |
+
|
140 |
+
assert sin(x*I) == sinh(x)*I
|
141 |
+
|
142 |
+
assert sin(k*pi) == 0
|
143 |
+
assert sin(17*k*pi) == 0
|
144 |
+
assert sin(2*k*pi + 4) == sin(4)
|
145 |
+
assert sin(2*k*pi + m*pi + 1) == (-1)**(m + 2*k)*sin(1)
|
146 |
+
|
147 |
+
assert sin(k*pi*I) == sinh(k*pi)*I
|
148 |
+
|
149 |
+
assert sin(r).is_real is True
|
150 |
+
|
151 |
+
assert sin(0, evaluate=False).is_algebraic
|
152 |
+
assert sin(a).is_algebraic is None
|
153 |
+
assert sin(na).is_algebraic is False
|
154 |
+
q = Symbol('q', rational=True)
|
155 |
+
assert sin(pi*q).is_algebraic
|
156 |
+
qn = Symbol('qn', rational=True, nonzero=True)
|
157 |
+
assert sin(qn).is_rational is False
|
158 |
+
assert sin(q).is_rational is None # issue 8653
|
159 |
+
|
160 |
+
assert isinstance(sin( re(x) - im(y)), sin) is True
|
161 |
+
assert isinstance(sin(-re(x) + im(y)), sin) is False
|
162 |
+
|
163 |
+
assert sin(SetExpr(Interval(0, 1))) == SetExpr(ImageSet(Lambda(x, sin(x)),
|
164 |
+
Interval(0, 1)))
|
165 |
+
|
166 |
+
for d in list(range(1, 22)) + [60, 85]:
|
167 |
+
for n in range(d*2 + 1):
|
168 |
+
x = n*pi/d
|
169 |
+
e = abs( float(sin(x)) - sin(float(x)) )
|
170 |
+
assert e < 1e-12
|
171 |
+
|
172 |
+
assert sin(0, evaluate=False).is_zero is True
|
173 |
+
assert sin(k*pi, evaluate=False).is_zero is True
|
174 |
+
|
175 |
+
assert sin(Add(1, -1, evaluate=False), evaluate=False).is_zero is True
|
176 |
+
|
177 |
+
|
178 |
+
def test_sin_cos():
|
179 |
+
for d in [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 24, 30, 40, 60, 120]: # list is not exhaustive...
|
180 |
+
for n in range(-2*d, d*2):
|
181 |
+
x = n*pi/d
|
182 |
+
assert sin(x + pi/2) == cos(x), "fails for %d*pi/%d" % (n, d)
|
183 |
+
assert sin(x - pi/2) == -cos(x), "fails for %d*pi/%d" % (n, d)
|
184 |
+
assert sin(x) == cos(x - pi/2), "fails for %d*pi/%d" % (n, d)
|
185 |
+
assert -sin(x) == cos(x + pi/2), "fails for %d*pi/%d" % (n, d)
|
186 |
+
|
187 |
+
|
188 |
+
def test_sin_series():
|
189 |
+
assert sin(x).series(x, 0, 9) == \
|
190 |
+
x - x**3/6 + x**5/120 - x**7/5040 + O(x**9)
|
191 |
+
|
192 |
+
|
193 |
+
def test_sin_rewrite():
|
194 |
+
assert sin(x).rewrite(exp) == -I*(exp(I*x) - exp(-I*x))/2
|
195 |
+
assert sin(x).rewrite(tan) == 2*tan(x/2)/(1 + tan(x/2)**2)
|
196 |
+
assert sin(x).rewrite(cot) == \
|
197 |
+
Piecewise((0, Eq(im(x), 0) & Eq(Mod(x, pi), 0)),
|
198 |
+
(2*cot(x/2)/(cot(x/2)**2 + 1), True))
|
199 |
+
assert sin(sinh(x)).rewrite(
|
200 |
+
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sinh(3)).n()
|
201 |
+
assert sin(cosh(x)).rewrite(
|
202 |
+
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cosh(3)).n()
|
203 |
+
assert sin(tanh(x)).rewrite(
|
204 |
+
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tanh(3)).n()
|
205 |
+
assert sin(coth(x)).rewrite(
|
206 |
+
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, coth(3)).n()
|
207 |
+
assert sin(sin(x)).rewrite(
|
208 |
+
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sin(3)).n()
|
209 |
+
assert sin(cos(x)).rewrite(
|
210 |
+
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cos(3)).n()
|
211 |
+
assert sin(tan(x)).rewrite(
|
212 |
+
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tan(3)).n()
|
213 |
+
assert sin(cot(x)).rewrite(
|
214 |
+
exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cot(3)).n()
|
215 |
+
assert sin(log(x)).rewrite(Pow) == I*x**-I / 2 - I*x**I /2
|
216 |
+
assert sin(x).rewrite(csc) == 1/csc(x)
|
217 |
+
assert sin(x).rewrite(cos) == cos(x - pi / 2, evaluate=False)
|
218 |
+
assert sin(x).rewrite(sec) == 1 / sec(x - pi / 2, evaluate=False)
|
219 |
+
assert sin(cos(x)).rewrite(Pow) == sin(cos(x))
|
220 |
+
|
221 |
+
|
222 |
+
def _test_extrig(f, i, e):
|
223 |
+
from sympy.core.function import expand_trig
|
224 |
+
assert unchanged(f, i)
|
225 |
+
assert expand_trig(f(i)) == f(i)
|
226 |
+
# testing directly instead of with .expand(trig=True)
|
227 |
+
# because the other expansions undo the unevaluated Mul
|
228 |
+
assert expand_trig(f(Mul(i, 1, evaluate=False))) == e
|
229 |
+
assert abs(f(i) - e).n() < 1e-10
|
230 |
+
|
231 |
+
|
232 |
+
def test_sin_expansion():
|
233 |
+
# Note: these formulas are not unique. The ones here come from the
|
234 |
+
# Chebyshev formulas.
|
235 |
+
assert sin(x + y).expand(trig=True) == sin(x)*cos(y) + cos(x)*sin(y)
|
236 |
+
assert sin(x - y).expand(trig=True) == sin(x)*cos(y) - cos(x)*sin(y)
|
237 |
+
assert sin(y - x).expand(trig=True) == cos(x)*sin(y) - sin(x)*cos(y)
|
238 |
+
assert sin(2*x).expand(trig=True) == 2*sin(x)*cos(x)
|
239 |
+
assert sin(3*x).expand(trig=True) == -4*sin(x)**3 + 3*sin(x)
|
240 |
+
assert sin(4*x).expand(trig=True) == -8*sin(x)**3*cos(x) + 4*sin(x)*cos(x)
|
241 |
+
_test_extrig(sin, 2, 2*sin(1)*cos(1))
|
242 |
+
_test_extrig(sin, 3, -4*sin(1)**3 + 3*sin(1))
|
243 |
+
|
244 |
+
|
245 |
+
def test_sin_AccumBounds():
|
246 |
+
assert sin(AccumBounds(-oo, oo)) == AccumBounds(-1, 1)
|
247 |
+
assert sin(AccumBounds(0, oo)) == AccumBounds(-1, 1)
|
248 |
+
assert sin(AccumBounds(-oo, 0)) == AccumBounds(-1, 1)
|
249 |
+
assert sin(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1)
|
250 |
+
assert sin(AccumBounds(0, S.Pi*Rational(3, 4))) == AccumBounds(0, 1)
|
251 |
+
assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(7, 4))) == AccumBounds(-1, sin(S.Pi*Rational(3, 4)))
|
252 |
+
assert sin(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(sin(S.Pi/4), sin(S.Pi/3))
|
253 |
+
assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 6))) == AccumBounds(sin(S.Pi*Rational(5, 6)), sin(S.Pi*Rational(3, 4)))
|
254 |
+
|
255 |
+
|
256 |
+
def test_sin_fdiff():
|
257 |
+
assert sin(x).fdiff() == cos(x)
|
258 |
+
raises(ArgumentIndexError, lambda: sin(x).fdiff(2))
|
259 |
+
|
260 |
+
|
261 |
+
def test_trig_symmetry():
|
262 |
+
assert sin(-x) == -sin(x)
|
263 |
+
assert cos(-x) == cos(x)
|
264 |
+
assert tan(-x) == -tan(x)
|
265 |
+
assert cot(-x) == -cot(x)
|
266 |
+
assert sin(x + pi) == -sin(x)
|
267 |
+
assert sin(x + 2*pi) == sin(x)
|
268 |
+
assert sin(x + 3*pi) == -sin(x)
|
269 |
+
assert sin(x + 4*pi) == sin(x)
|
270 |
+
assert sin(x - 5*pi) == -sin(x)
|
271 |
+
assert cos(x + pi) == -cos(x)
|
272 |
+
assert cos(x + 2*pi) == cos(x)
|
273 |
+
assert cos(x + 3*pi) == -cos(x)
|
274 |
+
assert cos(x + 4*pi) == cos(x)
|
275 |
+
assert cos(x - 5*pi) == -cos(x)
|
276 |
+
assert tan(x + pi) == tan(x)
|
277 |
+
assert tan(x - 3*pi) == tan(x)
|
278 |
+
assert cot(x + pi) == cot(x)
|
279 |
+
assert cot(x - 3*pi) == cot(x)
|
280 |
+
assert sin(pi/2 - x) == cos(x)
|
281 |
+
assert sin(pi*Rational(3, 2) - x) == -cos(x)
|
282 |
+
assert sin(pi*Rational(5, 2) - x) == cos(x)
|
283 |
+
assert cos(pi/2 - x) == sin(x)
|
284 |
+
assert cos(pi*Rational(3, 2) - x) == -sin(x)
|
285 |
+
assert cos(pi*Rational(5, 2) - x) == sin(x)
|
286 |
+
assert tan(pi/2 - x) == cot(x)
|
287 |
+
assert tan(pi*Rational(3, 2) - x) == cot(x)
|
288 |
+
assert tan(pi*Rational(5, 2) - x) == cot(x)
|
289 |
+
assert cot(pi/2 - x) == tan(x)
|
290 |
+
assert cot(pi*Rational(3, 2) - x) == tan(x)
|
291 |
+
assert cot(pi*Rational(5, 2) - x) == tan(x)
|
292 |
+
assert sin(pi/2 + x) == cos(x)
|
293 |
+
assert cos(pi/2 + x) == -sin(x)
|
294 |
+
assert tan(pi/2 + x) == -cot(x)
|
295 |
+
assert cot(pi/2 + x) == -tan(x)
|
296 |
+
|
297 |
+
|
298 |
+
def test_cos():
|
299 |
+
x, y = symbols('x y')
|
300 |
+
|
301 |
+
assert cos.nargs == FiniteSet(1)
|
302 |
+
assert cos(nan) is nan
|
303 |
+
|
304 |
+
assert cos(oo) == AccumBounds(-1, 1)
|
305 |
+
assert cos(oo) - cos(oo) == AccumBounds(-2, 2)
|
306 |
+
assert cos(oo*I) is oo
|
307 |
+
assert cos(-oo*I) is oo
|
308 |
+
assert cos(zoo) is nan
|
309 |
+
|
310 |
+
assert cos(0) == 1
|
311 |
+
|
312 |
+
assert cos(acos(x)) == x
|
313 |
+
assert cos(atan(x)) == 1 / sqrt(1 + x**2)
|
314 |
+
assert cos(asin(x)) == sqrt(1 - x**2)
|
315 |
+
assert cos(acot(x)) == 1 / sqrt(1 + 1 / x**2)
|
316 |
+
assert cos(acsc(x)) == sqrt(1 - 1 / x**2)
|
317 |
+
assert cos(asec(x)) == 1 / x
|
318 |
+
assert cos(atan2(y, x)) == x / sqrt(x**2 + y**2)
|
319 |
+
|
320 |
+
assert cos(pi*I) == cosh(pi)
|
321 |
+
assert cos(-pi*I) == cosh(pi)
|
322 |
+
assert cos(-2*I) == cosh(2)
|
323 |
+
|
324 |
+
assert cos(pi/2) == 0
|
325 |
+
assert cos(-pi/2) == 0
|
326 |
+
assert cos(pi/2) == 0
|
327 |
+
assert cos(-pi/2) == 0
|
328 |
+
assert cos((-3*10**73 + 1)*pi/2) == 0
|
329 |
+
assert cos((7*10**103 + 1)*pi/2) == 0
|
330 |
+
|
331 |
+
n = symbols('n', integer=True, even=False)
|
332 |
+
e = symbols('e', even=True)
|
333 |
+
assert cos(pi*n/2) == 0
|
334 |
+
assert cos(pi*e/2) == (-1)**(e/2)
|
335 |
+
|
336 |
+
assert cos(pi) == -1
|
337 |
+
assert cos(-pi) == -1
|
338 |
+
assert cos(2*pi) == 1
|
339 |
+
assert cos(5*pi) == -1
|
340 |
+
assert cos(8*pi) == 1
|
341 |
+
|
342 |
+
assert cos(pi/3) == S.Half
|
343 |
+
assert cos(pi*Rational(-2, 3)) == Rational(-1, 2)
|
344 |
+
|
345 |
+
assert cos(pi/4) == S.Half*sqrt(2)
|
346 |
+
assert cos(-pi/4) == S.Half*sqrt(2)
|
347 |
+
assert cos(pi*Rational(11, 4)) == Rational(-1, 2)*sqrt(2)
|
348 |
+
assert cos(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
|
349 |
+
|
350 |
+
assert cos(pi/6) == S.Half*sqrt(3)
|
351 |
+
assert cos(-pi/6) == S.Half*sqrt(3)
|
352 |
+
assert cos(pi*Rational(7, 6)) == Rational(-1, 2)*sqrt(3)
|
353 |
+
assert cos(pi*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3)
|
354 |
+
|
355 |
+
assert cos(pi*Rational(1, 5)) == (sqrt(5) + 1)/4
|
356 |
+
assert cos(pi*Rational(2, 5)) == (sqrt(5) - 1)/4
|
357 |
+
assert cos(pi*Rational(3, 5)) == -cos(pi*Rational(2, 5))
|
358 |
+
assert cos(pi*Rational(4, 5)) == -cos(pi*Rational(1, 5))
|
359 |
+
assert cos(pi*Rational(6, 5)) == -cos(pi*Rational(1, 5))
|
360 |
+
assert cos(pi*Rational(8, 5)) == cos(pi*Rational(2, 5))
|
361 |
+
|
362 |
+
assert cos(pi*Rational(-1273, 5)) == -cos(pi*Rational(2, 5))
|
363 |
+
|
364 |
+
assert cos(pi/8) == sqrt((2 + sqrt(2))/4)
|
365 |
+
|
366 |
+
assert cos(pi/12) == sqrt(2)/4 + sqrt(6)/4
|
367 |
+
assert cos(pi*Rational(5, 12)) == -sqrt(2)/4 + sqrt(6)/4
|
368 |
+
assert cos(pi*Rational(7, 12)) == sqrt(2)/4 - sqrt(6)/4
|
369 |
+
assert cos(pi*Rational(11, 12)) == -sqrt(2)/4 - sqrt(6)/4
|
370 |
+
|
371 |
+
assert cos(pi*Rational(104, 105)) == -cos(pi/105)
|
372 |
+
assert cos(pi*Rational(106, 105)) == -cos(pi/105)
|
373 |
+
|
374 |
+
assert cos(pi*Rational(-104, 105)) == -cos(pi/105)
|
375 |
+
assert cos(pi*Rational(-106, 105)) == -cos(pi/105)
|
376 |
+
|
377 |
+
assert cos(x*I) == cosh(x)
|
378 |
+
assert cos(k*pi*I) == cosh(k*pi)
|
379 |
+
|
380 |
+
assert cos(r).is_real is True
|
381 |
+
|
382 |
+
assert cos(0, evaluate=False).is_algebraic
|
383 |
+
assert cos(a).is_algebraic is None
|
384 |
+
assert cos(na).is_algebraic is False
|
385 |
+
q = Symbol('q', rational=True)
|
386 |
+
assert cos(pi*q).is_algebraic
|
387 |
+
assert cos(pi*Rational(2, 7)).is_algebraic
|
388 |
+
|
389 |
+
assert cos(k*pi) == (-1)**k
|
390 |
+
assert cos(2*k*pi) == 1
|
391 |
+
assert cos(0, evaluate=False).is_zero is False
|
392 |
+
assert cos(Rational(1, 2)).is_zero is False
|
393 |
+
# The following test will return None as the result, but really it should
|
394 |
+
# be True even if it is not always possible to resolve an assumptions query.
|
395 |
+
assert cos(asin(-1, evaluate=False), evaluate=False).is_zero is None
|
396 |
+
for d in list(range(1, 22)) + [60, 85]:
|
397 |
+
for n in range(2*d + 1):
|
398 |
+
x = n*pi/d
|
399 |
+
e = abs( float(cos(x)) - cos(float(x)) )
|
400 |
+
assert e < 1e-12
|
401 |
+
|
402 |
+
|
403 |
+
def test_issue_6190():
|
404 |
+
c = Float('123456789012345678901234567890.25', '')
|
405 |
+
for cls in [sin, cos, tan, cot]:
|
406 |
+
assert cls(c*pi) == cls(pi/4)
|
407 |
+
assert cls(4.125*pi) == cls(pi/8)
|
408 |
+
assert cls(4.7*pi) == cls((4.7 % 2)*pi)
|
409 |
+
|
410 |
+
|
411 |
+
def test_cos_series():
|
412 |
+
assert cos(x).series(x, 0, 9) == \
|
413 |
+
1 - x**2/2 + x**4/24 - x**6/720 + x**8/40320 + O(x**9)
|
414 |
+
|
415 |
+
|
416 |
+
def test_cos_rewrite():
|
417 |
+
assert cos(x).rewrite(exp) == exp(I*x)/2 + exp(-I*x)/2
|
418 |
+
assert cos(x).rewrite(tan) == (1 - tan(x/2)**2)/(1 + tan(x/2)**2)
|
419 |
+
assert cos(x).rewrite(cot) == \
|
420 |
+
Piecewise((1, Eq(im(x), 0) & Eq(Mod(x, 2*pi), 0)),
|
421 |
+
((cot(x/2)**2 - 1)/(cot(x/2)**2 + 1), True))
|
422 |
+
assert cos(sinh(x)).rewrite(
|
423 |
+
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sinh(3)).n()
|
424 |
+
assert cos(cosh(x)).rewrite(
|
425 |
+
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cosh(3)).n()
|
426 |
+
assert cos(tanh(x)).rewrite(
|
427 |
+
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tanh(3)).n()
|
428 |
+
assert cos(coth(x)).rewrite(
|
429 |
+
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, coth(3)).n()
|
430 |
+
assert cos(sin(x)).rewrite(
|
431 |
+
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sin(3)).n()
|
432 |
+
assert cos(cos(x)).rewrite(
|
433 |
+
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cos(3)).n()
|
434 |
+
assert cos(tan(x)).rewrite(
|
435 |
+
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tan(3)).n()
|
436 |
+
assert cos(cot(x)).rewrite(
|
437 |
+
exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cot(3)).n()
|
438 |
+
assert cos(log(x)).rewrite(Pow) == x**I/2 + x**-I/2
|
439 |
+
assert cos(x).rewrite(sec) == 1/sec(x)
|
440 |
+
assert cos(x).rewrite(sin) == sin(x + pi/2, evaluate=False)
|
441 |
+
assert cos(x).rewrite(csc) == 1/csc(-x + pi/2, evaluate=False)
|
442 |
+
assert cos(sin(x)).rewrite(Pow) == cos(sin(x))
|
443 |
+
|
444 |
+
|
445 |
+
def test_cos_expansion():
|
446 |
+
assert cos(x + y).expand(trig=True) == cos(x)*cos(y) - sin(x)*sin(y)
|
447 |
+
assert cos(x - y).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y)
|
448 |
+
assert cos(y - x).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y)
|
449 |
+
assert cos(2*x).expand(trig=True) == 2*cos(x)**2 - 1
|
450 |
+
assert cos(3*x).expand(trig=True) == 4*cos(x)**3 - 3*cos(x)
|
451 |
+
assert cos(4*x).expand(trig=True) == 8*cos(x)**4 - 8*cos(x)**2 + 1
|
452 |
+
_test_extrig(cos, 2, 2*cos(1)**2 - 1)
|
453 |
+
_test_extrig(cos, 3, 4*cos(1)**3 - 3*cos(1))
|
454 |
+
|
455 |
+
|
456 |
+
def test_cos_AccumBounds():
|
457 |
+
assert cos(AccumBounds(-oo, oo)) == AccumBounds(-1, 1)
|
458 |
+
assert cos(AccumBounds(0, oo)) == AccumBounds(-1, 1)
|
459 |
+
assert cos(AccumBounds(-oo, 0)) == AccumBounds(-1, 1)
|
460 |
+
assert cos(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1)
|
461 |
+
assert cos(AccumBounds(-S.Pi/3, S.Pi/4)) == AccumBounds(cos(-S.Pi/3), 1)
|
462 |
+
assert cos(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 4))) == AccumBounds(-1, cos(S.Pi*Rational(3, 4)))
|
463 |
+
assert cos(AccumBounds(S.Pi*Rational(5, 4), S.Pi*Rational(4, 3))) == AccumBounds(cos(S.Pi*Rational(5, 4)), cos(S.Pi*Rational(4, 3)))
|
464 |
+
assert cos(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(cos(S.Pi/3), cos(S.Pi/4))
|
465 |
+
|
466 |
+
|
467 |
+
def test_cos_fdiff():
|
468 |
+
assert cos(x).fdiff() == -sin(x)
|
469 |
+
raises(ArgumentIndexError, lambda: cos(x).fdiff(2))
|
470 |
+
|
471 |
+
|
472 |
+
def test_tan():
|
473 |
+
assert tan(nan) is nan
|
474 |
+
|
475 |
+
assert tan(zoo) is nan
|
476 |
+
assert tan(oo) == AccumBounds(-oo, oo)
|
477 |
+
assert tan(oo) - tan(oo) == AccumBounds(-oo, oo)
|
478 |
+
assert tan.nargs == FiniteSet(1)
|
479 |
+
assert tan(oo*I) == I
|
480 |
+
assert tan(-oo*I) == -I
|
481 |
+
|
482 |
+
assert tan(0) == 0
|
483 |
+
|
484 |
+
assert tan(atan(x)) == x
|
485 |
+
assert tan(asin(x)) == x / sqrt(1 - x**2)
|
486 |
+
assert tan(acos(x)) == sqrt(1 - x**2) / x
|
487 |
+
assert tan(acot(x)) == 1 / x
|
488 |
+
assert tan(acsc(x)) == 1 / (sqrt(1 - 1 / x**2) * x)
|
489 |
+
assert tan(asec(x)) == sqrt(1 - 1 / x**2) * x
|
490 |
+
assert tan(atan2(y, x)) == y/x
|
491 |
+
|
492 |
+
assert tan(pi*I) == tanh(pi)*I
|
493 |
+
assert tan(-pi*I) == -tanh(pi)*I
|
494 |
+
assert tan(-2*I) == -tanh(2)*I
|
495 |
+
|
496 |
+
assert tan(pi) == 0
|
497 |
+
assert tan(-pi) == 0
|
498 |
+
assert tan(2*pi) == 0
|
499 |
+
assert tan(-2*pi) == 0
|
500 |
+
assert tan(-3*10**73*pi) == 0
|
501 |
+
|
502 |
+
assert tan(pi/2) is zoo
|
503 |
+
assert tan(pi*Rational(3, 2)) is zoo
|
504 |
+
|
505 |
+
assert tan(pi/3) == sqrt(3)
|
506 |
+
assert tan(pi*Rational(-2, 3)) == sqrt(3)
|
507 |
+
|
508 |
+
assert tan(pi/4) is S.One
|
509 |
+
assert tan(-pi/4) is S.NegativeOne
|
510 |
+
assert tan(pi*Rational(17, 4)) is S.One
|
511 |
+
assert tan(pi*Rational(-3, 4)) is S.One
|
512 |
+
|
513 |
+
assert tan(pi/5) == sqrt(5 - 2*sqrt(5))
|
514 |
+
assert tan(pi*Rational(2, 5)) == sqrt(5 + 2*sqrt(5))
|
515 |
+
assert tan(pi*Rational(18, 5)) == -sqrt(5 + 2*sqrt(5))
|
516 |
+
assert tan(pi*Rational(-16, 5)) == -sqrt(5 - 2*sqrt(5))
|
517 |
+
|
518 |
+
assert tan(pi/6) == 1/sqrt(3)
|
519 |
+
assert tan(-pi/6) == -1/sqrt(3)
|
520 |
+
assert tan(pi*Rational(7, 6)) == 1/sqrt(3)
|
521 |
+
assert tan(pi*Rational(-5, 6)) == 1/sqrt(3)
|
522 |
+
|
523 |
+
assert tan(pi/8) == -1 + sqrt(2)
|
524 |
+
assert tan(pi*Rational(3, 8)) == 1 + sqrt(2) # issue 15959
|
525 |
+
assert tan(pi*Rational(5, 8)) == -1 - sqrt(2)
|
526 |
+
assert tan(pi*Rational(7, 8)) == 1 - sqrt(2)
|
527 |
+
|
528 |
+
assert tan(pi/10) == sqrt(1 - 2*sqrt(5)/5)
|
529 |
+
assert tan(pi*Rational(3, 10)) == sqrt(1 + 2*sqrt(5)/5)
|
530 |
+
assert tan(pi*Rational(17, 10)) == -sqrt(1 + 2*sqrt(5)/5)
|
531 |
+
assert tan(pi*Rational(-31, 10)) == -sqrt(1 - 2*sqrt(5)/5)
|
532 |
+
|
533 |
+
assert tan(pi/12) == -sqrt(3) + 2
|
534 |
+
assert tan(pi*Rational(5, 12)) == sqrt(3) + 2
|
535 |
+
assert tan(pi*Rational(7, 12)) == -sqrt(3) - 2
|
536 |
+
assert tan(pi*Rational(11, 12)) == sqrt(3) - 2
|
537 |
+
|
538 |
+
assert tan(pi/24).radsimp() == -2 - sqrt(3) + sqrt(2) + sqrt(6)
|
539 |
+
assert tan(pi*Rational(5, 24)).radsimp() == -2 + sqrt(3) - sqrt(2) + sqrt(6)
|
540 |
+
assert tan(pi*Rational(7, 24)).radsimp() == 2 - sqrt(3) - sqrt(2) + sqrt(6)
|
541 |
+
assert tan(pi*Rational(11, 24)).radsimp() == 2 + sqrt(3) + sqrt(2) + sqrt(6)
|
542 |
+
assert tan(pi*Rational(13, 24)).radsimp() == -2 - sqrt(3) - sqrt(2) - sqrt(6)
|
543 |
+
assert tan(pi*Rational(17, 24)).radsimp() == -2 + sqrt(3) + sqrt(2) - sqrt(6)
|
544 |
+
assert tan(pi*Rational(19, 24)).radsimp() == 2 - sqrt(3) + sqrt(2) - sqrt(6)
|
545 |
+
assert tan(pi*Rational(23, 24)).radsimp() == 2 + sqrt(3) - sqrt(2) - sqrt(6)
|
546 |
+
|
547 |
+
assert tan(x*I) == tanh(x)*I
|
548 |
+
|
549 |
+
assert tan(k*pi) == 0
|
550 |
+
assert tan(17*k*pi) == 0
|
551 |
+
|
552 |
+
assert tan(k*pi*I) == tanh(k*pi)*I
|
553 |
+
|
554 |
+
assert tan(r).is_real is None
|
555 |
+
assert tan(r).is_extended_real is True
|
556 |
+
|
557 |
+
assert tan(0, evaluate=False).is_algebraic
|
558 |
+
assert tan(a).is_algebraic is None
|
559 |
+
assert tan(na).is_algebraic is False
|
560 |
+
|
561 |
+
assert tan(pi*Rational(10, 7)) == tan(pi*Rational(3, 7))
|
562 |
+
assert tan(pi*Rational(11, 7)) == -tan(pi*Rational(3, 7))
|
563 |
+
assert tan(pi*Rational(-11, 7)) == tan(pi*Rational(3, 7))
|
564 |
+
|
565 |
+
assert tan(pi*Rational(15, 14)) == tan(pi/14)
|
566 |
+
assert tan(pi*Rational(-15, 14)) == -tan(pi/14)
|
567 |
+
|
568 |
+
assert tan(r).is_finite is None
|
569 |
+
assert tan(I*r).is_finite is True
|
570 |
+
|
571 |
+
# https://github.com/sympy/sympy/issues/21177
|
572 |
+
f = tan(pi*(x + S(3)/2))/(3*x)
|
573 |
+
assert f.as_leading_term(x) == -1/(3*pi*x**2)
|
574 |
+
|
575 |
+
|
576 |
+
def test_tan_series():
|
577 |
+
assert tan(x).series(x, 0, 9) == \
|
578 |
+
x + x**3/3 + 2*x**5/15 + 17*x**7/315 + O(x**9)
|
579 |
+
|
580 |
+
|
581 |
+
def test_tan_rewrite():
|
582 |
+
neg_exp, pos_exp = exp(-x*I), exp(x*I)
|
583 |
+
assert tan(x).rewrite(exp) == I*(neg_exp - pos_exp)/(neg_exp + pos_exp)
|
584 |
+
assert tan(x).rewrite(sin) == 2*sin(x)**2/sin(2*x)
|
585 |
+
assert tan(x).rewrite(cos) == cos(x - S.Pi/2, evaluate=False)/cos(x)
|
586 |
+
assert tan(x).rewrite(cot) == 1/cot(x)
|
587 |
+
assert tan(sinh(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sinh(3)).n()
|
588 |
+
assert tan(cosh(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cosh(3)).n()
|
589 |
+
assert tan(tanh(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tanh(3)).n()
|
590 |
+
assert tan(coth(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, coth(3)).n()
|
591 |
+
assert tan(sin(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sin(3)).n()
|
592 |
+
assert tan(cos(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cos(3)).n()
|
593 |
+
assert tan(tan(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tan(3)).n()
|
594 |
+
assert tan(cot(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cot(3)).n()
|
595 |
+
assert tan(log(x)).rewrite(Pow) == I*(x**-I - x**I)/(x**-I + x**I)
|
596 |
+
assert tan(x).rewrite(sec) == sec(x)/sec(x - pi/2, evaluate=False)
|
597 |
+
assert tan(x).rewrite(csc) == csc(-x + pi/2, evaluate=False)/csc(x)
|
598 |
+
assert tan(sin(x)).rewrite(Pow) == tan(sin(x))
|
599 |
+
|
600 |
+
|
601 |
+
@slow
|
602 |
+
def test_tan_rewrite_slow():
|
603 |
+
assert 0 == (cos(pi/34)*tan(pi/34) - sin(pi/34)).rewrite(pow)
|
604 |
+
assert 0 == (cos(pi/17)*tan(pi/17) - sin(pi/17)).rewrite(pow)
|
605 |
+
assert tan(pi/19).rewrite(pow) == tan(pi/19)
|
606 |
+
assert tan(pi*Rational(8, 19)).rewrite(sqrt) == tan(pi*Rational(8, 19))
|
607 |
+
assert tan(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == sqrt(sqrt(5)/8 +
|
608 |
+
Rational(5, 8))/(Rational(-1, 4) + sqrt(5)/4)
|
609 |
+
|
610 |
+
|
611 |
+
def test_tan_subs():
|
612 |
+
assert tan(x).subs(tan(x), y) == y
|
613 |
+
assert tan(x).subs(x, y) == tan(y)
|
614 |
+
assert tan(x).subs(x, S.Pi/2) is zoo
|
615 |
+
assert tan(x).subs(x, S.Pi*Rational(3, 2)) is zoo
|
616 |
+
|
617 |
+
|
618 |
+
def test_tan_expansion():
|
619 |
+
assert tan(x + y).expand(trig=True) == ((tan(x) + tan(y))/(1 - tan(x)*tan(y))).expand()
|
620 |
+
assert tan(x - y).expand(trig=True) == ((tan(x) - tan(y))/(1 + tan(x)*tan(y))).expand()
|
621 |
+
assert tan(x + y + z).expand(trig=True) == (
|
622 |
+
(tan(x) + tan(y) + tan(z) - tan(x)*tan(y)*tan(z))/
|
623 |
+
(1 - tan(x)*tan(y) - tan(x)*tan(z) - tan(y)*tan(z))).expand()
|
624 |
+
assert 0 == tan(2*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 7))])*24 - 7
|
625 |
+
assert 0 == tan(3*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*55 - 37
|
626 |
+
assert 0 == tan(4*x - pi/4).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*239 - 1
|
627 |
+
_test_extrig(tan, 2, 2*tan(1)/(1 - tan(1)**2))
|
628 |
+
_test_extrig(tan, 3, (-tan(1)**3 + 3*tan(1))/(1 - 3*tan(1)**2))
|
629 |
+
|
630 |
+
|
631 |
+
def test_tan_AccumBounds():
|
632 |
+
assert tan(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo)
|
633 |
+
assert tan(AccumBounds(S.Pi/3, S.Pi*Rational(2, 3))) == AccumBounds(-oo, oo)
|
634 |
+
assert tan(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(tan(S.Pi/6), tan(S.Pi/3))
|
635 |
+
|
636 |
+
|
637 |
+
def test_tan_fdiff():
|
638 |
+
assert tan(x).fdiff() == tan(x)**2 + 1
|
639 |
+
raises(ArgumentIndexError, lambda: tan(x).fdiff(2))
|
640 |
+
|
641 |
+
|
642 |
+
def test_cot():
|
643 |
+
assert cot(nan) is nan
|
644 |
+
|
645 |
+
assert cot.nargs == FiniteSet(1)
|
646 |
+
assert cot(oo*I) == -I
|
647 |
+
assert cot(-oo*I) == I
|
648 |
+
assert cot(zoo) is nan
|
649 |
+
|
650 |
+
assert cot(0) is zoo
|
651 |
+
assert cot(2*pi) is zoo
|
652 |
+
|
653 |
+
assert cot(acot(x)) == x
|
654 |
+
assert cot(atan(x)) == 1 / x
|
655 |
+
assert cot(asin(x)) == sqrt(1 - x**2) / x
|
656 |
+
assert cot(acos(x)) == x / sqrt(1 - x**2)
|
657 |
+
assert cot(acsc(x)) == sqrt(1 - 1 / x**2) * x
|
658 |
+
assert cot(asec(x)) == 1 / (sqrt(1 - 1 / x**2) * x)
|
659 |
+
assert cot(atan2(y, x)) == x/y
|
660 |
+
|
661 |
+
assert cot(pi*I) == -coth(pi)*I
|
662 |
+
assert cot(-pi*I) == coth(pi)*I
|
663 |
+
assert cot(-2*I) == coth(2)*I
|
664 |
+
|
665 |
+
assert cot(pi) == cot(2*pi) == cot(3*pi)
|
666 |
+
assert cot(-pi) == cot(-2*pi) == cot(-3*pi)
|
667 |
+
|
668 |
+
assert cot(pi/2) == 0
|
669 |
+
assert cot(-pi/2) == 0
|
670 |
+
assert cot(pi*Rational(5, 2)) == 0
|
671 |
+
assert cot(pi*Rational(7, 2)) == 0
|
672 |
+
|
673 |
+
assert cot(pi/3) == 1/sqrt(3)
|
674 |
+
assert cot(pi*Rational(-2, 3)) == 1/sqrt(3)
|
675 |
+
|
676 |
+
assert cot(pi/4) is S.One
|
677 |
+
assert cot(-pi/4) is S.NegativeOne
|
678 |
+
assert cot(pi*Rational(17, 4)) is S.One
|
679 |
+
assert cot(pi*Rational(-3, 4)) is S.One
|
680 |
+
|
681 |
+
assert cot(pi/6) == sqrt(3)
|
682 |
+
assert cot(-pi/6) == -sqrt(3)
|
683 |
+
assert cot(pi*Rational(7, 6)) == sqrt(3)
|
684 |
+
assert cot(pi*Rational(-5, 6)) == sqrt(3)
|
685 |
+
|
686 |
+
assert cot(pi/8) == 1 + sqrt(2)
|
687 |
+
assert cot(pi*Rational(3, 8)) == -1 + sqrt(2)
|
688 |
+
assert cot(pi*Rational(5, 8)) == 1 - sqrt(2)
|
689 |
+
assert cot(pi*Rational(7, 8)) == -1 - sqrt(2)
|
690 |
+
|
691 |
+
assert cot(pi/12) == sqrt(3) + 2
|
692 |
+
assert cot(pi*Rational(5, 12)) == -sqrt(3) + 2
|
693 |
+
assert cot(pi*Rational(7, 12)) == sqrt(3) - 2
|
694 |
+
assert cot(pi*Rational(11, 12)) == -sqrt(3) - 2
|
695 |
+
|
696 |
+
assert cot(pi/24).radsimp() == sqrt(2) + sqrt(3) + 2 + sqrt(6)
|
697 |
+
assert cot(pi*Rational(5, 24)).radsimp() == -sqrt(2) - sqrt(3) + 2 + sqrt(6)
|
698 |
+
assert cot(pi*Rational(7, 24)).radsimp() == -sqrt(2) + sqrt(3) - 2 + sqrt(6)
|
699 |
+
assert cot(pi*Rational(11, 24)).radsimp() == sqrt(2) - sqrt(3) - 2 + sqrt(6)
|
700 |
+
assert cot(pi*Rational(13, 24)).radsimp() == -sqrt(2) + sqrt(3) + 2 - sqrt(6)
|
701 |
+
assert cot(pi*Rational(17, 24)).radsimp() == sqrt(2) - sqrt(3) + 2 - sqrt(6)
|
702 |
+
assert cot(pi*Rational(19, 24)).radsimp() == sqrt(2) + sqrt(3) - 2 - sqrt(6)
|
703 |
+
assert cot(pi*Rational(23, 24)).radsimp() == -sqrt(2) - sqrt(3) - 2 - sqrt(6)
|
704 |
+
|
705 |
+
assert cot(x*I) == -coth(x)*I
|
706 |
+
assert cot(k*pi*I) == -coth(k*pi)*I
|
707 |
+
|
708 |
+
assert cot(r).is_real is None
|
709 |
+
assert cot(r).is_extended_real is True
|
710 |
+
|
711 |
+
assert cot(a).is_algebraic is None
|
712 |
+
assert cot(na).is_algebraic is False
|
713 |
+
|
714 |
+
assert cot(pi*Rational(10, 7)) == cot(pi*Rational(3, 7))
|
715 |
+
assert cot(pi*Rational(11, 7)) == -cot(pi*Rational(3, 7))
|
716 |
+
assert cot(pi*Rational(-11, 7)) == cot(pi*Rational(3, 7))
|
717 |
+
|
718 |
+
assert cot(pi*Rational(39, 34)) == cot(pi*Rational(5, 34))
|
719 |
+
assert cot(pi*Rational(-41, 34)) == -cot(pi*Rational(7, 34))
|
720 |
+
|
721 |
+
assert cot(x).is_finite is None
|
722 |
+
assert cot(r).is_finite is None
|
723 |
+
i = Symbol('i', imaginary=True)
|
724 |
+
assert cot(i).is_finite is True
|
725 |
+
|
726 |
+
assert cot(x).subs(x, 3*pi) is zoo
|
727 |
+
|
728 |
+
# https://github.com/sympy/sympy/issues/21177
|
729 |
+
f = cot(pi*(x + 4))/(3*x)
|
730 |
+
assert f.as_leading_term(x) == 1/(3*pi*x**2)
|
731 |
+
|
732 |
+
|
733 |
+
def test_tan_cot_sin_cos_evalf():
|
734 |
+
assert abs((tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15)) - 1).evalf()) < 1e-14
|
735 |
+
assert abs((cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15)) - 1).evalf()) < 1e-14
|
736 |
+
|
737 |
+
@XFAIL
|
738 |
+
def test_tan_cot_sin_cos_ratsimp():
|
739 |
+
assert 1 == (tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15))).ratsimp()
|
740 |
+
assert 1 == (cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15))).ratsimp()
|
741 |
+
|
742 |
+
|
743 |
+
def test_cot_series():
|
744 |
+
assert cot(x).series(x, 0, 9) == \
|
745 |
+
1/x - x/3 - x**3/45 - 2*x**5/945 - x**7/4725 + O(x**9)
|
746 |
+
# issue 6210
|
747 |
+
assert cot(x**4 + x**5).series(x, 0, 1) == \
|
748 |
+
x**(-4) - 1/x**3 + x**(-2) - 1/x + 1 + O(x)
|
749 |
+
assert cot(pi*(1-x)).series(x, 0, 3) == -1/(pi*x) + pi*x/3 + O(x**3)
|
750 |
+
assert cot(x).taylor_term(0, x) == 1/x
|
751 |
+
assert cot(x).taylor_term(2, x) is S.Zero
|
752 |
+
assert cot(x).taylor_term(3, x) == -x**3/45
|
753 |
+
|
754 |
+
|
755 |
+
def test_cot_rewrite():
|
756 |
+
neg_exp, pos_exp = exp(-x*I), exp(x*I)
|
757 |
+
assert cot(x).rewrite(exp) == I*(pos_exp + neg_exp)/(pos_exp - neg_exp)
|
758 |
+
assert cot(x).rewrite(sin) == sin(2*x)/(2*(sin(x)**2))
|
759 |
+
assert cot(x).rewrite(cos) == cos(x)/cos(x - pi/2, evaluate=False)
|
760 |
+
assert cot(x).rewrite(tan) == 1/tan(x)
|
761 |
+
def check(func):
|
762 |
+
z = cot(func(x)).rewrite(exp) - cot(x).rewrite(exp).subs(x, func(x))
|
763 |
+
assert z.rewrite(exp).expand() == 0
|
764 |
+
check(sinh)
|
765 |
+
check(cosh)
|
766 |
+
check(tanh)
|
767 |
+
check(coth)
|
768 |
+
check(sin)
|
769 |
+
check(cos)
|
770 |
+
check(tan)
|
771 |
+
assert cot(log(x)).rewrite(Pow) == -I*(x**-I + x**I)/(x**-I - x**I)
|
772 |
+
assert cot(x).rewrite(sec) == sec(x - pi / 2, evaluate=False) / sec(x)
|
773 |
+
assert cot(x).rewrite(csc) == csc(x) / csc(- x + pi / 2, evaluate=False)
|
774 |
+
assert cot(sin(x)).rewrite(Pow) == cot(sin(x))
|
775 |
+
|
776 |
+
|
777 |
+
@slow
|
778 |
+
def test_cot_rewrite_slow():
|
779 |
+
assert cot(pi*Rational(4, 34)).rewrite(pow).ratsimp() == \
|
780 |
+
(cos(pi*Rational(4, 34))/sin(pi*Rational(4, 34))).rewrite(pow).ratsimp()
|
781 |
+
assert cot(pi*Rational(4, 17)).rewrite(pow) == \
|
782 |
+
(cos(pi*Rational(4, 17))/sin(pi*Rational(4, 17))).rewrite(pow)
|
783 |
+
assert cot(pi/19).rewrite(pow) == cot(pi/19)
|
784 |
+
assert cot(pi/19).rewrite(sqrt) == cot(pi/19)
|
785 |
+
assert cot(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == \
|
786 |
+
(Rational(-1, 4) + sqrt(5)/4) / sqrt(sqrt(5)/8 + Rational(5, 8))
|
787 |
+
|
788 |
+
|
789 |
+
def test_cot_subs():
|
790 |
+
assert cot(x).subs(cot(x), y) == y
|
791 |
+
assert cot(x).subs(x, y) == cot(y)
|
792 |
+
assert cot(x).subs(x, 0) is zoo
|
793 |
+
assert cot(x).subs(x, S.Pi) is zoo
|
794 |
+
|
795 |
+
|
796 |
+
def test_cot_expansion():
|
797 |
+
assert cot(x + y).expand(trig=True).together() == (
|
798 |
+
(cot(x)*cot(y) - 1)/(cot(x) + cot(y)))
|
799 |
+
assert cot(x - y).expand(trig=True).together() == (
|
800 |
+
cot(x)*cot(-y) - 1)/(cot(x) + cot(-y))
|
801 |
+
assert cot(x + y + z).expand(trig=True).together() == (
|
802 |
+
(cot(x)*cot(y)*cot(z) - cot(x) - cot(y) - cot(z))/
|
803 |
+
(-1 + cot(x)*cot(y) + cot(x)*cot(z) + cot(y)*cot(z)))
|
804 |
+
assert cot(3*x).expand(trig=True).together() == (
|
805 |
+
(cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1))
|
806 |
+
assert cot(2*x).expand(trig=True) == cot(x)/2 - 1/(2*cot(x))
|
807 |
+
assert cot(3*x).expand(trig=True).together() == (
|
808 |
+
cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1)
|
809 |
+
assert cot(4*x - pi/4).expand(trig=True).cancel() == (
|
810 |
+
-tan(x)**4 + 4*tan(x)**3 + 6*tan(x)**2 - 4*tan(x) - 1
|
811 |
+
)/(tan(x)**4 + 4*tan(x)**3 - 6*tan(x)**2 - 4*tan(x) + 1)
|
812 |
+
_test_extrig(cot, 2, (-1 + cot(1)**2)/(2*cot(1)))
|
813 |
+
_test_extrig(cot, 3, (-3*cot(1) + cot(1)**3)/(-1 + 3*cot(1)**2))
|
814 |
+
|
815 |
+
|
816 |
+
def test_cot_AccumBounds():
|
817 |
+
assert cot(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo)
|
818 |
+
assert cot(AccumBounds(-S.Pi/3, S.Pi/3)) == AccumBounds(-oo, oo)
|
819 |
+
assert cot(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(cot(S.Pi/3), cot(S.Pi/6))
|
820 |
+
|
821 |
+
|
822 |
+
def test_cot_fdiff():
|
823 |
+
assert cot(x).fdiff() == -cot(x)**2 - 1
|
824 |
+
raises(ArgumentIndexError, lambda: cot(x).fdiff(2))
|
825 |
+
|
826 |
+
|
827 |
+
def test_sinc():
|
828 |
+
assert isinstance(sinc(x), sinc)
|
829 |
+
|
830 |
+
s = Symbol('s', zero=True)
|
831 |
+
assert sinc(s) is S.One
|
832 |
+
assert sinc(S.Infinity) is S.Zero
|
833 |
+
assert sinc(S.NegativeInfinity) is S.Zero
|
834 |
+
assert sinc(S.NaN) is S.NaN
|
835 |
+
assert sinc(S.ComplexInfinity) is S.NaN
|
836 |
+
|
837 |
+
n = Symbol('n', integer=True, nonzero=True)
|
838 |
+
assert sinc(n*pi) is S.Zero
|
839 |
+
assert sinc(-n*pi) is S.Zero
|
840 |
+
assert sinc(pi/2) == 2 / pi
|
841 |
+
assert sinc(-pi/2) == 2 / pi
|
842 |
+
assert sinc(pi*Rational(5, 2)) == 2 / (5*pi)
|
843 |
+
assert sinc(pi*Rational(7, 2)) == -2 / (7*pi)
|
844 |
+
|
845 |
+
assert sinc(-x) == sinc(x)
|
846 |
+
|
847 |
+
assert sinc(x).diff(x) == cos(x)/x - sin(x)/x**2
|
848 |
+
assert sinc(x).diff(x) == (sin(x)/x).diff(x)
|
849 |
+
assert sinc(x).diff(x, x) == (-sin(x) - 2*cos(x)/x + 2*sin(x)/x**2)/x
|
850 |
+
assert sinc(x).diff(x, x) == (sin(x)/x).diff(x, x)
|
851 |
+
assert limit(sinc(x).diff(x), x, 0) == 0
|
852 |
+
assert limit(sinc(x).diff(x, x), x, 0) == -S(1)/3
|
853 |
+
|
854 |
+
# https://github.com/sympy/sympy/issues/11402
|
855 |
+
#
|
856 |
+
# assert sinc(x).diff(x) == Piecewise(((x*cos(x) - sin(x)) / x**2, Ne(x, 0)), (0, True))
|
857 |
+
#
|
858 |
+
# assert sinc(x).diff(x).equals(sinc(x).rewrite(sin).diff(x))
|
859 |
+
#
|
860 |
+
# assert sinc(x).diff(x).subs(x, 0) is S.Zero
|
861 |
+
|
862 |
+
assert sinc(x).series() == 1 - x**2/6 + x**4/120 + O(x**6)
|
863 |
+
|
864 |
+
assert sinc(x).rewrite(jn) == jn(0, x)
|
865 |
+
assert sinc(x).rewrite(sin) == Piecewise((sin(x)/x, Ne(x, 0)), (1, True))
|
866 |
+
assert sinc(pi, evaluate=False).is_zero is True
|
867 |
+
assert sinc(0, evaluate=False).is_zero is False
|
868 |
+
assert sinc(n*pi, evaluate=False).is_zero is True
|
869 |
+
assert sinc(x).is_zero is None
|
870 |
+
xr = Symbol('xr', real=True, nonzero=True)
|
871 |
+
assert sinc(x).is_real is None
|
872 |
+
assert sinc(xr).is_real is True
|
873 |
+
assert sinc(I*xr).is_real is True
|
874 |
+
assert sinc(I*100).is_real is True
|
875 |
+
assert sinc(x).is_finite is None
|
876 |
+
assert sinc(xr).is_finite is True
|
877 |
+
|
878 |
+
|
879 |
+
def test_asin():
|
880 |
+
assert asin(nan) is nan
|
881 |
+
|
882 |
+
assert asin.nargs == FiniteSet(1)
|
883 |
+
assert asin(oo) == -I*oo
|
884 |
+
assert asin(-oo) == I*oo
|
885 |
+
assert asin(zoo) is zoo
|
886 |
+
|
887 |
+
# Note: asin(-x) = - asin(x)
|
888 |
+
assert asin(0) == 0
|
889 |
+
assert asin(1) == pi/2
|
890 |
+
assert asin(-1) == -pi/2
|
891 |
+
assert asin(sqrt(3)/2) == pi/3
|
892 |
+
assert asin(-sqrt(3)/2) == -pi/3
|
893 |
+
assert asin(sqrt(2)/2) == pi/4
|
894 |
+
assert asin(-sqrt(2)/2) == -pi/4
|
895 |
+
assert asin(sqrt((5 - sqrt(5))/8)) == pi/5
|
896 |
+
assert asin(-sqrt((5 - sqrt(5))/8)) == -pi/5
|
897 |
+
assert asin(S.Half) == pi/6
|
898 |
+
assert asin(Rational(-1, 2)) == -pi/6
|
899 |
+
assert asin((sqrt(2 - sqrt(2)))/2) == pi/8
|
900 |
+
assert asin(-(sqrt(2 - sqrt(2)))/2) == -pi/8
|
901 |
+
assert asin((sqrt(5) - 1)/4) == pi/10
|
902 |
+
assert asin(-(sqrt(5) - 1)/4) == -pi/10
|
903 |
+
assert asin((sqrt(3) - 1)/sqrt(2**3)) == pi/12
|
904 |
+
assert asin(-(sqrt(3) - 1)/sqrt(2**3)) == -pi/12
|
905 |
+
|
906 |
+
# check round-trip for exact values:
|
907 |
+
for d in [5, 6, 8, 10, 12]:
|
908 |
+
for n in range(-(d//2), d//2 + 1):
|
909 |
+
if gcd(n, d) == 1:
|
910 |
+
assert asin(sin(n*pi/d)) == n*pi/d
|
911 |
+
|
912 |
+
assert asin(x).diff(x) == 1/sqrt(1 - x**2)
|
913 |
+
|
914 |
+
assert asin(0.2, evaluate=False).is_real is True
|
915 |
+
assert asin(-2).is_real is False
|
916 |
+
assert asin(r).is_real is None
|
917 |
+
|
918 |
+
assert asin(-2*I) == -I*asinh(2)
|
919 |
+
|
920 |
+
assert asin(Rational(1, 7), evaluate=False).is_positive is True
|
921 |
+
assert asin(Rational(-1, 7), evaluate=False).is_positive is False
|
922 |
+
assert asin(p).is_positive is None
|
923 |
+
assert asin(sin(Rational(7, 2))) == Rational(-7, 2) + pi
|
924 |
+
assert asin(sin(Rational(-7, 4))) == Rational(7, 4) - pi
|
925 |
+
assert unchanged(asin, cos(x))
|
926 |
+
|
927 |
+
|
928 |
+
def test_asin_series():
|
929 |
+
assert asin(x).series(x, 0, 9) == \
|
930 |
+
x + x**3/6 + 3*x**5/40 + 5*x**7/112 + O(x**9)
|
931 |
+
t5 = asin(x).taylor_term(5, x)
|
932 |
+
assert t5 == 3*x**5/40
|
933 |
+
assert asin(x).taylor_term(7, x, t5, 0) == 5*x**7/112
|
934 |
+
|
935 |
+
|
936 |
+
def test_asin_leading_term():
|
937 |
+
assert asin(x).as_leading_term(x) == x
|
938 |
+
# Tests concerning branch points
|
939 |
+
assert asin(x + 1).as_leading_term(x) == pi/2
|
940 |
+
assert asin(x - 1).as_leading_term(x) == -pi/2
|
941 |
+
assert asin(1/x).as_leading_term(x, cdir=1) == I*log(x) + pi/2 - I*log(2)
|
942 |
+
assert asin(1/x).as_leading_term(x, cdir=-1) == -I*log(x) - 3*pi/2 + I*log(2)
|
943 |
+
# Tests concerning points lying on branch cuts
|
944 |
+
assert asin(I*x + 2).as_leading_term(x, cdir=1) == pi - asin(2)
|
945 |
+
assert asin(-I*x + 2).as_leading_term(x, cdir=1) == asin(2)
|
946 |
+
assert asin(I*x - 2).as_leading_term(x, cdir=1) == -asin(2)
|
947 |
+
assert asin(-I*x - 2).as_leading_term(x, cdir=1) == -pi + asin(2)
|
948 |
+
# Tests concerning im(ndir) == 0
|
949 |
+
assert asin(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == -pi/2 + I*log(2 - sqrt(3))
|
950 |
+
assert asin(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(2 - sqrt(3))
|
951 |
+
|
952 |
+
|
953 |
+
def test_asin_rewrite():
|
954 |
+
assert asin(x).rewrite(log) == -I*log(I*x + sqrt(1 - x**2))
|
955 |
+
assert asin(x).rewrite(atan) == 2*atan(x/(1 + sqrt(1 - x**2)))
|
956 |
+
assert asin(x).rewrite(acos) == S.Pi/2 - acos(x)
|
957 |
+
assert asin(x).rewrite(acot) == 2*acot((sqrt(-x**2 + 1) + 1)/x)
|
958 |
+
assert asin(x).rewrite(asec) == -asec(1/x) + pi/2
|
959 |
+
assert asin(x).rewrite(acsc) == acsc(1/x)
|
960 |
+
|
961 |
+
|
962 |
+
def test_asin_fdiff():
|
963 |
+
assert asin(x).fdiff() == 1/sqrt(1 - x**2)
|
964 |
+
raises(ArgumentIndexError, lambda: asin(x).fdiff(2))
|
965 |
+
|
966 |
+
|
967 |
+
def test_acos():
|
968 |
+
assert acos(nan) is nan
|
969 |
+
assert acos(zoo) is zoo
|
970 |
+
|
971 |
+
assert acos.nargs == FiniteSet(1)
|
972 |
+
assert acos(oo) == I*oo
|
973 |
+
assert acos(-oo) == -I*oo
|
974 |
+
|
975 |
+
# Note: acos(-x) = pi - acos(x)
|
976 |
+
assert acos(0) == pi/2
|
977 |
+
assert acos(S.Half) == pi/3
|
978 |
+
assert acos(Rational(-1, 2)) == pi*Rational(2, 3)
|
979 |
+
assert acos(1) == 0
|
980 |
+
assert acos(-1) == pi
|
981 |
+
assert acos(sqrt(2)/2) == pi/4
|
982 |
+
assert acos(-sqrt(2)/2) == pi*Rational(3, 4)
|
983 |
+
|
984 |
+
# check round-trip for exact values:
|
985 |
+
for d in [5, 6, 8, 10, 12]:
|
986 |
+
for num in range(d):
|
987 |
+
if gcd(num, d) == 1:
|
988 |
+
assert acos(cos(num*pi/d)) == num*pi/d
|
989 |
+
|
990 |
+
assert acos(2*I) == pi/2 - asin(2*I)
|
991 |
+
|
992 |
+
assert acos(x).diff(x) == -1/sqrt(1 - x**2)
|
993 |
+
|
994 |
+
assert acos(0.2).is_real is True
|
995 |
+
assert acos(-2).is_real is False
|
996 |
+
assert acos(r).is_real is None
|
997 |
+
|
998 |
+
assert acos(Rational(1, 7), evaluate=False).is_positive is True
|
999 |
+
assert acos(Rational(-1, 7), evaluate=False).is_positive is True
|
1000 |
+
assert acos(Rational(3, 2), evaluate=False).is_positive is False
|
1001 |
+
assert acos(p).is_positive is None
|
1002 |
+
|
1003 |
+
assert acos(2 + p).conjugate() != acos(10 + p)
|
1004 |
+
assert acos(-3 + n).conjugate() != acos(-3 + n)
|
1005 |
+
assert acos(Rational(1, 3)).conjugate() == acos(Rational(1, 3))
|
1006 |
+
assert acos(Rational(-1, 3)).conjugate() == acos(Rational(-1, 3))
|
1007 |
+
assert acos(p + n*I).conjugate() == acos(p - n*I)
|
1008 |
+
assert acos(z).conjugate() != acos(conjugate(z))
|
1009 |
+
|
1010 |
+
|
1011 |
+
def test_acos_leading_term():
|
1012 |
+
assert acos(x).as_leading_term(x) == pi/2
|
1013 |
+
# Tests concerning branch points
|
1014 |
+
assert acos(x + 1).as_leading_term(x) == sqrt(2)*sqrt(-x)
|
1015 |
+
assert acos(x - 1).as_leading_term(x) == pi
|
1016 |
+
assert acos(1/x).as_leading_term(x, cdir=1) == -I*log(x) + I*log(2)
|
1017 |
+
assert acos(1/x).as_leading_term(x, cdir=-1) == I*log(x) + 2*pi - I*log(2)
|
1018 |
+
# Tests concerning points lying on branch cuts
|
1019 |
+
assert acos(I*x + 2).as_leading_term(x, cdir=1) == -acos(2)
|
1020 |
+
assert acos(-I*x + 2).as_leading_term(x, cdir=1) == acos(2)
|
1021 |
+
assert acos(I*x - 2).as_leading_term(x, cdir=1) == acos(-2)
|
1022 |
+
assert acos(-I*x - 2).as_leading_term(x, cdir=1) == 2*pi - acos(-2)
|
1023 |
+
# Tests concerning im(ndir) == 0
|
1024 |
+
assert acos(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == pi + I*log(sqrt(3) + 2)
|
1025 |
+
assert acos(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == pi + I*log(sqrt(3) + 2)
|
1026 |
+
|
1027 |
+
|
1028 |
+
def test_acos_series():
|
1029 |
+
assert acos(x).series(x, 0, 8) == \
|
1030 |
+
pi/2 - x - x**3/6 - 3*x**5/40 - 5*x**7/112 + O(x**8)
|
1031 |
+
assert acos(x).series(x, 0, 8) == pi/2 - asin(x).series(x, 0, 8)
|
1032 |
+
t5 = acos(x).taylor_term(5, x)
|
1033 |
+
assert t5 == -3*x**5/40
|
1034 |
+
assert acos(x).taylor_term(7, x, t5, 0) == -5*x**7/112
|
1035 |
+
assert acos(x).taylor_term(0, x) == pi/2
|
1036 |
+
assert acos(x).taylor_term(2, x) is S.Zero
|
1037 |
+
|
1038 |
+
|
1039 |
+
def test_acos_rewrite():
|
1040 |
+
assert acos(x).rewrite(log) == pi/2 + I*log(I*x + sqrt(1 - x**2))
|
1041 |
+
assert acos(x).rewrite(atan) == pi*(-x*sqrt(x**(-2)) + 1)/2 + atan(sqrt(1 - x**2)/x)
|
1042 |
+
assert acos(0).rewrite(atan) == S.Pi/2
|
1043 |
+
assert acos(0.5).rewrite(atan) == acos(0.5).rewrite(log)
|
1044 |
+
assert acos(x).rewrite(asin) == S.Pi/2 - asin(x)
|
1045 |
+
assert acos(x).rewrite(acot) == -2*acot((sqrt(-x**2 + 1) + 1)/x) + pi/2
|
1046 |
+
assert acos(x).rewrite(asec) == asec(1/x)
|
1047 |
+
assert acos(x).rewrite(acsc) == -acsc(1/x) + pi/2
|
1048 |
+
|
1049 |
+
|
1050 |
+
def test_acos_fdiff():
|
1051 |
+
assert acos(x).fdiff() == -1/sqrt(1 - x**2)
|
1052 |
+
raises(ArgumentIndexError, lambda: acos(x).fdiff(2))
|
1053 |
+
|
1054 |
+
|
1055 |
+
def test_atan():
|
1056 |
+
assert atan(nan) is nan
|
1057 |
+
|
1058 |
+
assert atan.nargs == FiniteSet(1)
|
1059 |
+
assert atan(oo) == pi/2
|
1060 |
+
assert atan(-oo) == -pi/2
|
1061 |
+
assert atan(zoo) == AccumBounds(-pi/2, pi/2)
|
1062 |
+
|
1063 |
+
assert atan(0) == 0
|
1064 |
+
assert atan(1) == pi/4
|
1065 |
+
assert atan(sqrt(3)) == pi/3
|
1066 |
+
assert atan(-(1 + sqrt(2))) == pi*Rational(-3, 8)
|
1067 |
+
assert atan(sqrt(5 - 2 * sqrt(5))) == pi/5
|
1068 |
+
assert atan(-sqrt(1 - 2 * sqrt(5)/ 5)) == -pi/10
|
1069 |
+
assert atan(sqrt(1 + 2 * sqrt(5) / 5)) == pi*Rational(3, 10)
|
1070 |
+
assert atan(-2 + sqrt(3)) == -pi/12
|
1071 |
+
assert atan(2 + sqrt(3)) == pi*Rational(5, 12)
|
1072 |
+
assert atan(-2 - sqrt(3)) == pi*Rational(-5, 12)
|
1073 |
+
|
1074 |
+
# check round-trip for exact values:
|
1075 |
+
for d in [5, 6, 8, 10, 12]:
|
1076 |
+
for num in range(-(d//2), d//2 + 1):
|
1077 |
+
if gcd(num, d) == 1:
|
1078 |
+
assert atan(tan(num*pi/d)) == num*pi/d
|
1079 |
+
|
1080 |
+
assert atan(oo) == pi/2
|
1081 |
+
assert atan(x).diff(x) == 1/(1 + x**2)
|
1082 |
+
|
1083 |
+
assert atan(r).is_real is True
|
1084 |
+
|
1085 |
+
assert atan(-2*I) == -I*atanh(2)
|
1086 |
+
assert unchanged(atan, cot(x))
|
1087 |
+
assert atan(cot(Rational(1, 4))) == Rational(-1, 4) + pi/2
|
1088 |
+
assert acot(Rational(1, 4)).is_rational is False
|
1089 |
+
|
1090 |
+
for s in (x, p, n, np, nn, nz, ep, en, enp, enn, enz):
|
1091 |
+
if s.is_real or s.is_extended_real is None:
|
1092 |
+
assert s.is_nonzero is atan(s).is_nonzero
|
1093 |
+
assert s.is_positive is atan(s).is_positive
|
1094 |
+
assert s.is_negative is atan(s).is_negative
|
1095 |
+
assert s.is_nonpositive is atan(s).is_nonpositive
|
1096 |
+
assert s.is_nonnegative is atan(s).is_nonnegative
|
1097 |
+
else:
|
1098 |
+
assert s.is_extended_nonzero is atan(s).is_nonzero
|
1099 |
+
assert s.is_extended_positive is atan(s).is_positive
|
1100 |
+
assert s.is_extended_negative is atan(s).is_negative
|
1101 |
+
assert s.is_extended_nonpositive is atan(s).is_nonpositive
|
1102 |
+
assert s.is_extended_nonnegative is atan(s).is_nonnegative
|
1103 |
+
assert s.is_extended_nonzero is atan(s).is_extended_nonzero
|
1104 |
+
assert s.is_extended_positive is atan(s).is_extended_positive
|
1105 |
+
assert s.is_extended_negative is atan(s).is_extended_negative
|
1106 |
+
assert s.is_extended_nonpositive is atan(s).is_extended_nonpositive
|
1107 |
+
assert s.is_extended_nonnegative is atan(s).is_extended_nonnegative
|
1108 |
+
|
1109 |
+
|
1110 |
+
def test_atan_rewrite():
|
1111 |
+
assert atan(x).rewrite(log) == I*(log(1 - I*x)-log(1 + I*x))/2
|
1112 |
+
assert atan(x).rewrite(asin) == (-asin(1/sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x
|
1113 |
+
assert atan(x).rewrite(acos) == sqrt(x**2)*acos(1/sqrt(x**2 + 1))/x
|
1114 |
+
assert atan(x).rewrite(acot) == acot(1/x)
|
1115 |
+
assert atan(x).rewrite(asec) == sqrt(x**2)*asec(sqrt(x**2 + 1))/x
|
1116 |
+
assert atan(x).rewrite(acsc) == (-acsc(sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x
|
1117 |
+
|
1118 |
+
assert atan(-5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:-5*I})
|
1119 |
+
assert atan(5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:5*I})
|
1120 |
+
|
1121 |
+
|
1122 |
+
def test_atan_fdiff():
|
1123 |
+
assert atan(x).fdiff() == 1/(x**2 + 1)
|
1124 |
+
raises(ArgumentIndexError, lambda: atan(x).fdiff(2))
|
1125 |
+
|
1126 |
+
|
1127 |
+
def test_atan_leading_term():
|
1128 |
+
assert atan(x).as_leading_term(x) == x
|
1129 |
+
assert atan(1/x).as_leading_term(x, cdir=1) == pi/2
|
1130 |
+
assert atan(1/x).as_leading_term(x, cdir=-1) == -pi/2
|
1131 |
+
# Tests concerning branch points
|
1132 |
+
assert atan(x + I).as_leading_term(x, cdir=1) == -I*log(x)/2 + pi/4 + I*log(2)/2
|
1133 |
+
assert atan(x + I).as_leading_term(x, cdir=-1) == -I*log(x)/2 - 3*pi/4 + I*log(2)/2
|
1134 |
+
assert atan(x - I).as_leading_term(x, cdir=1) == I*log(x)/2 + pi/4 - I*log(2)/2
|
1135 |
+
assert atan(x - I).as_leading_term(x, cdir=-1) == I*log(x)/2 + pi/4 - I*log(2)/2
|
1136 |
+
# Tests concerning points lying on branch cuts
|
1137 |
+
assert atan(x + 2*I).as_leading_term(x, cdir=1) == I*atanh(2)
|
1138 |
+
assert atan(x + 2*I).as_leading_term(x, cdir=-1) == -pi + I*atanh(2)
|
1139 |
+
assert atan(x - 2*I).as_leading_term(x, cdir=1) == pi - I*atanh(2)
|
1140 |
+
assert atan(x - 2*I).as_leading_term(x, cdir=-1) == -I*atanh(2)
|
1141 |
+
# Tests concerning re(ndir) == 0
|
1142 |
+
assert atan(2*I - I*x - x**2).as_leading_term(x, cdir=1) == -pi/2 + I*log(3)/2
|
1143 |
+
assert atan(2*I - I*x - x**2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(3)/2
|
1144 |
+
|
1145 |
+
|
1146 |
+
def test_atan2():
|
1147 |
+
assert atan2.nargs == FiniteSet(2)
|
1148 |
+
assert atan2(0, 0) is S.NaN
|
1149 |
+
assert atan2(0, 1) == 0
|
1150 |
+
assert atan2(1, 1) == pi/4
|
1151 |
+
assert atan2(1, 0) == pi/2
|
1152 |
+
assert atan2(1, -1) == pi*Rational(3, 4)
|
1153 |
+
assert atan2(0, -1) == pi
|
1154 |
+
assert atan2(-1, -1) == pi*Rational(-3, 4)
|
1155 |
+
assert atan2(-1, 0) == -pi/2
|
1156 |
+
assert atan2(-1, 1) == -pi/4
|
1157 |
+
i = symbols('i', imaginary=True)
|
1158 |
+
r = symbols('r', real=True)
|
1159 |
+
eq = atan2(r, i)
|
1160 |
+
ans = -I*log((i + I*r)/sqrt(i**2 + r**2))
|
1161 |
+
reps = ((r, 2), (i, I))
|
1162 |
+
assert eq.subs(reps) == ans.subs(reps)
|
1163 |
+
|
1164 |
+
x = Symbol('x', negative=True)
|
1165 |
+
y = Symbol('y', negative=True)
|
1166 |
+
assert atan2(y, x) == atan(y/x) - pi
|
1167 |
+
y = Symbol('y', nonnegative=True)
|
1168 |
+
assert atan2(y, x) == atan(y/x) + pi
|
1169 |
+
y = Symbol('y')
|
1170 |
+
assert atan2(y, x) == atan2(y, x, evaluate=False)
|
1171 |
+
|
1172 |
+
u = Symbol("u", positive=True)
|
1173 |
+
assert atan2(0, u) == 0
|
1174 |
+
u = Symbol("u", negative=True)
|
1175 |
+
assert atan2(0, u) == pi
|
1176 |
+
|
1177 |
+
assert atan2(y, oo) == 0
|
1178 |
+
assert atan2(y, -oo)== 2*pi*Heaviside(re(y), S.Half) - pi
|
1179 |
+
|
1180 |
+
assert atan2(y, x).rewrite(log) == -I*log((x + I*y)/sqrt(x**2 + y**2))
|
1181 |
+
assert atan2(0, 0) is S.NaN
|
1182 |
+
|
1183 |
+
ex = atan2(y, x) - arg(x + I*y)
|
1184 |
+
assert ex.subs({x:2, y:3}).rewrite(arg) == 0
|
1185 |
+
assert ex.subs({x:2, y:3*I}).rewrite(arg) == -pi - I*log(sqrt(5)*I/5)
|
1186 |
+
assert ex.subs({x:2*I, y:3}).rewrite(arg) == -pi/2 - I*log(sqrt(5)*I)
|
1187 |
+
assert ex.subs({x:2*I, y:3*I}).rewrite(arg) == -pi + atan(Rational(2, 3)) + atan(Rational(3, 2))
|
1188 |
+
i = symbols('i', imaginary=True)
|
1189 |
+
r = symbols('r', real=True)
|
1190 |
+
e = atan2(i, r)
|
1191 |
+
rewrite = e.rewrite(arg)
|
1192 |
+
reps = {i: I, r: -2}
|
1193 |
+
assert rewrite == -I*log(abs(I*i + r)/sqrt(abs(i**2 + r**2))) + arg((I*i + r)/sqrt(i**2 + r**2))
|
1194 |
+
assert (e - rewrite).subs(reps).equals(0)
|
1195 |
+
|
1196 |
+
assert atan2(0, x).rewrite(atan) == Piecewise((pi, re(x) < 0),
|
1197 |
+
(0, Ne(x, 0)),
|
1198 |
+
(nan, True))
|
1199 |
+
assert atan2(0, r).rewrite(atan) == Piecewise((pi, r < 0), (0, Ne(r, 0)), (S.NaN, True))
|
1200 |
+
assert atan2(0, i),rewrite(atan) == 0
|
1201 |
+
assert atan2(0, r + i).rewrite(atan) == Piecewise((pi, r < 0), (0, True))
|
1202 |
+
|
1203 |
+
assert atan2(y, x).rewrite(atan) == Piecewise(
|
1204 |
+
(2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)),
|
1205 |
+
(pi, re(x) < 0),
|
1206 |
+
(0, (re(x) > 0) | Ne(im(x), 0)),
|
1207 |
+
(nan, True))
|
1208 |
+
assert conjugate(atan2(x, y)) == atan2(conjugate(x), conjugate(y))
|
1209 |
+
|
1210 |
+
assert diff(atan2(y, x), x) == -y/(x**2 + y**2)
|
1211 |
+
assert diff(atan2(y, x), y) == x/(x**2 + y**2)
|
1212 |
+
|
1213 |
+
assert simplify(diff(atan2(y, x).rewrite(log), x)) == -y/(x**2 + y**2)
|
1214 |
+
assert simplify(diff(atan2(y, x).rewrite(log), y)) == x/(x**2 + y**2)
|
1215 |
+
|
1216 |
+
assert str(atan2(1, 2).evalf(5)) == '0.46365'
|
1217 |
+
raises(ArgumentIndexError, lambda: atan2(x, y).fdiff(3))
|
1218 |
+
|
1219 |
+
def test_issue_17461():
|
1220 |
+
class A(Symbol):
|
1221 |
+
is_extended_real = True
|
1222 |
+
|
1223 |
+
def _eval_evalf(self, prec):
|
1224 |
+
return Float(5.0)
|
1225 |
+
|
1226 |
+
x = A('X')
|
1227 |
+
y = A('Y')
|
1228 |
+
assert abs(atan2(x, y).evalf() - 0.785398163397448) <= 1e-10
|
1229 |
+
|
1230 |
+
def test_acot():
|
1231 |
+
assert acot(nan) is nan
|
1232 |
+
|
1233 |
+
assert acot.nargs == FiniteSet(1)
|
1234 |
+
assert acot(-oo) == 0
|
1235 |
+
assert acot(oo) == 0
|
1236 |
+
assert acot(zoo) == 0
|
1237 |
+
assert acot(1) == pi/4
|
1238 |
+
assert acot(0) == pi/2
|
1239 |
+
assert acot(sqrt(3)/3) == pi/3
|
1240 |
+
assert acot(1/sqrt(3)) == pi/3
|
1241 |
+
assert acot(-1/sqrt(3)) == -pi/3
|
1242 |
+
assert acot(x).diff(x) == -1/(1 + x**2)
|
1243 |
+
|
1244 |
+
assert acot(r).is_extended_real is True
|
1245 |
+
|
1246 |
+
assert acot(I*pi) == -I*acoth(pi)
|
1247 |
+
assert acot(-2*I) == I*acoth(2)
|
1248 |
+
assert acot(x).is_positive is None
|
1249 |
+
assert acot(n).is_positive is False
|
1250 |
+
assert acot(p).is_positive is True
|
1251 |
+
assert acot(I).is_positive is False
|
1252 |
+
assert acot(Rational(1, 4)).is_rational is False
|
1253 |
+
assert unchanged(acot, cot(x))
|
1254 |
+
assert unchanged(acot, tan(x))
|
1255 |
+
assert acot(cot(Rational(1, 4))) == Rational(1, 4)
|
1256 |
+
assert acot(tan(Rational(-1, 4))) == Rational(1, 4) - pi/2
|
1257 |
+
|
1258 |
+
|
1259 |
+
def test_acot_rewrite():
|
1260 |
+
assert acot(x).rewrite(log) == I*(log(1 - I/x)-log(1 + I/x))/2
|
1261 |
+
assert acot(x).rewrite(asin) == x*(-asin(sqrt(-x**2)/sqrt(-x**2 - 1)) + pi/2)*sqrt(x**(-2))
|
1262 |
+
assert acot(x).rewrite(acos) == x*sqrt(x**(-2))*acos(sqrt(-x**2)/sqrt(-x**2 - 1))
|
1263 |
+
assert acot(x).rewrite(atan) == atan(1/x)
|
1264 |
+
assert acot(x).rewrite(asec) == x*sqrt(x**(-2))*asec(sqrt((x**2 + 1)/x**2))
|
1265 |
+
assert acot(x).rewrite(acsc) == x*(-acsc(sqrt((x**2 + 1)/x**2)) + pi/2)*sqrt(x**(-2))
|
1266 |
+
|
1267 |
+
assert acot(-I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:-I/5})
|
1268 |
+
assert acot(I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:I/5})
|
1269 |
+
|
1270 |
+
|
1271 |
+
def test_acot_fdiff():
|
1272 |
+
assert acot(x).fdiff() == -1/(x**2 + 1)
|
1273 |
+
raises(ArgumentIndexError, lambda: acot(x).fdiff(2))
|
1274 |
+
|
1275 |
+
def test_acot_leading_term():
|
1276 |
+
assert acot(1/x).as_leading_term(x) == x
|
1277 |
+
# Tests concerning branch points
|
1278 |
+
assert acot(x + I).as_leading_term(x, cdir=1) == I*log(x)/2 + pi/4 - I*log(2)/2
|
1279 |
+
assert acot(x + I).as_leading_term(x, cdir=-1) == I*log(x)/2 + pi/4 - I*log(2)/2
|
1280 |
+
assert acot(x - I).as_leading_term(x, cdir=1) == -I*log(x)/2 + pi/4 + I*log(2)/2
|
1281 |
+
assert acot(x - I).as_leading_term(x, cdir=-1) == -I*log(x)/2 - 3*pi/4 + I*log(2)/2
|
1282 |
+
# Tests concerning points lying on branch cuts
|
1283 |
+
assert acot(x).as_leading_term(x, cdir=1) == pi/2
|
1284 |
+
assert acot(x).as_leading_term(x, cdir=-1) == -pi/2
|
1285 |
+
assert acot(x + I/2).as_leading_term(x, cdir=1) == pi - I*acoth(S(1)/2)
|
1286 |
+
assert acot(x + I/2).as_leading_term(x, cdir=-1) == -I*acoth(S(1)/2)
|
1287 |
+
assert acot(x - I/2).as_leading_term(x, cdir=1) == I*acoth(S(1)/2)
|
1288 |
+
assert acot(x - I/2).as_leading_term(x, cdir=-1) == -pi + I*acoth(S(1)/2)
|
1289 |
+
# Tests concerning re(ndir) == 0
|
1290 |
+
assert acot(I/2 - I*x - x**2).as_leading_term(x, cdir=1) == -pi/2 - I*log(3)/2
|
1291 |
+
assert acot(I/2 - I*x - x**2).as_leading_term(x, cdir=-1) == -pi/2 - I*log(3)/2
|
1292 |
+
|
1293 |
+
|
1294 |
+
def test_attributes():
|
1295 |
+
assert sin(x).args == (x,)
|
1296 |
+
|
1297 |
+
|
1298 |
+
def test_sincos_rewrite():
|
1299 |
+
assert sin(pi/2 - x) == cos(x)
|
1300 |
+
assert sin(pi - x) == sin(x)
|
1301 |
+
assert cos(pi/2 - x) == sin(x)
|
1302 |
+
assert cos(pi - x) == -cos(x)
|
1303 |
+
|
1304 |
+
|
1305 |
+
def _check_even_rewrite(func, arg):
|
1306 |
+
"""Checks that the expr has been rewritten using f(-x) -> f(x)
|
1307 |
+
arg : -x
|
1308 |
+
"""
|
1309 |
+
return func(arg).args[0] == -arg
|
1310 |
+
|
1311 |
+
|
1312 |
+
def _check_odd_rewrite(func, arg):
|
1313 |
+
"""Checks that the expr has been rewritten using f(-x) -> -f(x)
|
1314 |
+
arg : -x
|
1315 |
+
"""
|
1316 |
+
return func(arg).func.is_Mul
|
1317 |
+
|
1318 |
+
|
1319 |
+
def _check_no_rewrite(func, arg):
|
1320 |
+
"""Checks that the expr is not rewritten"""
|
1321 |
+
return func(arg).args[0] == arg
|
1322 |
+
|
1323 |
+
|
1324 |
+
def test_evenodd_rewrite():
|
1325 |
+
a = cos(2) # negative
|
1326 |
+
b = sin(1) # positive
|
1327 |
+
even = [cos]
|
1328 |
+
odd = [sin, tan, cot, asin, atan, acot]
|
1329 |
+
with_minus = [-1, -2**1024 * E, -pi/105, -x*y, -x - y]
|
1330 |
+
for func in even:
|
1331 |
+
for expr in with_minus:
|
1332 |
+
assert _check_even_rewrite(func, expr)
|
1333 |
+
assert _check_no_rewrite(func, a*b)
|
1334 |
+
assert func(
|
1335 |
+
x - y) == func(y - x) # it doesn't matter which form is canonical
|
1336 |
+
for func in odd:
|
1337 |
+
for expr in with_minus:
|
1338 |
+
assert _check_odd_rewrite(func, expr)
|
1339 |
+
assert _check_no_rewrite(func, a*b)
|
1340 |
+
assert func(
|
1341 |
+
x - y) == -func(y - x) # it doesn't matter which form is canonical
|
1342 |
+
|
1343 |
+
|
1344 |
+
def test_as_leading_term_issue_5272():
|
1345 |
+
assert sin(x).as_leading_term(x) == x
|
1346 |
+
assert cos(x).as_leading_term(x) == 1
|
1347 |
+
assert tan(x).as_leading_term(x) == x
|
1348 |
+
assert cot(x).as_leading_term(x) == 1/x
|
1349 |
+
|
1350 |
+
|
1351 |
+
def test_leading_terms():
|
1352 |
+
assert sin(1/x).as_leading_term(x) == AccumBounds(-1, 1)
|
1353 |
+
assert sin(S.Half).as_leading_term(x) == sin(S.Half)
|
1354 |
+
assert cos(1/x).as_leading_term(x) == AccumBounds(-1, 1)
|
1355 |
+
assert cos(S.Half).as_leading_term(x) == cos(S.Half)
|
1356 |
+
assert sec(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
|
1357 |
+
assert csc(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
|
1358 |
+
assert tan(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
|
1359 |
+
assert cot(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
|
1360 |
+
|
1361 |
+
# https://github.com/sympy/sympy/issues/21038
|
1362 |
+
f = sin(pi*(x + 4))/(3*x)
|
1363 |
+
assert f.as_leading_term(x) == pi/3
|
1364 |
+
|
1365 |
+
|
1366 |
+
def test_atan2_expansion():
|
1367 |
+
assert cancel(atan2(x**2, x + 1).diff(x) - atan(x**2/(x + 1)).diff(x)) == 0
|
1368 |
+
assert cancel(atan(y/x).series(y, 0, 5) - atan2(y, x).series(y, 0, 5)
|
1369 |
+
+ atan2(0, x) - atan(0)) == O(y**5)
|
1370 |
+
assert cancel(atan(y/x).series(x, 1, 4) - atan2(y, x).series(x, 1, 4)
|
1371 |
+
+ atan2(y, 1) - atan(y)) == O((x - 1)**4, (x, 1))
|
1372 |
+
assert cancel(atan((y + x)/x).series(x, 1, 3) - atan2(y + x, x).series(x, 1, 3)
|
1373 |
+
+ atan2(1 + y, 1) - atan(1 + y)) == O((x - 1)**3, (x, 1))
|
1374 |
+
assert Matrix([atan2(y, x)]).jacobian([y, x]) == \
|
1375 |
+
Matrix([[x/(y**2 + x**2), -y/(y**2 + x**2)]])
|
1376 |
+
|
1377 |
+
|
1378 |
+
def test_aseries():
|
1379 |
+
def t(n, v, d, e):
|
1380 |
+
assert abs(
|
1381 |
+
n(1/v).evalf() - n(1/x).series(x, dir=d).removeO().subs(x, v)) < e
|
1382 |
+
t(atan, 0.1, '+', 1e-5)
|
1383 |
+
t(atan, -0.1, '-', 1e-5)
|
1384 |
+
t(acot, 0.1, '+', 1e-5)
|
1385 |
+
t(acot, -0.1, '-', 1e-5)
|
1386 |
+
|
1387 |
+
|
1388 |
+
def test_issue_4420():
|
1389 |
+
i = Symbol('i', integer=True)
|
1390 |
+
e = Symbol('e', even=True)
|
1391 |
+
o = Symbol('o', odd=True)
|
1392 |
+
|
1393 |
+
# unknown parity for variable
|
1394 |
+
assert cos(4*i*pi) == 1
|
1395 |
+
assert sin(4*i*pi) == 0
|
1396 |
+
assert tan(4*i*pi) == 0
|
1397 |
+
assert cot(4*i*pi) is zoo
|
1398 |
+
|
1399 |
+
assert cos(3*i*pi) == cos(pi*i) # +/-1
|
1400 |
+
assert sin(3*i*pi) == 0
|
1401 |
+
assert tan(3*i*pi) == 0
|
1402 |
+
assert cot(3*i*pi) is zoo
|
1403 |
+
|
1404 |
+
assert cos(4.0*i*pi) == 1
|
1405 |
+
assert sin(4.0*i*pi) == 0
|
1406 |
+
assert tan(4.0*i*pi) == 0
|
1407 |
+
assert cot(4.0*i*pi) is zoo
|
1408 |
+
|
1409 |
+
assert cos(3.0*i*pi) == cos(pi*i) # +/-1
|
1410 |
+
assert sin(3.0*i*pi) == 0
|
1411 |
+
assert tan(3.0*i*pi) == 0
|
1412 |
+
assert cot(3.0*i*pi) is zoo
|
1413 |
+
|
1414 |
+
assert cos(4.5*i*pi) == cos(0.5*pi*i)
|
1415 |
+
assert sin(4.5*i*pi) == sin(0.5*pi*i)
|
1416 |
+
assert tan(4.5*i*pi) == tan(0.5*pi*i)
|
1417 |
+
assert cot(4.5*i*pi) == cot(0.5*pi*i)
|
1418 |
+
|
1419 |
+
# parity of variable is known
|
1420 |
+
assert cos(4*e*pi) == 1
|
1421 |
+
assert sin(4*e*pi) == 0
|
1422 |
+
assert tan(4*e*pi) == 0
|
1423 |
+
assert cot(4*e*pi) is zoo
|
1424 |
+
|
1425 |
+
assert cos(3*e*pi) == 1
|
1426 |
+
assert sin(3*e*pi) == 0
|
1427 |
+
assert tan(3*e*pi) == 0
|
1428 |
+
assert cot(3*e*pi) is zoo
|
1429 |
+
|
1430 |
+
assert cos(4.0*e*pi) == 1
|
1431 |
+
assert sin(4.0*e*pi) == 0
|
1432 |
+
assert tan(4.0*e*pi) == 0
|
1433 |
+
assert cot(4.0*e*pi) is zoo
|
1434 |
+
|
1435 |
+
assert cos(3.0*e*pi) == 1
|
1436 |
+
assert sin(3.0*e*pi) == 0
|
1437 |
+
assert tan(3.0*e*pi) == 0
|
1438 |
+
assert cot(3.0*e*pi) is zoo
|
1439 |
+
|
1440 |
+
assert cos(4.5*e*pi) == cos(0.5*pi*e)
|
1441 |
+
assert sin(4.5*e*pi) == sin(0.5*pi*e)
|
1442 |
+
assert tan(4.5*e*pi) == tan(0.5*pi*e)
|
1443 |
+
assert cot(4.5*e*pi) == cot(0.5*pi*e)
|
1444 |
+
|
1445 |
+
assert cos(4*o*pi) == 1
|
1446 |
+
assert sin(4*o*pi) == 0
|
1447 |
+
assert tan(4*o*pi) == 0
|
1448 |
+
assert cot(4*o*pi) is zoo
|
1449 |
+
|
1450 |
+
assert cos(3*o*pi) == -1
|
1451 |
+
assert sin(3*o*pi) == 0
|
1452 |
+
assert tan(3*o*pi) == 0
|
1453 |
+
assert cot(3*o*pi) is zoo
|
1454 |
+
|
1455 |
+
assert cos(4.0*o*pi) == 1
|
1456 |
+
assert sin(4.0*o*pi) == 0
|
1457 |
+
assert tan(4.0*o*pi) == 0
|
1458 |
+
assert cot(4.0*o*pi) is zoo
|
1459 |
+
|
1460 |
+
assert cos(3.0*o*pi) == -1
|
1461 |
+
assert sin(3.0*o*pi) == 0
|
1462 |
+
assert tan(3.0*o*pi) == 0
|
1463 |
+
assert cot(3.0*o*pi) is zoo
|
1464 |
+
|
1465 |
+
assert cos(4.5*o*pi) == cos(0.5*pi*o)
|
1466 |
+
assert sin(4.5*o*pi) == sin(0.5*pi*o)
|
1467 |
+
assert tan(4.5*o*pi) == tan(0.5*pi*o)
|
1468 |
+
assert cot(4.5*o*pi) == cot(0.5*pi*o)
|
1469 |
+
|
1470 |
+
# x could be imaginary
|
1471 |
+
assert cos(4*x*pi) == cos(4*pi*x)
|
1472 |
+
assert sin(4*x*pi) == sin(4*pi*x)
|
1473 |
+
assert tan(4*x*pi) == tan(4*pi*x)
|
1474 |
+
assert cot(4*x*pi) == cot(4*pi*x)
|
1475 |
+
|
1476 |
+
assert cos(3*x*pi) == cos(3*pi*x)
|
1477 |
+
assert sin(3*x*pi) == sin(3*pi*x)
|
1478 |
+
assert tan(3*x*pi) == tan(3*pi*x)
|
1479 |
+
assert cot(3*x*pi) == cot(3*pi*x)
|
1480 |
+
|
1481 |
+
assert cos(4.0*x*pi) == cos(4.0*pi*x)
|
1482 |
+
assert sin(4.0*x*pi) == sin(4.0*pi*x)
|
1483 |
+
assert tan(4.0*x*pi) == tan(4.0*pi*x)
|
1484 |
+
assert cot(4.0*x*pi) == cot(4.0*pi*x)
|
1485 |
+
|
1486 |
+
assert cos(3.0*x*pi) == cos(3.0*pi*x)
|
1487 |
+
assert sin(3.0*x*pi) == sin(3.0*pi*x)
|
1488 |
+
assert tan(3.0*x*pi) == tan(3.0*pi*x)
|
1489 |
+
assert cot(3.0*x*pi) == cot(3.0*pi*x)
|
1490 |
+
|
1491 |
+
assert cos(4.5*x*pi) == cos(4.5*pi*x)
|
1492 |
+
assert sin(4.5*x*pi) == sin(4.5*pi*x)
|
1493 |
+
assert tan(4.5*x*pi) == tan(4.5*pi*x)
|
1494 |
+
assert cot(4.5*x*pi) == cot(4.5*pi*x)
|
1495 |
+
|
1496 |
+
|
1497 |
+
def test_inverses():
|
1498 |
+
raises(AttributeError, lambda: sin(x).inverse())
|
1499 |
+
raises(AttributeError, lambda: cos(x).inverse())
|
1500 |
+
assert tan(x).inverse() == atan
|
1501 |
+
assert cot(x).inverse() == acot
|
1502 |
+
raises(AttributeError, lambda: csc(x).inverse())
|
1503 |
+
raises(AttributeError, lambda: sec(x).inverse())
|
1504 |
+
assert asin(x).inverse() == sin
|
1505 |
+
assert acos(x).inverse() == cos
|
1506 |
+
assert atan(x).inverse() == tan
|
1507 |
+
assert acot(x).inverse() == cot
|
1508 |
+
|
1509 |
+
|
1510 |
+
def test_real_imag():
|
1511 |
+
a, b = symbols('a b', real=True)
|
1512 |
+
z = a + b*I
|
1513 |
+
for deep in [True, False]:
|
1514 |
+
assert sin(
|
1515 |
+
z).as_real_imag(deep=deep) == (sin(a)*cosh(b), cos(a)*sinh(b))
|
1516 |
+
assert cos(
|
1517 |
+
z).as_real_imag(deep=deep) == (cos(a)*cosh(b), -sin(a)*sinh(b))
|
1518 |
+
assert tan(z).as_real_imag(deep=deep) == (sin(2*a)/(cos(2*a) +
|
1519 |
+
cosh(2*b)), sinh(2*b)/(cos(2*a) + cosh(2*b)))
|
1520 |
+
assert cot(z).as_real_imag(deep=deep) == (-sin(2*a)/(cos(2*a) -
|
1521 |
+
cosh(2*b)), sinh(2*b)/(cos(2*a) - cosh(2*b)))
|
1522 |
+
assert sin(a).as_real_imag(deep=deep) == (sin(a), 0)
|
1523 |
+
assert cos(a).as_real_imag(deep=deep) == (cos(a), 0)
|
1524 |
+
assert tan(a).as_real_imag(deep=deep) == (tan(a), 0)
|
1525 |
+
assert cot(a).as_real_imag(deep=deep) == (cot(a), 0)
|
1526 |
+
|
1527 |
+
|
1528 |
+
@XFAIL
|
1529 |
+
def test_sin_cos_with_infinity():
|
1530 |
+
# Test for issue 5196
|
1531 |
+
# https://github.com/sympy/sympy/issues/5196
|
1532 |
+
assert sin(oo) is S.NaN
|
1533 |
+
assert cos(oo) is S.NaN
|
1534 |
+
|
1535 |
+
|
1536 |
+
@slow
|
1537 |
+
def test_sincos_rewrite_sqrt():
|
1538 |
+
# equivalent to testing rewrite(pow)
|
1539 |
+
for p in [1, 3, 5, 17]:
|
1540 |
+
for t in [1, 8]:
|
1541 |
+
n = t*p
|
1542 |
+
# The vertices `exp(i*pi/n)` of a regular `n`-gon can
|
1543 |
+
# be expressed by means of nested square roots if and
|
1544 |
+
# only if `n` is a product of Fermat primes, `p`, and
|
1545 |
+
# powers of 2, `t'. The code aims to check all vertices
|
1546 |
+
# not belonging to an `m`-gon for `m < n`(`gcd(i, n) == 1`).
|
1547 |
+
# For large `n` this makes the test too slow, therefore
|
1548 |
+
# the vertices are limited to those of index `i < 10`.
|
1549 |
+
for i in range(1, min((n + 1)//2 + 1, 10)):
|
1550 |
+
if 1 == gcd(i, n):
|
1551 |
+
x = i*pi/n
|
1552 |
+
s1 = sin(x).rewrite(sqrt)
|
1553 |
+
c1 = cos(x).rewrite(sqrt)
|
1554 |
+
assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
|
1555 |
+
assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
|
1556 |
+
assert 1e-3 > abs(sin(x.evalf(5)) - s1.evalf(2)), "fails for %d*pi/%d" % (i, n)
|
1557 |
+
assert 1e-3 > abs(cos(x.evalf(5)) - c1.evalf(2)), "fails for %d*pi/%d" % (i, n)
|
1558 |
+
assert cos(pi/14).rewrite(sqrt) == sqrt(cos(pi/7)/2 + S.Half)
|
1559 |
+
assert cos(pi*Rational(-15, 2)/11, evaluate=False).rewrite(
|
1560 |
+
sqrt) == -sqrt(-cos(pi*Rational(4, 11))/2 + S.Half)
|
1561 |
+
assert cos(Mul(2, pi, S.Half, evaluate=False), evaluate=False).rewrite(
|
1562 |
+
sqrt) == -1
|
1563 |
+
e = cos(pi/3/17) # don't use pi/15 since that is caught at instantiation
|
1564 |
+
a = (
|
1565 |
+
-3*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17) + 17)/64 -
|
1566 |
+
3*sqrt(34)*sqrt(sqrt(17) + 17)/128 - sqrt(sqrt(17) +
|
1567 |
+
17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17)
|
1568 |
+
+ sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 - sqrt(-sqrt(17)
|
1569 |
+
+ 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
|
1570 |
+
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 - Rational(1, 32) +
|
1571 |
+
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
|
1572 |
+
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 +
|
1573 |
+
3*sqrt(2)*sqrt(sqrt(17) + 17)/128 + sqrt(34)*sqrt(-sqrt(17) + 17)/128
|
1574 |
+
+ 13*sqrt(2)*sqrt(-sqrt(17) + 17)/128 + sqrt(17)*sqrt(-sqrt(17) +
|
1575 |
+
17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17)
|
1576 |
+
+ sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 + 5*sqrt(17)/32
|
1577 |
+
+ sqrt(3)*sqrt(-sqrt(2)*sqrt(sqrt(17) + 17)*sqrt(sqrt(17)/32 +
|
1578 |
+
sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
|
1579 |
+
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
|
1580 |
+
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/8 -
|
1581 |
+
5*sqrt(2)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
|
1582 |
+
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
|
1583 |
+
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
|
1584 |
+
Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
|
1585 |
+
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 -
|
1586 |
+
3*sqrt(2)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 +
|
1587 |
+
sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
|
1588 |
+
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
|
1589 |
+
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/32
|
1590 |
+
+ sqrt(34)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
|
1591 |
+
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
|
1592 |
+
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
|
1593 |
+
Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
|
1594 |
+
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 +
|
1595 |
+
sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
|
1596 |
+
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
|
1597 |
+
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/2 +
|
1598 |
+
S.Half + sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) +
|
1599 |
+
17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) -
|
1600 |
+
sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) +
|
1601 |
+
6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) -
|
1602 |
+
sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) +
|
1603 |
+
6*sqrt(17) + 34)/32 + sqrt(34)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 +
|
1604 |
+
sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
|
1605 |
+
sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
|
1606 |
+
17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
|
1607 |
+
Rational(15, 32))/32)/2)
|
1608 |
+
assert e.rewrite(sqrt) == a
|
1609 |
+
assert e.n() == a.n()
|
1610 |
+
# coverage of fermatCoords: multiplicity > 1; the following could be
|
1611 |
+
# different but that portion of the code should be tested in some way
|
1612 |
+
assert cos(pi/9/17).rewrite(sqrt) == \
|
1613 |
+
sin(pi/9)*sin(pi*Rational(2, 17)) + cos(pi/9)*cos(pi*Rational(2, 17))
|
1614 |
+
|
1615 |
+
|
1616 |
+
@slow
|
1617 |
+
def test_sincos_rewrite_sqrt_257():
|
1618 |
+
assert cos(pi/257).rewrite(sqrt).evalf(64) == cos(pi/257).evalf(64)
|
1619 |
+
|
1620 |
+
|
1621 |
+
@slow
|
1622 |
+
def test_tancot_rewrite_sqrt():
|
1623 |
+
# equivalent to testing rewrite(pow)
|
1624 |
+
for p in [1, 3, 5, 17]:
|
1625 |
+
for t in [1, 8]:
|
1626 |
+
n = t*p
|
1627 |
+
for i in range(1, min((n + 1)//2 + 1, 10)):
|
1628 |
+
if 1 == gcd(i, n):
|
1629 |
+
x = i*pi/n
|
1630 |
+
if 2*i != n and 3*i != 2*n:
|
1631 |
+
t1 = tan(x).rewrite(sqrt)
|
1632 |
+
assert not t1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
|
1633 |
+
assert 1e-3 > abs( tan(x.evalf(7)) - t1.evalf(4) ), "fails for %d*pi/%d" % (i, n)
|
1634 |
+
if i != 0 and i != n:
|
1635 |
+
c1 = cot(x).rewrite(sqrt)
|
1636 |
+
assert not c1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
|
1637 |
+
assert 1e-3 > abs( cot(x.evalf(7)) - c1.evalf(4) ), "fails for %d*pi/%d" % (i, n)
|
1638 |
+
|
1639 |
+
|
1640 |
+
def test_sec():
|
1641 |
+
x = symbols('x', real=True)
|
1642 |
+
z = symbols('z')
|
1643 |
+
|
1644 |
+
assert sec.nargs == FiniteSet(1)
|
1645 |
+
|
1646 |
+
assert sec(zoo) is nan
|
1647 |
+
assert sec(0) == 1
|
1648 |
+
assert sec(pi) == -1
|
1649 |
+
assert sec(pi/2) is zoo
|
1650 |
+
assert sec(-pi/2) is zoo
|
1651 |
+
assert sec(pi/6) == 2*sqrt(3)/3
|
1652 |
+
assert sec(pi/3) == 2
|
1653 |
+
assert sec(pi*Rational(5, 2)) is zoo
|
1654 |
+
assert sec(pi*Rational(9, 7)) == -sec(pi*Rational(2, 7))
|
1655 |
+
assert sec(pi*Rational(3, 4)) == -sqrt(2) # issue 8421
|
1656 |
+
assert sec(I) == 1/cosh(1)
|
1657 |
+
assert sec(x*I) == 1/cosh(x)
|
1658 |
+
assert sec(-x) == sec(x)
|
1659 |
+
|
1660 |
+
assert sec(asec(x)) == x
|
1661 |
+
|
1662 |
+
assert sec(z).conjugate() == sec(conjugate(z))
|
1663 |
+
|
1664 |
+
assert (sec(z).as_real_imag() ==
|
1665 |
+
(cos(re(z))*cosh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
|
1666 |
+
cos(re(z))**2*cosh(im(z))**2),
|
1667 |
+
sin(re(z))*sinh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
|
1668 |
+
cos(re(z))**2*cosh(im(z))**2)))
|
1669 |
+
|
1670 |
+
assert sec(x).expand(trig=True) == 1/cos(x)
|
1671 |
+
assert sec(2*x).expand(trig=True) == 1/(2*cos(x)**2 - 1)
|
1672 |
+
|
1673 |
+
assert sec(x).is_extended_real == True
|
1674 |
+
assert sec(z).is_real == None
|
1675 |
+
|
1676 |
+
assert sec(a).is_algebraic is None
|
1677 |
+
assert sec(na).is_algebraic is False
|
1678 |
+
|
1679 |
+
assert sec(x).as_leading_term() == sec(x)
|
1680 |
+
|
1681 |
+
assert sec(0, evaluate=False).is_finite == True
|
1682 |
+
assert sec(x).is_finite == None
|
1683 |
+
assert sec(pi/2, evaluate=False).is_finite == False
|
1684 |
+
|
1685 |
+
assert series(sec(x), x, x0=0, n=6) == 1 + x**2/2 + 5*x**4/24 + O(x**6)
|
1686 |
+
|
1687 |
+
# https://github.com/sympy/sympy/issues/7166
|
1688 |
+
assert series(sqrt(sec(x))) == 1 + x**2/4 + 7*x**4/96 + O(x**6)
|
1689 |
+
|
1690 |
+
# https://github.com/sympy/sympy/issues/7167
|
1691 |
+
assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) ==
|
1692 |
+
1/sqrt(x - pi*Rational(3, 2)) + (x - pi*Rational(3, 2))**Rational(3, 2)/12 +
|
1693 |
+
(x - pi*Rational(3, 2))**Rational(7, 2)/160 + O((x - pi*Rational(3, 2))**4, (x, pi*Rational(3, 2))))
|
1694 |
+
|
1695 |
+
assert sec(x).diff(x) == tan(x)*sec(x)
|
1696 |
+
|
1697 |
+
# Taylor Term checks
|
1698 |
+
assert sec(z).taylor_term(4, z) == 5*z**4/24
|
1699 |
+
assert sec(z).taylor_term(6, z) == 61*z**6/720
|
1700 |
+
assert sec(z).taylor_term(5, z) == 0
|
1701 |
+
|
1702 |
+
|
1703 |
+
def test_sec_rewrite():
|
1704 |
+
assert sec(x).rewrite(exp) == 1/(exp(I*x)/2 + exp(-I*x)/2)
|
1705 |
+
assert sec(x).rewrite(cos) == 1/cos(x)
|
1706 |
+
assert sec(x).rewrite(tan) == (tan(x/2)**2 + 1)/(-tan(x/2)**2 + 1)
|
1707 |
+
assert sec(x).rewrite(pow) == sec(x)
|
1708 |
+
assert sec(x).rewrite(sqrt) == sec(x)
|
1709 |
+
assert sec(z).rewrite(cot) == (cot(z/2)**2 + 1)/(cot(z/2)**2 - 1)
|
1710 |
+
assert sec(x).rewrite(sin) == 1 / sin(x + pi / 2, evaluate=False)
|
1711 |
+
assert sec(x).rewrite(tan) == (tan(x / 2)**2 + 1) / (-tan(x / 2)**2 + 1)
|
1712 |
+
assert sec(x).rewrite(csc) == csc(-x + pi/2, evaluate=False)
|
1713 |
+
|
1714 |
+
|
1715 |
+
def test_sec_fdiff():
|
1716 |
+
assert sec(x).fdiff() == tan(x)*sec(x)
|
1717 |
+
raises(ArgumentIndexError, lambda: sec(x).fdiff(2))
|
1718 |
+
|
1719 |
+
|
1720 |
+
def test_csc():
|
1721 |
+
x = symbols('x', real=True)
|
1722 |
+
z = symbols('z')
|
1723 |
+
|
1724 |
+
# https://github.com/sympy/sympy/issues/6707
|
1725 |
+
cosecant = csc('x')
|
1726 |
+
alternate = 1/sin('x')
|
1727 |
+
assert cosecant.equals(alternate) == True
|
1728 |
+
assert alternate.equals(cosecant) == True
|
1729 |
+
|
1730 |
+
assert csc.nargs == FiniteSet(1)
|
1731 |
+
|
1732 |
+
assert csc(0) is zoo
|
1733 |
+
assert csc(pi) is zoo
|
1734 |
+
assert csc(zoo) is nan
|
1735 |
+
|
1736 |
+
assert csc(pi/2) == 1
|
1737 |
+
assert csc(-pi/2) == -1
|
1738 |
+
assert csc(pi/6) == 2
|
1739 |
+
assert csc(pi/3) == 2*sqrt(3)/3
|
1740 |
+
assert csc(pi*Rational(5, 2)) == 1
|
1741 |
+
assert csc(pi*Rational(9, 7)) == -csc(pi*Rational(2, 7))
|
1742 |
+
assert csc(pi*Rational(3, 4)) == sqrt(2) # issue 8421
|
1743 |
+
assert csc(I) == -I/sinh(1)
|
1744 |
+
assert csc(x*I) == -I/sinh(x)
|
1745 |
+
assert csc(-x) == -csc(x)
|
1746 |
+
|
1747 |
+
assert csc(acsc(x)) == x
|
1748 |
+
|
1749 |
+
assert csc(z).conjugate() == csc(conjugate(z))
|
1750 |
+
|
1751 |
+
assert (csc(z).as_real_imag() ==
|
1752 |
+
(sin(re(z))*cosh(im(z))/(sin(re(z))**2*cosh(im(z))**2 +
|
1753 |
+
cos(re(z))**2*sinh(im(z))**2),
|
1754 |
+
-cos(re(z))*sinh(im(z))/(sin(re(z))**2*cosh(im(z))**2 +
|
1755 |
+
cos(re(z))**2*sinh(im(z))**2)))
|
1756 |
+
|
1757 |
+
assert csc(x).expand(trig=True) == 1/sin(x)
|
1758 |
+
assert csc(2*x).expand(trig=True) == 1/(2*sin(x)*cos(x))
|
1759 |
+
|
1760 |
+
assert csc(x).is_extended_real == True
|
1761 |
+
assert csc(z).is_real == None
|
1762 |
+
|
1763 |
+
assert csc(a).is_algebraic is None
|
1764 |
+
assert csc(na).is_algebraic is False
|
1765 |
+
|
1766 |
+
assert csc(x).as_leading_term() == csc(x)
|
1767 |
+
|
1768 |
+
assert csc(0, evaluate=False).is_finite == False
|
1769 |
+
assert csc(x).is_finite == None
|
1770 |
+
assert csc(pi/2, evaluate=False).is_finite == True
|
1771 |
+
|
1772 |
+
assert series(csc(x), x, x0=pi/2, n=6) == \
|
1773 |
+
1 + (x - pi/2)**2/2 + 5*(x - pi/2)**4/24 + O((x - pi/2)**6, (x, pi/2))
|
1774 |
+
assert series(csc(x), x, x0=0, n=6) == \
|
1775 |
+
1/x + x/6 + 7*x**3/360 + 31*x**5/15120 + O(x**6)
|
1776 |
+
|
1777 |
+
assert csc(x).diff(x) == -cot(x)*csc(x)
|
1778 |
+
|
1779 |
+
assert csc(x).taylor_term(2, x) == 0
|
1780 |
+
assert csc(x).taylor_term(3, x) == 7*x**3/360
|
1781 |
+
assert csc(x).taylor_term(5, x) == 31*x**5/15120
|
1782 |
+
raises(ArgumentIndexError, lambda: csc(x).fdiff(2))
|
1783 |
+
|
1784 |
+
|
1785 |
+
def test_asec():
|
1786 |
+
z = Symbol('z', zero=True)
|
1787 |
+
assert asec(z) is zoo
|
1788 |
+
assert asec(nan) is nan
|
1789 |
+
assert asec(1) == 0
|
1790 |
+
assert asec(-1) == pi
|
1791 |
+
assert asec(oo) == pi/2
|
1792 |
+
assert asec(-oo) == pi/2
|
1793 |
+
assert asec(zoo) == pi/2
|
1794 |
+
|
1795 |
+
assert asec(sec(pi*Rational(13, 4))) == pi*Rational(3, 4)
|
1796 |
+
assert asec(1 + sqrt(5)) == pi*Rational(2, 5)
|
1797 |
+
assert asec(2/sqrt(3)) == pi/6
|
1798 |
+
assert asec(sqrt(4 - 2*sqrt(2))) == pi/8
|
1799 |
+
assert asec(-sqrt(4 + 2*sqrt(2))) == pi*Rational(5, 8)
|
1800 |
+
assert asec(sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(3, 10)
|
1801 |
+
assert asec(-sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(7, 10)
|
1802 |
+
assert asec(sqrt(2) - sqrt(6)) == pi*Rational(11, 12)
|
1803 |
+
|
1804 |
+
assert asec(x).diff(x) == 1/(x**2*sqrt(1 - 1/x**2))
|
1805 |
+
|
1806 |
+
assert asec(x).rewrite(log) == I*log(sqrt(1 - 1/x**2) + I/x) + pi/2
|
1807 |
+
assert asec(x).rewrite(asin) == -asin(1/x) + pi/2
|
1808 |
+
assert asec(x).rewrite(acos) == acos(1/x)
|
1809 |
+
assert asec(x).rewrite(atan) == \
|
1810 |
+
pi*(1 - sqrt(x**2)/x)/2 + sqrt(x**2)*atan(sqrt(x**2 - 1))/x
|
1811 |
+
assert asec(x).rewrite(acot) == \
|
1812 |
+
pi*(1 - sqrt(x**2)/x)/2 + sqrt(x**2)*acot(1/sqrt(x**2 - 1))/x
|
1813 |
+
assert asec(x).rewrite(acsc) == -acsc(x) + pi/2
|
1814 |
+
raises(ArgumentIndexError, lambda: asec(x).fdiff(2))
|
1815 |
+
|
1816 |
+
|
1817 |
+
def test_asec_is_real():
|
1818 |
+
assert asec(S.Half).is_real is False
|
1819 |
+
n = Symbol('n', positive=True, integer=True)
|
1820 |
+
assert asec(n).is_extended_real is True
|
1821 |
+
assert asec(x).is_real is None
|
1822 |
+
assert asec(r).is_real is None
|
1823 |
+
t = Symbol('t', real=False, finite=True)
|
1824 |
+
assert asec(t).is_real is False
|
1825 |
+
|
1826 |
+
|
1827 |
+
def test_asec_leading_term():
|
1828 |
+
assert asec(1/x).as_leading_term(x) == pi/2
|
1829 |
+
# Tests concerning branch points
|
1830 |
+
assert asec(x + 1).as_leading_term(x) == sqrt(2)*sqrt(x)
|
1831 |
+
assert asec(x - 1).as_leading_term(x) == pi
|
1832 |
+
# Tests concerning points lying on branch cuts
|
1833 |
+
assert asec(x).as_leading_term(x, cdir=1) == -I*log(x) + I*log(2)
|
1834 |
+
assert asec(x).as_leading_term(x, cdir=-1) == I*log(x) + 2*pi - I*log(2)
|
1835 |
+
assert asec(I*x + 1/2).as_leading_term(x, cdir=1) == asec(1/2)
|
1836 |
+
assert asec(-I*x + 1/2).as_leading_term(x, cdir=1) == -asec(1/2)
|
1837 |
+
assert asec(I*x - 1/2).as_leading_term(x, cdir=1) == 2*pi - asec(-1/2)
|
1838 |
+
assert asec(-I*x - 1/2).as_leading_term(x, cdir=1) == asec(-1/2)
|
1839 |
+
# Tests concerning im(ndir) == 0
|
1840 |
+
assert asec(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=1) == pi + I*log(2 - sqrt(3))
|
1841 |
+
assert asec(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=-1) == pi + I*log(2 - sqrt(3))
|
1842 |
+
|
1843 |
+
|
1844 |
+
def test_asec_series():
|
1845 |
+
assert asec(x).series(x, 0, 9) == \
|
1846 |
+
I*log(2) - I*log(x) - I*x**2/4 - 3*I*x**4/32 \
|
1847 |
+
- 5*I*x**6/96 - 35*I*x**8/1024 + O(x**9)
|
1848 |
+
t4 = asec(x).taylor_term(4, x)
|
1849 |
+
assert t4 == -3*I*x**4/32
|
1850 |
+
assert asec(x).taylor_term(6, x, t4, 0) == -5*I*x**6/96
|
1851 |
+
|
1852 |
+
|
1853 |
+
def test_acsc():
|
1854 |
+
assert acsc(nan) is nan
|
1855 |
+
assert acsc(1) == pi/2
|
1856 |
+
assert acsc(-1) == -pi/2
|
1857 |
+
assert acsc(oo) == 0
|
1858 |
+
assert acsc(-oo) == 0
|
1859 |
+
assert acsc(zoo) == 0
|
1860 |
+
assert acsc(0) is zoo
|
1861 |
+
|
1862 |
+
assert acsc(csc(3)) == -3 + pi
|
1863 |
+
assert acsc(csc(4)) == -4 + pi
|
1864 |
+
assert acsc(csc(6)) == 6 - 2*pi
|
1865 |
+
assert unchanged(acsc, csc(x))
|
1866 |
+
assert unchanged(acsc, sec(x))
|
1867 |
+
|
1868 |
+
assert acsc(2/sqrt(3)) == pi/3
|
1869 |
+
assert acsc(csc(pi*Rational(13, 4))) == -pi/4
|
1870 |
+
assert acsc(sqrt(2 + 2*sqrt(5)/5)) == pi/5
|
1871 |
+
assert acsc(-sqrt(2 + 2*sqrt(5)/5)) == -pi/5
|
1872 |
+
assert acsc(-2) == -pi/6
|
1873 |
+
assert acsc(-sqrt(4 + 2*sqrt(2))) == -pi/8
|
1874 |
+
assert acsc(sqrt(4 - 2*sqrt(2))) == pi*Rational(3, 8)
|
1875 |
+
assert acsc(1 + sqrt(5)) == pi/10
|
1876 |
+
assert acsc(sqrt(2) - sqrt(6)) == pi*Rational(-5, 12)
|
1877 |
+
|
1878 |
+
assert acsc(x).diff(x) == -1/(x**2*sqrt(1 - 1/x**2))
|
1879 |
+
|
1880 |
+
assert acsc(x).rewrite(log) == -I*log(sqrt(1 - 1/x**2) + I/x)
|
1881 |
+
assert acsc(x).rewrite(asin) == asin(1/x)
|
1882 |
+
assert acsc(x).rewrite(acos) == -acos(1/x) + pi/2
|
1883 |
+
assert acsc(x).rewrite(atan) == \
|
1884 |
+
(-atan(sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x
|
1885 |
+
assert acsc(x).rewrite(acot) == (-acot(1/sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x
|
1886 |
+
assert acsc(x).rewrite(asec) == -asec(x) + pi/2
|
1887 |
+
raises(ArgumentIndexError, lambda: acsc(x).fdiff(2))
|
1888 |
+
|
1889 |
+
|
1890 |
+
def test_csc_rewrite():
|
1891 |
+
assert csc(x).rewrite(pow) == csc(x)
|
1892 |
+
assert csc(x).rewrite(sqrt) == csc(x)
|
1893 |
+
|
1894 |
+
assert csc(x).rewrite(exp) == 2*I/(exp(I*x) - exp(-I*x))
|
1895 |
+
assert csc(x).rewrite(sin) == 1/sin(x)
|
1896 |
+
assert csc(x).rewrite(tan) == (tan(x/2)**2 + 1)/(2*tan(x/2))
|
1897 |
+
assert csc(x).rewrite(cot) == (cot(x/2)**2 + 1)/(2*cot(x/2))
|
1898 |
+
assert csc(x).rewrite(cos) == 1/cos(x - pi/2, evaluate=False)
|
1899 |
+
assert csc(x).rewrite(sec) == sec(-x + pi/2, evaluate=False)
|
1900 |
+
|
1901 |
+
# issue 17349
|
1902 |
+
assert csc(1 - exp(-besselj(I, I))).rewrite(cos) == \
|
1903 |
+
-1/cos(-pi/2 - 1 + cos(I*besselj(I, I)) +
|
1904 |
+
I*cos(-pi/2 + I*besselj(I, I), evaluate=False), evaluate=False)
|
1905 |
+
|
1906 |
+
|
1907 |
+
def test_acsc_leading_term():
|
1908 |
+
assert acsc(1/x).as_leading_term(x) == x
|
1909 |
+
# Tests concerning branch points
|
1910 |
+
assert acsc(x + 1).as_leading_term(x) == pi/2
|
1911 |
+
assert acsc(x - 1).as_leading_term(x) == -pi/2
|
1912 |
+
# Tests concerning points lying on branch cuts
|
1913 |
+
assert acsc(x).as_leading_term(x, cdir=1) == I*log(x) + pi/2 - I*log(2)
|
1914 |
+
assert acsc(x).as_leading_term(x, cdir=-1) == -I*log(x) - 3*pi/2 + I*log(2)
|
1915 |
+
assert acsc(I*x + 1/2).as_leading_term(x, cdir=1) == acsc(1/2)
|
1916 |
+
assert acsc(-I*x + 1/2).as_leading_term(x, cdir=1) == pi - acsc(1/2)
|
1917 |
+
assert acsc(I*x - 1/2).as_leading_term(x, cdir=1) == -pi - acsc(-1/2)
|
1918 |
+
assert acsc(-I*x - 1/2).as_leading_term(x, cdir=1) == -acsc(1/2)
|
1919 |
+
# Tests concerning im(ndir) == 0
|
1920 |
+
assert acsc(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=1) == -pi/2 + I*log(sqrt(3) + 2)
|
1921 |
+
assert acsc(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(sqrt(3) + 2)
|
1922 |
+
|
1923 |
+
|
1924 |
+
def test_acsc_series():
|
1925 |
+
assert acsc(x).series(x, 0, 9) == \
|
1926 |
+
-I*log(2) + pi/2 + I*log(x) + I*x**2/4 \
|
1927 |
+
+ 3*I*x**4/32 + 5*I*x**6/96 + 35*I*x**8/1024 + O(x**9)
|
1928 |
+
t6 = acsc(x).taylor_term(6, x)
|
1929 |
+
assert t6 == 5*I*x**6/96
|
1930 |
+
assert acsc(x).taylor_term(8, x, t6, 0) == 35*I*x**8/1024
|
1931 |
+
|
1932 |
+
|
1933 |
+
def test_asin_nseries():
|
1934 |
+
assert asin(x + 2)._eval_nseries(x, 4, None, I) == -asin(2) + pi + \
|
1935 |
+
sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
|
1936 |
+
assert asin(x + 2)._eval_nseries(x, 4, None, -I) == asin(2) - \
|
1937 |
+
sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
|
1938 |
+
assert asin(x - 2)._eval_nseries(x, 4, None, I) == -asin(2) - \
|
1939 |
+
sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
|
1940 |
+
assert asin(x - 2)._eval_nseries(x, 4, None, -I) == asin(2) - pi + \
|
1941 |
+
sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
|
1942 |
+
# testing nseries for asin at branch points
|
1943 |
+
assert asin(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) - \
|
1944 |
+
sqrt(2)*(-x)**(S(3)/2)/12 - 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
|
1945 |
+
assert asin(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) + \
|
1946 |
+
sqrt(2)*x**(S(3)/2)/12 + 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
|
1947 |
+
assert asin(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) + \
|
1948 |
+
sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
|
1949 |
+
assert asin(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - \
|
1950 |
+
sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
|
1951 |
+
|
1952 |
+
|
1953 |
+
def test_acos_nseries():
|
1954 |
+
assert acos(x + 2)._eval_nseries(x, 4, None, I) == -acos(2) - sqrt(3)*I*x/3 + \
|
1955 |
+
sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
|
1956 |
+
assert acos(x + 2)._eval_nseries(x, 4, None, -I) == acos(2) + sqrt(3)*I*x/3 - \
|
1957 |
+
sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
|
1958 |
+
assert acos(x - 2)._eval_nseries(x, 4, None, I) == acos(-2) + sqrt(3)*I*x/3 + \
|
1959 |
+
sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
|
1960 |
+
assert acos(x - 2)._eval_nseries(x, 4, None, -I) == -acos(-2) + 2*pi - \
|
1961 |
+
sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
|
1962 |
+
# testing nseries for acos at branch points
|
1963 |
+
assert acos(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) + \
|
1964 |
+
sqrt(2)*(-x)**(S(3)/2)/12 + 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
|
1965 |
+
assert acos(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) - \
|
1966 |
+
sqrt(2)*x**(S(3)/2)/12 - 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
|
1967 |
+
assert acos(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) - \
|
1968 |
+
sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
|
1969 |
+
assert acos(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + \
|
1970 |
+
sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
|
1971 |
+
|
1972 |
+
|
1973 |
+
def test_atan_nseries():
|
1974 |
+
assert atan(x + 2*I)._eval_nseries(x, 4, None, 1) == I*atanh(2) - x/3 - \
|
1975 |
+
2*I*x**2/9 + 13*x**3/81 + O(x**4)
|
1976 |
+
assert atan(x + 2*I)._eval_nseries(x, 4, None, -1) == I*atanh(2) - pi - \
|
1977 |
+
x/3 - 2*I*x**2/9 + 13*x**3/81 + O(x**4)
|
1978 |
+
assert atan(x - 2*I)._eval_nseries(x, 4, None, 1) == -I*atanh(2) + pi - \
|
1979 |
+
x/3 + 2*I*x**2/9 + 13*x**3/81 + O(x**4)
|
1980 |
+
assert atan(x - 2*I)._eval_nseries(x, 4, None, -1) == -I*atanh(2) - x/3 + \
|
1981 |
+
2*I*x**2/9 + 13*x**3/81 + O(x**4)
|
1982 |
+
assert atan(1/x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2)
|
1983 |
+
assert atan(1/x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2)
|
1984 |
+
# testing nseries for atan at branch points
|
1985 |
+
assert atan(x + I)._eval_nseries(x, 4, None) == I*log(2)/2 + pi/4 - \
|
1986 |
+
I*log(x)/2 + x/4 + I*x**2/16 - x**3/48 + O(x**4)
|
1987 |
+
assert atan(x - I)._eval_nseries(x, 4, None) == -I*log(2)/2 + pi/4 + \
|
1988 |
+
I*log(x)/2 + x/4 - I*x**2/16 - x**3/48 + O(x**4)
|
1989 |
+
|
1990 |
+
|
1991 |
+
def test_acot_nseries():
|
1992 |
+
assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, 1) == -I*acoth(S(1)/2) + \
|
1993 |
+
pi - 4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4)
|
1994 |
+
assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, -1) == -I*acoth(S(1)/2) - \
|
1995 |
+
4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4)
|
1996 |
+
assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, 1) == I*acoth(S(1)/2) - \
|
1997 |
+
4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4)
|
1998 |
+
assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, -1) == I*acoth(S(1)/2) - \
|
1999 |
+
pi - 4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4)
|
2000 |
+
assert acot(x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2)
|
2001 |
+
assert acot(x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2)
|
2002 |
+
# testing nseries for acot at branch points
|
2003 |
+
assert acot(x + I)._eval_nseries(x, 4, None) == -I*log(2)/2 + pi/4 + \
|
2004 |
+
I*log(x)/2 - x/4 - I*x**2/16 + x**3/48 + O(x**4)
|
2005 |
+
assert acot(x - I)._eval_nseries(x, 4, None) == I*log(2)/2 + pi/4 - \
|
2006 |
+
I*log(x)/2 - x/4 + I*x**2/16 + x**3/48 + O(x**4)
|
2007 |
+
|
2008 |
+
|
2009 |
+
def test_asec_nseries():
|
2010 |
+
assert asec(x + S(1)/2)._eval_nseries(x, 4, None, I) == asec(S(1)/2) - \
|
2011 |
+
4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
|
2012 |
+
assert asec(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -asec(S(1)/2) + \
|
2013 |
+
4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
|
2014 |
+
assert asec(x - S(1)/2)._eval_nseries(x, 4, None, I) == -asec(-S(1)/2) + \
|
2015 |
+
2*pi + 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
|
2016 |
+
assert asec(x - S(1)/2)._eval_nseries(x, 4, None, -I) == asec(-S(1)/2) - \
|
2017 |
+
4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
|
2018 |
+
# testing nseries for asec at branch points
|
2019 |
+
assert asec(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - \
|
2020 |
+
5*sqrt(2)*x**(S(3)/2)/12 + 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
|
2021 |
+
assert asec(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + \
|
2022 |
+
5*sqrt(2)*(-x)**(S(3)/2)/12 - 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
|
2023 |
+
assert asec(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - \
|
2024 |
+
sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3)
|
2025 |
+
assert asec(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) + \
|
2026 |
+
sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3)
|
2027 |
+
|
2028 |
+
|
2029 |
+
def test_acsc_nseries():
|
2030 |
+
assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/2) + \
|
2031 |
+
4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
|
2032 |
+
assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/2) + \
|
2033 |
+
pi - 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
|
2034 |
+
assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/2) - pi -\
|
2035 |
+
4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
|
2036 |
+
assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/2) + \
|
2037 |
+
4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
|
2038 |
+
# testing nseries for acsc at branch points
|
2039 |
+
assert acsc(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + \
|
2040 |
+
5*sqrt(2)*x**(S(3)/2)/12 - 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
|
2041 |
+
assert acsc(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - \
|
2042 |
+
5*sqrt(2)*(-x)**(S(3)/2)/12 + 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
|
2043 |
+
assert acsc(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + \
|
2044 |
+
sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3)
|
2045 |
+
assert acsc(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) - \
|
2046 |
+
sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3)
|
2047 |
+
|
2048 |
+
|
2049 |
+
def test_issue_8653():
|
2050 |
+
n = Symbol('n', integer=True)
|
2051 |
+
assert sin(n).is_irrational is None
|
2052 |
+
assert cos(n).is_irrational is None
|
2053 |
+
assert tan(n).is_irrational is None
|
2054 |
+
|
2055 |
+
|
2056 |
+
def test_issue_9157():
|
2057 |
+
n = Symbol('n', integer=True, positive=True)
|
2058 |
+
assert atan(n - 1).is_nonnegative is True
|
2059 |
+
|
2060 |
+
|
2061 |
+
def test_trig_period():
|
2062 |
+
x, y = symbols('x, y')
|
2063 |
+
|
2064 |
+
assert sin(x).period() == 2*pi
|
2065 |
+
assert cos(x).period() == 2*pi
|
2066 |
+
assert tan(x).period() == pi
|
2067 |
+
assert cot(x).period() == pi
|
2068 |
+
assert sec(x).period() == 2*pi
|
2069 |
+
assert csc(x).period() == 2*pi
|
2070 |
+
assert sin(2*x).period() == pi
|
2071 |
+
assert cot(4*x - 6).period() == pi/4
|
2072 |
+
assert cos((-3)*x).period() == pi*Rational(2, 3)
|
2073 |
+
assert cos(x*y).period(x) == 2*pi/abs(y)
|
2074 |
+
assert sin(3*x*y + 2*pi).period(y) == 2*pi/abs(3*x)
|
2075 |
+
assert tan(3*x).period(y) is S.Zero
|
2076 |
+
raises(NotImplementedError, lambda: sin(x**2).period(x))
|
2077 |
+
|
2078 |
+
|
2079 |
+
def test_issue_7171():
|
2080 |
+
assert sin(x).rewrite(sqrt) == sin(x)
|
2081 |
+
assert sin(x).rewrite(pow) == sin(x)
|
2082 |
+
|
2083 |
+
|
2084 |
+
def test_issue_11864():
|
2085 |
+
w, k = symbols('w, k', real=True)
|
2086 |
+
F = Piecewise((1, Eq(2*pi*k, 0)), (sin(pi*k)/(pi*k), True))
|
2087 |
+
soln = Piecewise((1, Eq(2*pi*k, 0)), (sinc(pi*k), True))
|
2088 |
+
assert F.rewrite(sinc) == soln
|
2089 |
+
|
2090 |
+
def test_real_assumptions():
|
2091 |
+
z = Symbol('z', real=False, finite=True)
|
2092 |
+
assert sin(z).is_real is None
|
2093 |
+
assert cos(z).is_real is None
|
2094 |
+
assert tan(z).is_real is False
|
2095 |
+
assert sec(z).is_real is None
|
2096 |
+
assert csc(z).is_real is None
|
2097 |
+
assert cot(z).is_real is False
|
2098 |
+
assert asin(p).is_real is None
|
2099 |
+
assert asin(n).is_real is None
|
2100 |
+
assert asec(p).is_real is None
|
2101 |
+
assert asec(n).is_real is None
|
2102 |
+
assert acos(p).is_real is None
|
2103 |
+
assert acos(n).is_real is None
|
2104 |
+
assert acsc(p).is_real is None
|
2105 |
+
assert acsc(n).is_real is None
|
2106 |
+
assert atan(p).is_positive is True
|
2107 |
+
assert atan(n).is_negative is True
|
2108 |
+
assert acot(p).is_positive is True
|
2109 |
+
assert acot(n).is_negative is True
|
2110 |
+
|
2111 |
+
def test_issue_14320():
|
2112 |
+
assert asin(sin(2)) == -2 + pi and (-pi/2 <= -2 + pi <= pi/2) and sin(2) == sin(-2 + pi)
|
2113 |
+
assert asin(cos(2)) == -2 + pi/2 and (-pi/2 <= -2 + pi/2 <= pi/2) and cos(2) == sin(-2 + pi/2)
|
2114 |
+
assert acos(sin(2)) == -pi/2 + 2 and (0 <= -pi/2 + 2 <= pi) and sin(2) == cos(-pi/2 + 2)
|
2115 |
+
assert acos(cos(20)) == -6*pi + 20 and (0 <= -6*pi + 20 <= pi) and cos(20) == cos(-6*pi + 20)
|
2116 |
+
assert acos(cos(30)) == -30 + 10*pi and (0 <= -30 + 10*pi <= pi) and cos(30) == cos(-30 + 10*pi)
|
2117 |
+
|
2118 |
+
assert atan(tan(17)) == -5*pi + 17 and (-pi/2 < -5*pi + 17 < pi/2) and tan(17) == tan(-5*pi + 17)
|
2119 |
+
assert atan(tan(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 < pi/2) and tan(15) == tan(-5*pi + 15)
|
2120 |
+
assert atan(cot(12)) == -12 + pi*Rational(7, 2) and (-pi/2 < -12 + pi*Rational(7, 2) < pi/2) and cot(12) == tan(-12 + pi*Rational(7, 2))
|
2121 |
+
assert acot(cot(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 <= pi/2) and cot(15) == cot(-5*pi + 15)
|
2122 |
+
assert acot(tan(19)) == -19 + pi*Rational(13, 2) and (-pi/2 < -19 + pi*Rational(13, 2) <= pi/2) and tan(19) == cot(-19 + pi*Rational(13, 2))
|
2123 |
+
|
2124 |
+
assert asec(sec(11)) == -11 + 4*pi and (0 <= -11 + 4*pi <= pi) and cos(11) == cos(-11 + 4*pi)
|
2125 |
+
assert asec(csc(13)) == -13 + pi*Rational(9, 2) and (0 <= -13 + pi*Rational(9, 2) <= pi) and sin(13) == cos(-13 + pi*Rational(9, 2))
|
2126 |
+
assert acsc(csc(14)) == -4*pi + 14 and (-pi/2 <= -4*pi + 14 <= pi/2) and sin(14) == sin(-4*pi + 14)
|
2127 |
+
assert acsc(sec(10)) == pi*Rational(-7, 2) + 10 and (-pi/2 <= pi*Rational(-7, 2) + 10 <= pi/2) and cos(10) == sin(pi*Rational(-7, 2) + 10)
|
2128 |
+
|
2129 |
+
def test_issue_14543():
|
2130 |
+
assert sec(2*pi + 11) == sec(11)
|
2131 |
+
assert sec(2*pi - 11) == sec(11)
|
2132 |
+
assert sec(pi + 11) == -sec(11)
|
2133 |
+
assert sec(pi - 11) == -sec(11)
|
2134 |
+
|
2135 |
+
assert csc(2*pi + 17) == csc(17)
|
2136 |
+
assert csc(2*pi - 17) == -csc(17)
|
2137 |
+
assert csc(pi + 17) == -csc(17)
|
2138 |
+
assert csc(pi - 17) == csc(17)
|
2139 |
+
|
2140 |
+
x = Symbol('x')
|
2141 |
+
assert csc(pi/2 + x) == sec(x)
|
2142 |
+
assert csc(pi/2 - x) == sec(x)
|
2143 |
+
assert csc(pi*Rational(3, 2) + x) == -sec(x)
|
2144 |
+
assert csc(pi*Rational(3, 2) - x) == -sec(x)
|
2145 |
+
|
2146 |
+
assert sec(pi/2 - x) == csc(x)
|
2147 |
+
assert sec(pi/2 + x) == -csc(x)
|
2148 |
+
assert sec(pi*Rational(3, 2) + x) == csc(x)
|
2149 |
+
assert sec(pi*Rational(3, 2) - x) == -csc(x)
|
2150 |
+
|
2151 |
+
|
2152 |
+
def test_as_real_imag():
|
2153 |
+
# This is for https://github.com/sympy/sympy/issues/17142
|
2154 |
+
# If it start failing again in irrelevant builds or in the master
|
2155 |
+
# please open up the issue again.
|
2156 |
+
expr = atan(I/(I + I*tan(1)))
|
2157 |
+
assert expr.as_real_imag() == (expr, 0)
|
2158 |
+
|
2159 |
+
|
2160 |
+
def test_issue_18746():
|
2161 |
+
e3 = cos(S.Pi*(x/4 + 1/4))
|
2162 |
+
assert e3.period() == 8
|
venv/lib/python3.10/site-packages/sympy/functions/elementary/trigonometric.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.02 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/autowrap.cpython-310.pyc
ADDED
Binary file (36.7 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/codegen.cpython-310.pyc
ADDED
Binary file (63.6 kB). View file
|
|