applied-ai-018 commited on
Commit
ee917cb
·
verified ·
1 Parent(s): 05ac8e8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step80/zero/10.input_layernorm.weight/exp_avg_sq.pt +3 -0
  2. ckpts/universal/global_step80/zero/10.input_layernorm.weight/fp32.pt +3 -0
  3. ckpts/universal/global_step80/zero/4.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
  4. ckpts/universal/global_step80/zero/7.attention.query_key_value.weight/exp_avg_sq.pt +3 -0
  5. ckpts/universal/global_step80/zero/7.attention.query_key_value.weight/fp32.pt +3 -0
  6. venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__init__.py +0 -0
  7. venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_complexes.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_exponential.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_hyperbolic.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_integers.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_interface.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_miscellaneous.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_piecewise.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_trigonometric.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_hyperbolic.py +1460 -0
  17. venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_integers.py +632 -0
  18. venv/lib/python3.10/site-packages/sympy/functions/special/__init__.py +1 -0
  19. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/__init__.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/bessel.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/beta_functions.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/bsplines.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/delta_functions.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/elliptic_integrals.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/error_functions.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/gamma_functions.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/hyper.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/mathieu_functions.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/polynomials.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/singularity_functions.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/spherical_harmonics.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/tensor_functions.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/zeta_functions.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__init__.py +0 -0
  35. venv/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__pycache__/bench_special.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/sympy/functions/special/benchmarks/bench_special.py +8 -0
  37. venv/lib/python3.10/site-packages/sympy/functions/special/bessel.py +2089 -0
  38. venv/lib/python3.10/site-packages/sympy/functions/special/beta_functions.py +389 -0
  39. venv/lib/python3.10/site-packages/sympy/functions/special/bsplines.py +351 -0
  40. venv/lib/python3.10/site-packages/sympy/functions/special/delta_functions.py +664 -0
  41. venv/lib/python3.10/site-packages/sympy/functions/special/elliptic_integrals.py +445 -0
  42. venv/lib/python3.10/site-packages/sympy/functions/special/error_functions.py +2741 -0
  43. venv/lib/python3.10/site-packages/sympy/functions/special/gamma_functions.py +1344 -0
  44. venv/lib/python3.10/site-packages/sympy/functions/special/hyper.py +1152 -0
  45. venv/lib/python3.10/site-packages/sympy/functions/special/mathieu_functions.py +269 -0
  46. venv/lib/python3.10/site-packages/sympy/functions/special/polynomials.py +1447 -0
  47. venv/lib/python3.10/site-packages/sympy/functions/special/singularity_functions.py +228 -0
  48. venv/lib/python3.10/site-packages/sympy/functions/special/spherical_harmonics.py +334 -0
  49. venv/lib/python3.10/site-packages/sympy/functions/special/tensor_functions.py +474 -0
  50. venv/lib/python3.10/site-packages/sympy/functions/special/tests/__init__.py +0 -0
ckpts/universal/global_step80/zero/10.input_layernorm.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e06f9bd0627c0ce83b11242293e5e7b295dfe4c0ee050de30b8865f5c9bdc50b
3
+ size 9387
ckpts/universal/global_step80/zero/10.input_layernorm.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3e04a6dc980b4eac8ab27f660d2db094b83e3ee83e949c489898f5e43fe37d9
3
+ size 9293
ckpts/universal/global_step80/zero/4.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:a13bd8a092b946bf904b3a7bf1136b79b370956c94a24804a8eb42383b3b88df
3
+ size 33555533
ckpts/universal/global_step80/zero/7.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:ac7199243da993215930957771b41533376920e6909bd7be3d33d2c0bc38045e
3
+ size 50332843
ckpts/universal/global_step80/zero/7.attention.query_key_value.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b44fe61276610602de4751a9b16b4722c1ced86e65ef9229e828f7a465e4df49
3
+ size 50332749
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (200 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_complexes.cpython-310.pyc ADDED
Binary file (30.5 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_exponential.cpython-310.pyc ADDED
Binary file (29.6 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_hyperbolic.cpython-310.pyc ADDED
Binary file (54.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_integers.cpython-310.pyc ADDED
Binary file (16.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_interface.cpython-310.pyc ADDED
Binary file (3.11 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_miscellaneous.cpython-310.pyc ADDED
Binary file (15.6 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_piecewise.cpython-310.pyc ADDED
Binary file (54.4 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_trigonometric.cpython-310.pyc ADDED
Binary file (85.4 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_hyperbolic.py ADDED
@@ -0,0 +1,1460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.calculus.accumulationbounds import AccumBounds
2
+ from sympy.core.function import (expand_mul, expand_trig)
3
+ from sympy.core.numbers import (E, I, Integer, Rational, nan, oo, pi, zoo)
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import (Symbol, symbols)
6
+ from sympy.functions.elementary.complexes import (im, re)
7
+ from sympy.functions.elementary.exponential import (exp, log)
8
+ from sympy.functions.elementary.hyperbolic import (acosh, acoth, acsch, asech, asinh, atanh, cosh, coth, csch, sech, sinh, tanh)
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.functions.elementary.trigonometric import (acos, asin, cos, cot, sec, sin, tan)
11
+ from sympy.series.order import O
12
+
13
+ from sympy.core.expr import unchanged
14
+ from sympy.core.function import ArgumentIndexError
15
+ from sympy.testing.pytest import raises
16
+
17
+
18
+ def test_sinh():
19
+ x, y = symbols('x,y')
20
+
21
+ k = Symbol('k', integer=True)
22
+
23
+ assert sinh(nan) is nan
24
+ assert sinh(zoo) is nan
25
+
26
+ assert sinh(oo) is oo
27
+ assert sinh(-oo) is -oo
28
+
29
+ assert sinh(0) == 0
30
+
31
+ assert unchanged(sinh, 1)
32
+ assert sinh(-1) == -sinh(1)
33
+
34
+ assert unchanged(sinh, x)
35
+ assert sinh(-x) == -sinh(x)
36
+
37
+ assert unchanged(sinh, pi)
38
+ assert sinh(-pi) == -sinh(pi)
39
+
40
+ assert unchanged(sinh, 2**1024 * E)
41
+ assert sinh(-2**1024 * E) == -sinh(2**1024 * E)
42
+
43
+ assert sinh(pi*I) == 0
44
+ assert sinh(-pi*I) == 0
45
+ assert sinh(2*pi*I) == 0
46
+ assert sinh(-2*pi*I) == 0
47
+ assert sinh(-3*10**73*pi*I) == 0
48
+ assert sinh(7*10**103*pi*I) == 0
49
+
50
+ assert sinh(pi*I/2) == I
51
+ assert sinh(-pi*I/2) == -I
52
+ assert sinh(pi*I*Rational(5, 2)) == I
53
+ assert sinh(pi*I*Rational(7, 2)) == -I
54
+
55
+ assert sinh(pi*I/3) == S.Half*sqrt(3)*I
56
+ assert sinh(pi*I*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3)*I
57
+
58
+ assert sinh(pi*I/4) == S.Half*sqrt(2)*I
59
+ assert sinh(-pi*I/4) == Rational(-1, 2)*sqrt(2)*I
60
+ assert sinh(pi*I*Rational(17, 4)) == S.Half*sqrt(2)*I
61
+ assert sinh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)*I
62
+
63
+ assert sinh(pi*I/6) == S.Half*I
64
+ assert sinh(-pi*I/6) == Rational(-1, 2)*I
65
+ assert sinh(pi*I*Rational(7, 6)) == Rational(-1, 2)*I
66
+ assert sinh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*I
67
+
68
+ assert sinh(pi*I/105) == sin(pi/105)*I
69
+ assert sinh(-pi*I/105) == -sin(pi/105)*I
70
+
71
+ assert unchanged(sinh, 2 + 3*I)
72
+
73
+ assert sinh(x*I) == sin(x)*I
74
+
75
+ assert sinh(k*pi*I) == 0
76
+ assert sinh(17*k*pi*I) == 0
77
+
78
+ assert sinh(k*pi*I/2) == sin(k*pi/2)*I
79
+
80
+ assert sinh(x).as_real_imag(deep=False) == (cos(im(x))*sinh(re(x)),
81
+ sin(im(x))*cosh(re(x)))
82
+ x = Symbol('x', extended_real=True)
83
+ assert sinh(x).as_real_imag(deep=False) == (sinh(x), 0)
84
+
85
+ x = Symbol('x', real=True)
86
+ assert sinh(I*x).is_finite is True
87
+ assert sinh(x).is_real is True
88
+ assert sinh(I).is_real is False
89
+ p = Symbol('p', positive=True)
90
+ assert sinh(p).is_zero is False
91
+ assert sinh(0, evaluate=False).is_zero is True
92
+ assert sinh(2*pi*I, evaluate=False).is_zero is True
93
+
94
+
95
+ def test_sinh_series():
96
+ x = Symbol('x')
97
+ assert sinh(x).series(x, 0, 10) == \
98
+ x + x**3/6 + x**5/120 + x**7/5040 + x**9/362880 + O(x**10)
99
+
100
+
101
+ def test_sinh_fdiff():
102
+ x = Symbol('x')
103
+ raises(ArgumentIndexError, lambda: sinh(x).fdiff(2))
104
+
105
+
106
+ def test_cosh():
107
+ x, y = symbols('x,y')
108
+
109
+ k = Symbol('k', integer=True)
110
+
111
+ assert cosh(nan) is nan
112
+ assert cosh(zoo) is nan
113
+
114
+ assert cosh(oo) is oo
115
+ assert cosh(-oo) is oo
116
+
117
+ assert cosh(0) == 1
118
+
119
+ assert unchanged(cosh, 1)
120
+ assert cosh(-1) == cosh(1)
121
+
122
+ assert unchanged(cosh, x)
123
+ assert cosh(-x) == cosh(x)
124
+
125
+ assert cosh(pi*I) == cos(pi)
126
+ assert cosh(-pi*I) == cos(pi)
127
+
128
+ assert unchanged(cosh, 2**1024 * E)
129
+ assert cosh(-2**1024 * E) == cosh(2**1024 * E)
130
+
131
+ assert cosh(pi*I/2) == 0
132
+ assert cosh(-pi*I/2) == 0
133
+ assert cosh((-3*10**73 + 1)*pi*I/2) == 0
134
+ assert cosh((7*10**103 + 1)*pi*I/2) == 0
135
+
136
+ assert cosh(pi*I) == -1
137
+ assert cosh(-pi*I) == -1
138
+ assert cosh(5*pi*I) == -1
139
+ assert cosh(8*pi*I) == 1
140
+
141
+ assert cosh(pi*I/3) == S.Half
142
+ assert cosh(pi*I*Rational(-2, 3)) == Rational(-1, 2)
143
+
144
+ assert cosh(pi*I/4) == S.Half*sqrt(2)
145
+ assert cosh(-pi*I/4) == S.Half*sqrt(2)
146
+ assert cosh(pi*I*Rational(11, 4)) == Rational(-1, 2)*sqrt(2)
147
+ assert cosh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
148
+
149
+ assert cosh(pi*I/6) == S.Half*sqrt(3)
150
+ assert cosh(-pi*I/6) == S.Half*sqrt(3)
151
+ assert cosh(pi*I*Rational(7, 6)) == Rational(-1, 2)*sqrt(3)
152
+ assert cosh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3)
153
+
154
+ assert cosh(pi*I/105) == cos(pi/105)
155
+ assert cosh(-pi*I/105) == cos(pi/105)
156
+
157
+ assert unchanged(cosh, 2 + 3*I)
158
+
159
+ assert cosh(x*I) == cos(x)
160
+
161
+ assert cosh(k*pi*I) == cos(k*pi)
162
+ assert cosh(17*k*pi*I) == cos(17*k*pi)
163
+
164
+ assert unchanged(cosh, k*pi)
165
+
166
+ assert cosh(x).as_real_imag(deep=False) == (cos(im(x))*cosh(re(x)),
167
+ sin(im(x))*sinh(re(x)))
168
+ x = Symbol('x', extended_real=True)
169
+ assert cosh(x).as_real_imag(deep=False) == (cosh(x), 0)
170
+
171
+ x = Symbol('x', real=True)
172
+ assert cosh(I*x).is_finite is True
173
+ assert cosh(I*x).is_real is True
174
+ assert cosh(I*2 + 1).is_real is False
175
+ assert cosh(5*I*S.Pi/2, evaluate=False).is_zero is True
176
+ assert cosh(x).is_zero is False
177
+
178
+
179
+ def test_cosh_series():
180
+ x = Symbol('x')
181
+ assert cosh(x).series(x, 0, 10) == \
182
+ 1 + x**2/2 + x**4/24 + x**6/720 + x**8/40320 + O(x**10)
183
+
184
+
185
+ def test_cosh_fdiff():
186
+ x = Symbol('x')
187
+ raises(ArgumentIndexError, lambda: cosh(x).fdiff(2))
188
+
189
+
190
+ def test_tanh():
191
+ x, y = symbols('x,y')
192
+
193
+ k = Symbol('k', integer=True)
194
+
195
+ assert tanh(nan) is nan
196
+ assert tanh(zoo) is nan
197
+
198
+ assert tanh(oo) == 1
199
+ assert tanh(-oo) == -1
200
+
201
+ assert tanh(0) == 0
202
+
203
+ assert unchanged(tanh, 1)
204
+ assert tanh(-1) == -tanh(1)
205
+
206
+ assert unchanged(tanh, x)
207
+ assert tanh(-x) == -tanh(x)
208
+
209
+ assert unchanged(tanh, pi)
210
+ assert tanh(-pi) == -tanh(pi)
211
+
212
+ assert unchanged(tanh, 2**1024 * E)
213
+ assert tanh(-2**1024 * E) == -tanh(2**1024 * E)
214
+
215
+ assert tanh(pi*I) == 0
216
+ assert tanh(-pi*I) == 0
217
+ assert tanh(2*pi*I) == 0
218
+ assert tanh(-2*pi*I) == 0
219
+ assert tanh(-3*10**73*pi*I) == 0
220
+ assert tanh(7*10**103*pi*I) == 0
221
+
222
+ assert tanh(pi*I/2) is zoo
223
+ assert tanh(-pi*I/2) is zoo
224
+ assert tanh(pi*I*Rational(5, 2)) is zoo
225
+ assert tanh(pi*I*Rational(7, 2)) is zoo
226
+
227
+ assert tanh(pi*I/3) == sqrt(3)*I
228
+ assert tanh(pi*I*Rational(-2, 3)) == sqrt(3)*I
229
+
230
+ assert tanh(pi*I/4) == I
231
+ assert tanh(-pi*I/4) == -I
232
+ assert tanh(pi*I*Rational(17, 4)) == I
233
+ assert tanh(pi*I*Rational(-3, 4)) == I
234
+
235
+ assert tanh(pi*I/6) == I/sqrt(3)
236
+ assert tanh(-pi*I/6) == -I/sqrt(3)
237
+ assert tanh(pi*I*Rational(7, 6)) == I/sqrt(3)
238
+ assert tanh(pi*I*Rational(-5, 6)) == I/sqrt(3)
239
+
240
+ assert tanh(pi*I/105) == tan(pi/105)*I
241
+ assert tanh(-pi*I/105) == -tan(pi/105)*I
242
+
243
+ assert unchanged(tanh, 2 + 3*I)
244
+
245
+ assert tanh(x*I) == tan(x)*I
246
+
247
+ assert tanh(k*pi*I) == 0
248
+ assert tanh(17*k*pi*I) == 0
249
+
250
+ assert tanh(k*pi*I/2) == tan(k*pi/2)*I
251
+
252
+ assert tanh(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(cos(im(x))**2
253
+ + sinh(re(x))**2),
254
+ sin(im(x))*cos(im(x))/(cos(im(x))**2 + sinh(re(x))**2))
255
+ x = Symbol('x', extended_real=True)
256
+ assert tanh(x).as_real_imag(deep=False) == (tanh(x), 0)
257
+ assert tanh(I*pi/3 + 1).is_real is False
258
+ assert tanh(x).is_real is True
259
+ assert tanh(I*pi*x/2).is_real is None
260
+
261
+
262
+ def test_tanh_series():
263
+ x = Symbol('x')
264
+ assert tanh(x).series(x, 0, 10) == \
265
+ x - x**3/3 + 2*x**5/15 - 17*x**7/315 + 62*x**9/2835 + O(x**10)
266
+
267
+
268
+ def test_tanh_fdiff():
269
+ x = Symbol('x')
270
+ raises(ArgumentIndexError, lambda: tanh(x).fdiff(2))
271
+
272
+
273
+ def test_coth():
274
+ x, y = symbols('x,y')
275
+
276
+ k = Symbol('k', integer=True)
277
+
278
+ assert coth(nan) is nan
279
+ assert coth(zoo) is nan
280
+
281
+ assert coth(oo) == 1
282
+ assert coth(-oo) == -1
283
+
284
+ assert coth(0) is zoo
285
+ assert unchanged(coth, 1)
286
+ assert coth(-1) == -coth(1)
287
+
288
+ assert unchanged(coth, x)
289
+ assert coth(-x) == -coth(x)
290
+
291
+ assert coth(pi*I) == -I*cot(pi)
292
+ assert coth(-pi*I) == cot(pi)*I
293
+
294
+ assert unchanged(coth, 2**1024 * E)
295
+ assert coth(-2**1024 * E) == -coth(2**1024 * E)
296
+
297
+ assert coth(pi*I) == -I*cot(pi)
298
+ assert coth(-pi*I) == I*cot(pi)
299
+ assert coth(2*pi*I) == -I*cot(2*pi)
300
+ assert coth(-2*pi*I) == I*cot(2*pi)
301
+ assert coth(-3*10**73*pi*I) == I*cot(3*10**73*pi)
302
+ assert coth(7*10**103*pi*I) == -I*cot(7*10**103*pi)
303
+
304
+ assert coth(pi*I/2) == 0
305
+ assert coth(-pi*I/2) == 0
306
+ assert coth(pi*I*Rational(5, 2)) == 0
307
+ assert coth(pi*I*Rational(7, 2)) == 0
308
+
309
+ assert coth(pi*I/3) == -I/sqrt(3)
310
+ assert coth(pi*I*Rational(-2, 3)) == -I/sqrt(3)
311
+
312
+ assert coth(pi*I/4) == -I
313
+ assert coth(-pi*I/4) == I
314
+ assert coth(pi*I*Rational(17, 4)) == -I
315
+ assert coth(pi*I*Rational(-3, 4)) == -I
316
+
317
+ assert coth(pi*I/6) == -sqrt(3)*I
318
+ assert coth(-pi*I/6) == sqrt(3)*I
319
+ assert coth(pi*I*Rational(7, 6)) == -sqrt(3)*I
320
+ assert coth(pi*I*Rational(-5, 6)) == -sqrt(3)*I
321
+
322
+ assert coth(pi*I/105) == -cot(pi/105)*I
323
+ assert coth(-pi*I/105) == cot(pi/105)*I
324
+
325
+ assert unchanged(coth, 2 + 3*I)
326
+
327
+ assert coth(x*I) == -cot(x)*I
328
+
329
+ assert coth(k*pi*I) == -cot(k*pi)*I
330
+ assert coth(17*k*pi*I) == -cot(17*k*pi)*I
331
+
332
+ assert coth(k*pi*I) == -cot(k*pi)*I
333
+
334
+ assert coth(log(tan(2))) == coth(log(-tan(2)))
335
+ assert coth(1 + I*pi/2) == tanh(1)
336
+
337
+ assert coth(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(sin(im(x))**2
338
+ + sinh(re(x))**2),
339
+ -sin(im(x))*cos(im(x))/(sin(im(x))**2 + sinh(re(x))**2))
340
+ x = Symbol('x', extended_real=True)
341
+ assert coth(x).as_real_imag(deep=False) == (coth(x), 0)
342
+
343
+ assert expand_trig(coth(2*x)) == (coth(x)**2 + 1)/(2*coth(x))
344
+ assert expand_trig(coth(3*x)) == (coth(x)**3 + 3*coth(x))/(1 + 3*coth(x)**2)
345
+
346
+ assert expand_trig(coth(x + y)) == (1 + coth(x)*coth(y))/(coth(x) + coth(y))
347
+
348
+
349
+ def test_coth_series():
350
+ x = Symbol('x')
351
+ assert coth(x).series(x, 0, 8) == \
352
+ 1/x + x/3 - x**3/45 + 2*x**5/945 - x**7/4725 + O(x**8)
353
+
354
+
355
+ def test_coth_fdiff():
356
+ x = Symbol('x')
357
+ raises(ArgumentIndexError, lambda: coth(x).fdiff(2))
358
+
359
+
360
+ def test_csch():
361
+ x, y = symbols('x,y')
362
+
363
+ k = Symbol('k', integer=True)
364
+ n = Symbol('n', positive=True)
365
+
366
+ assert csch(nan) is nan
367
+ assert csch(zoo) is nan
368
+
369
+ assert csch(oo) == 0
370
+ assert csch(-oo) == 0
371
+
372
+ assert csch(0) is zoo
373
+
374
+ assert csch(-1) == -csch(1)
375
+
376
+ assert csch(-x) == -csch(x)
377
+ assert csch(-pi) == -csch(pi)
378
+ assert csch(-2**1024 * E) == -csch(2**1024 * E)
379
+
380
+ assert csch(pi*I) is zoo
381
+ assert csch(-pi*I) is zoo
382
+ assert csch(2*pi*I) is zoo
383
+ assert csch(-2*pi*I) is zoo
384
+ assert csch(-3*10**73*pi*I) is zoo
385
+ assert csch(7*10**103*pi*I) is zoo
386
+
387
+ assert csch(pi*I/2) == -I
388
+ assert csch(-pi*I/2) == I
389
+ assert csch(pi*I*Rational(5, 2)) == -I
390
+ assert csch(pi*I*Rational(7, 2)) == I
391
+
392
+ assert csch(pi*I/3) == -2/sqrt(3)*I
393
+ assert csch(pi*I*Rational(-2, 3)) == 2/sqrt(3)*I
394
+
395
+ assert csch(pi*I/4) == -sqrt(2)*I
396
+ assert csch(-pi*I/4) == sqrt(2)*I
397
+ assert csch(pi*I*Rational(7, 4)) == sqrt(2)*I
398
+ assert csch(pi*I*Rational(-3, 4)) == sqrt(2)*I
399
+
400
+ assert csch(pi*I/6) == -2*I
401
+ assert csch(-pi*I/6) == 2*I
402
+ assert csch(pi*I*Rational(7, 6)) == 2*I
403
+ assert csch(pi*I*Rational(-7, 6)) == -2*I
404
+ assert csch(pi*I*Rational(-5, 6)) == 2*I
405
+
406
+ assert csch(pi*I/105) == -1/sin(pi/105)*I
407
+ assert csch(-pi*I/105) == 1/sin(pi/105)*I
408
+
409
+ assert csch(x*I) == -1/sin(x)*I
410
+
411
+ assert csch(k*pi*I) is zoo
412
+ assert csch(17*k*pi*I) is zoo
413
+
414
+ assert csch(k*pi*I/2) == -1/sin(k*pi/2)*I
415
+
416
+ assert csch(n).is_real is True
417
+
418
+ assert expand_trig(csch(x + y)) == 1/(sinh(x)*cosh(y) + cosh(x)*sinh(y))
419
+
420
+
421
+ def test_csch_series():
422
+ x = Symbol('x')
423
+ assert csch(x).series(x, 0, 10) == \
424
+ 1/ x - x/6 + 7*x**3/360 - 31*x**5/15120 + 127*x**7/604800 \
425
+ - 73*x**9/3421440 + O(x**10)
426
+
427
+
428
+ def test_csch_fdiff():
429
+ x = Symbol('x')
430
+ raises(ArgumentIndexError, lambda: csch(x).fdiff(2))
431
+
432
+
433
+ def test_sech():
434
+ x, y = symbols('x, y')
435
+
436
+ k = Symbol('k', integer=True)
437
+ n = Symbol('n', positive=True)
438
+
439
+ assert sech(nan) is nan
440
+ assert sech(zoo) is nan
441
+
442
+ assert sech(oo) == 0
443
+ assert sech(-oo) == 0
444
+
445
+ assert sech(0) == 1
446
+
447
+ assert sech(-1) == sech(1)
448
+ assert sech(-x) == sech(x)
449
+
450
+ assert sech(pi*I) == sec(pi)
451
+
452
+ assert sech(-pi*I) == sec(pi)
453
+ assert sech(-2**1024 * E) == sech(2**1024 * E)
454
+
455
+ assert sech(pi*I/2) is zoo
456
+ assert sech(-pi*I/2) is zoo
457
+ assert sech((-3*10**73 + 1)*pi*I/2) is zoo
458
+ assert sech((7*10**103 + 1)*pi*I/2) is zoo
459
+
460
+ assert sech(pi*I) == -1
461
+ assert sech(-pi*I) == -1
462
+ assert sech(5*pi*I) == -1
463
+ assert sech(8*pi*I) == 1
464
+
465
+ assert sech(pi*I/3) == 2
466
+ assert sech(pi*I*Rational(-2, 3)) == -2
467
+
468
+ assert sech(pi*I/4) == sqrt(2)
469
+ assert sech(-pi*I/4) == sqrt(2)
470
+ assert sech(pi*I*Rational(5, 4)) == -sqrt(2)
471
+ assert sech(pi*I*Rational(-5, 4)) == -sqrt(2)
472
+
473
+ assert sech(pi*I/6) == 2/sqrt(3)
474
+ assert sech(-pi*I/6) == 2/sqrt(3)
475
+ assert sech(pi*I*Rational(7, 6)) == -2/sqrt(3)
476
+ assert sech(pi*I*Rational(-5, 6)) == -2/sqrt(3)
477
+
478
+ assert sech(pi*I/105) == 1/cos(pi/105)
479
+ assert sech(-pi*I/105) == 1/cos(pi/105)
480
+
481
+ assert sech(x*I) == 1/cos(x)
482
+
483
+ assert sech(k*pi*I) == 1/cos(k*pi)
484
+ assert sech(17*k*pi*I) == 1/cos(17*k*pi)
485
+
486
+ assert sech(n).is_real is True
487
+
488
+ assert expand_trig(sech(x + y)) == 1/(cosh(x)*cosh(y) + sinh(x)*sinh(y))
489
+
490
+
491
+ def test_sech_series():
492
+ x = Symbol('x')
493
+ assert sech(x).series(x, 0, 10) == \
494
+ 1 - x**2/2 + 5*x**4/24 - 61*x**6/720 + 277*x**8/8064 + O(x**10)
495
+
496
+
497
+ def test_sech_fdiff():
498
+ x = Symbol('x')
499
+ raises(ArgumentIndexError, lambda: sech(x).fdiff(2))
500
+
501
+
502
+ def test_asinh():
503
+ x, y = symbols('x,y')
504
+ assert unchanged(asinh, x)
505
+ assert asinh(-x) == -asinh(x)
506
+
507
+ #at specific points
508
+ assert asinh(nan) is nan
509
+ assert asinh( 0) == 0
510
+ assert asinh(+1) == log(sqrt(2) + 1)
511
+
512
+ assert asinh(-1) == log(sqrt(2) - 1)
513
+ assert asinh(I) == pi*I/2
514
+ assert asinh(-I) == -pi*I/2
515
+ assert asinh(I/2) == pi*I/6
516
+ assert asinh(-I/2) == -pi*I/6
517
+
518
+ # at infinites
519
+ assert asinh(oo) is oo
520
+ assert asinh(-oo) is -oo
521
+
522
+ assert asinh(I*oo) is oo
523
+ assert asinh(-I *oo) is -oo
524
+
525
+ assert asinh(zoo) is zoo
526
+
527
+ #properties
528
+ assert asinh(I *(sqrt(3) - 1)/(2**Rational(3, 2))) == pi*I/12
529
+ assert asinh(-I *(sqrt(3) - 1)/(2**Rational(3, 2))) == -pi*I/12
530
+
531
+ assert asinh(I*(sqrt(5) - 1)/4) == pi*I/10
532
+ assert asinh(-I*(sqrt(5) - 1)/4) == -pi*I/10
533
+
534
+ assert asinh(I*(sqrt(5) + 1)/4) == pi*I*Rational(3, 10)
535
+ assert asinh(-I*(sqrt(5) + 1)/4) == pi*I*Rational(-3, 10)
536
+
537
+ # Symmetry
538
+ assert asinh(Rational(-1, 2)) == -asinh(S.Half)
539
+
540
+ # inverse composition
541
+ assert unchanged(asinh, sinh(Symbol('v1')))
542
+
543
+ assert asinh(sinh(0, evaluate=False)) == 0
544
+ assert asinh(sinh(-3, evaluate=False)) == -3
545
+ assert asinh(sinh(2, evaluate=False)) == 2
546
+ assert asinh(sinh(I, evaluate=False)) == I
547
+ assert asinh(sinh(-I, evaluate=False)) == -I
548
+ assert asinh(sinh(5*I, evaluate=False)) == -2*I*pi + 5*I
549
+ assert asinh(sinh(15 + 11*I)) == 15 - 4*I*pi + 11*I
550
+ assert asinh(sinh(-73 + 97*I)) == 73 - 97*I + 31*I*pi
551
+ assert asinh(sinh(-7 - 23*I)) == 7 - 7*I*pi + 23*I
552
+ assert asinh(sinh(13 - 3*I)) == -13 - I*pi + 3*I
553
+ p = Symbol('p', positive=True)
554
+ assert asinh(p).is_zero is False
555
+ assert asinh(sinh(0, evaluate=False), evaluate=False).is_zero is True
556
+
557
+
558
+ def test_asinh_rewrite():
559
+ x = Symbol('x')
560
+ assert asinh(x).rewrite(log) == log(x + sqrt(x**2 + 1))
561
+ assert asinh(x).rewrite(atanh) == atanh(x/sqrt(1 + x**2))
562
+ assert asinh(x).rewrite(asin) == asinh(x)
563
+ assert asinh(x*(1 + I)).rewrite(asin) == -I*asin(I*x*(1+I))
564
+ assert asinh(x).rewrite(acos) == I*(-I*asinh(x) + pi/2) - I*pi/2
565
+
566
+
567
+ def test_asinh_leading_term():
568
+ x = Symbol('x')
569
+ assert asinh(x).as_leading_term(x, cdir=1) == x
570
+ # Tests concerning branch points
571
+ assert asinh(x + I).as_leading_term(x, cdir=1) == I*pi/2
572
+ assert asinh(x - I).as_leading_term(x, cdir=1) == -I*pi/2
573
+ assert asinh(1/x).as_leading_term(x, cdir=1) == -log(x) + log(2)
574
+ assert asinh(1/x).as_leading_term(x, cdir=-1) == log(x) - log(2) - I*pi
575
+ # Tests concerning points lying on branch cuts
576
+ assert asinh(x + 2*I).as_leading_term(x, cdir=1) == I*asin(2)
577
+ assert asinh(x + 2*I).as_leading_term(x, cdir=-1) == -I*asin(2) + I*pi
578
+ assert asinh(x - 2*I).as_leading_term(x, cdir=1) == -I*pi + I*asin(2)
579
+ assert asinh(x - 2*I).as_leading_term(x, cdir=-1) == -I*asin(2)
580
+ # Tests concerning re(ndir) == 0
581
+ assert asinh(2*I + I*x - x**2).as_leading_term(x, cdir=1) == log(2 - sqrt(3)) + I*pi/2
582
+ assert asinh(2*I + I*x - x**2).as_leading_term(x, cdir=-1) == log(2 - sqrt(3)) + I*pi/2
583
+
584
+
585
+ def test_asinh_series():
586
+ x = Symbol('x')
587
+ assert asinh(x).series(x, 0, 8) == \
588
+ x - x**3/6 + 3*x**5/40 - 5*x**7/112 + O(x**8)
589
+ t5 = asinh(x).taylor_term(5, x)
590
+ assert t5 == 3*x**5/40
591
+ assert asinh(x).taylor_term(7, x, t5, 0) == -5*x**7/112
592
+
593
+
594
+ def test_asinh_nseries():
595
+ x = Symbol('x')
596
+ # Tests concerning branch points
597
+ assert asinh(x + I)._eval_nseries(x, 4, None) == I*pi/2 + \
598
+ sqrt(x)*(1 - I) + x**(S(3)/2)*(S(1)/12 + I/12) + x**(S(5)/2)*(-S(3)/160 + 3*I/160) + \
599
+ x**(S(7)/2)*(-S(5)/896 - 5*I/896) + O(x**4)
600
+ assert asinh(x - I)._eval_nseries(x, 4, None) == -I*pi/2 + \
601
+ sqrt(x)*(1 + I) + x**(S(3)/2)*(S(1)/12 - I/12) + x**(S(5)/2)*(-S(3)/160 - 3*I/160) + \
602
+ x**(S(7)/2)*(-S(5)/896 + 5*I/896) + O(x**4)
603
+ # Tests concerning points lying on branch cuts
604
+ assert asinh(x + 2*I)._eval_nseries(x, 4, None, cdir=1) == I*asin(2) - \
605
+ sqrt(3)*I*x/3 + sqrt(3)*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
606
+ assert asinh(x + 2*I)._eval_nseries(x, 4, None, cdir=-1) == I*pi - I*asin(2) + \
607
+ sqrt(3)*I*x/3 - sqrt(3)*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
608
+ assert asinh(x - 2*I)._eval_nseries(x, 4, None, cdir=1) == I*asin(2) - I*pi + \
609
+ sqrt(3)*I*x/3 + sqrt(3)*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
610
+ assert asinh(x - 2*I)._eval_nseries(x, 4, None, cdir=-1) == -I*asin(2) - \
611
+ sqrt(3)*I*x/3 - sqrt(3)*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
612
+ # Tests concerning re(ndir) == 0
613
+ assert asinh(2*I + I*x - x**2)._eval_nseries(x, 4, None) == I*pi/2 + log(2 - sqrt(3)) - \
614
+ sqrt(3)*x/3 + x**2*(sqrt(3)/9 - sqrt(3)*I/3) + x**3*(-sqrt(3)/18 + 2*sqrt(3)*I/9) + O(x**4)
615
+
616
+
617
+ def test_asinh_fdiff():
618
+ x = Symbol('x')
619
+ raises(ArgumentIndexError, lambda: asinh(x).fdiff(2))
620
+
621
+
622
+ def test_acosh():
623
+ x = Symbol('x')
624
+
625
+ assert unchanged(acosh, -x)
626
+
627
+ #at specific points
628
+ assert acosh(1) == 0
629
+ assert acosh(-1) == pi*I
630
+ assert acosh(0) == I*pi/2
631
+ assert acosh(S.Half) == I*pi/3
632
+ assert acosh(Rational(-1, 2)) == pi*I*Rational(2, 3)
633
+ assert acosh(nan) is nan
634
+
635
+ # at infinites
636
+ assert acosh(oo) is oo
637
+ assert acosh(-oo) is oo
638
+
639
+ assert acosh(I*oo) == oo + I*pi/2
640
+ assert acosh(-I*oo) == oo - I*pi/2
641
+
642
+ assert acosh(zoo) is zoo
643
+
644
+ assert acosh(I) == log(I*(1 + sqrt(2)))
645
+ assert acosh(-I) == log(-I*(1 + sqrt(2)))
646
+ assert acosh((sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(5, 12)
647
+ assert acosh(-(sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(7, 12)
648
+ assert acosh(sqrt(2)/2) == I*pi/4
649
+ assert acosh(-sqrt(2)/2) == I*pi*Rational(3, 4)
650
+ assert acosh(sqrt(3)/2) == I*pi/6
651
+ assert acosh(-sqrt(3)/2) == I*pi*Rational(5, 6)
652
+ assert acosh(sqrt(2 + sqrt(2))/2) == I*pi/8
653
+ assert acosh(-sqrt(2 + sqrt(2))/2) == I*pi*Rational(7, 8)
654
+ assert acosh(sqrt(2 - sqrt(2))/2) == I*pi*Rational(3, 8)
655
+ assert acosh(-sqrt(2 - sqrt(2))/2) == I*pi*Rational(5, 8)
656
+ assert acosh((1 + sqrt(3))/(2*sqrt(2))) == I*pi/12
657
+ assert acosh(-(1 + sqrt(3))/(2*sqrt(2))) == I*pi*Rational(11, 12)
658
+ assert acosh((sqrt(5) + 1)/4) == I*pi/5
659
+ assert acosh(-(sqrt(5) + 1)/4) == I*pi*Rational(4, 5)
660
+
661
+ assert str(acosh(5*I).n(6)) == '2.31244 + 1.5708*I'
662
+ assert str(acosh(-5*I).n(6)) == '2.31244 - 1.5708*I'
663
+
664
+ # inverse composition
665
+ assert unchanged(acosh, Symbol('v1'))
666
+
667
+ assert acosh(cosh(-3, evaluate=False)) == 3
668
+ assert acosh(cosh(3, evaluate=False)) == 3
669
+ assert acosh(cosh(0, evaluate=False)) == 0
670
+ assert acosh(cosh(I, evaluate=False)) == I
671
+ assert acosh(cosh(-I, evaluate=False)) == I
672
+ assert acosh(cosh(7*I, evaluate=False)) == -2*I*pi + 7*I
673
+ assert acosh(cosh(1 + I)) == 1 + I
674
+ assert acosh(cosh(3 - 3*I)) == 3 - 3*I
675
+ assert acosh(cosh(-3 + 2*I)) == 3 - 2*I
676
+ assert acosh(cosh(-5 - 17*I)) == 5 - 6*I*pi + 17*I
677
+ assert acosh(cosh(-21 + 11*I)) == 21 - 11*I + 4*I*pi
678
+ assert acosh(cosh(cosh(1) + I)) == cosh(1) + I
679
+ assert acosh(1, evaluate=False).is_zero is True
680
+
681
+
682
+ def test_acosh_rewrite():
683
+ x = Symbol('x')
684
+ assert acosh(x).rewrite(log) == log(x + sqrt(x - 1)*sqrt(x + 1))
685
+ assert acosh(x).rewrite(asin) == sqrt(x - 1)*(-asin(x) + pi/2)/sqrt(1 - x)
686
+ assert acosh(x).rewrite(asinh) == sqrt(x - 1)*(-asin(x) + pi/2)/sqrt(1 - x)
687
+ assert acosh(x).rewrite(atanh) == \
688
+ (sqrt(x - 1)*sqrt(x + 1)*atanh(sqrt(x**2 - 1)/x)/sqrt(x**2 - 1) +
689
+ pi*sqrt(x - 1)*(-x*sqrt(x**(-2)) + 1)/(2*sqrt(1 - x)))
690
+ x = Symbol('x', positive=True)
691
+ assert acosh(x).rewrite(atanh) == \
692
+ sqrt(x - 1)*sqrt(x + 1)*atanh(sqrt(x**2 - 1)/x)/sqrt(x**2 - 1)
693
+
694
+
695
+ def test_acosh_leading_term():
696
+ x = Symbol('x')
697
+ # Tests concerning branch points
698
+ assert acosh(x).as_leading_term(x) == I*pi/2
699
+ assert acosh(x + 1).as_leading_term(x) == sqrt(2)*sqrt(x)
700
+ assert acosh(x - 1).as_leading_term(x) == I*pi
701
+ assert acosh(1/x).as_leading_term(x, cdir=1) == -log(x) + log(2)
702
+ assert acosh(1/x).as_leading_term(x, cdir=-1) == -log(x) + log(2) + 2*I*pi
703
+ # Tests concerning points lying on branch cuts
704
+ assert acosh(I*x - 2).as_leading_term(x, cdir=1) == acosh(-2)
705
+ assert acosh(-I*x - 2).as_leading_term(x, cdir=1) == -2*I*pi + acosh(-2)
706
+ assert acosh(x**2 - I*x + S(1)/3).as_leading_term(x, cdir=1) == -acosh(S(1)/3)
707
+ assert acosh(x**2 - I*x + S(1)/3).as_leading_term(x, cdir=-1) == acosh(S(1)/3)
708
+ assert acosh(1/(I*x - 3)).as_leading_term(x, cdir=1) == -acosh(-S(1)/3)
709
+ assert acosh(1/(I*x - 3)).as_leading_term(x, cdir=-1) == acosh(-S(1)/3)
710
+ # Tests concerning im(ndir) == 0
711
+ assert acosh(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == log(sqrt(3) + 2) - I*pi
712
+ assert acosh(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == log(sqrt(3) + 2) - I*pi
713
+
714
+
715
+ def test_acosh_series():
716
+ x = Symbol('x')
717
+ assert acosh(x).series(x, 0, 8) == \
718
+ -I*x + pi*I/2 - I*x**3/6 - 3*I*x**5/40 - 5*I*x**7/112 + O(x**8)
719
+ t5 = acosh(x).taylor_term(5, x)
720
+ assert t5 == - 3*I*x**5/40
721
+ assert acosh(x).taylor_term(7, x, t5, 0) == - 5*I*x**7/112
722
+
723
+
724
+ def test_acosh_nseries():
725
+ x = Symbol('x')
726
+ # Tests concerning branch points
727
+ assert acosh(x + 1)._eval_nseries(x, 4, None) == sqrt(2)*sqrt(x) - \
728
+ sqrt(2)*x**(S(3)/2)/12 + 3*sqrt(2)*x**(S(5)/2)/160 - 5*sqrt(2)*x**(S(7)/2)/896 + O(x**4)
729
+ # Tests concerning points lying on branch cuts
730
+ assert acosh(x - 1)._eval_nseries(x, 4, None) == I*pi - \
731
+ sqrt(2)*I*sqrt(x) - sqrt(2)*I*x**(S(3)/2)/12 - 3*sqrt(2)*I*x**(S(5)/2)/160 - \
732
+ 5*sqrt(2)*I*x**(S(7)/2)/896 + O(x**4)
733
+ assert acosh(I*x - 2)._eval_nseries(x, 4, None, cdir=1) == acosh(-2) - \
734
+ sqrt(3)*I*x/3 + sqrt(3)*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
735
+ assert acosh(-I*x - 2)._eval_nseries(x, 4, None, cdir=1) == acosh(-2) - \
736
+ 2*I*pi + sqrt(3)*I*x/3 + sqrt(3)*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
737
+ assert acosh(1/(I*x - 3))._eval_nseries(x, 4, None, cdir=1) == -acosh(-S(1)/3) + \
738
+ sqrt(2)*x/12 + 17*sqrt(2)*I*x**2/576 - 443*sqrt(2)*x**3/41472 + O(x**4)
739
+ assert acosh(1/(I*x - 3))._eval_nseries(x, 4, None, cdir=-1) == acosh(-S(1)/3) - \
740
+ sqrt(2)*x/12 - 17*sqrt(2)*I*x**2/576 + 443*sqrt(2)*x**3/41472 + O(x**4)
741
+ # Tests concerning im(ndir) == 0
742
+ assert acosh(-I*x**2 + x - 2)._eval_nseries(x, 4, None) == -I*pi + log(sqrt(3) + 2) - \
743
+ sqrt(3)*x/3 + x**2*(-sqrt(3)/9 + sqrt(3)*I/3) + x**3*(-sqrt(3)/18 + 2*sqrt(3)*I/9) + O(x**4)
744
+
745
+
746
+ def test_acosh_fdiff():
747
+ x = Symbol('x')
748
+ raises(ArgumentIndexError, lambda: acosh(x).fdiff(2))
749
+
750
+
751
+ def test_asech():
752
+ x = Symbol('x')
753
+
754
+ assert unchanged(asech, -x)
755
+
756
+ # values at fixed points
757
+ assert asech(1) == 0
758
+ assert asech(-1) == pi*I
759
+ assert asech(0) is oo
760
+ assert asech(2) == I*pi/3
761
+ assert asech(-2) == 2*I*pi / 3
762
+ assert asech(nan) is nan
763
+
764
+ # at infinites
765
+ assert asech(oo) == I*pi/2
766
+ assert asech(-oo) == I*pi/2
767
+ assert asech(zoo) == I*AccumBounds(-pi/2, pi/2)
768
+
769
+ assert asech(I) == log(1 + sqrt(2)) - I*pi/2
770
+ assert asech(-I) == log(1 + sqrt(2)) + I*pi/2
771
+ assert asech(sqrt(2) - sqrt(6)) == 11*I*pi / 12
772
+ assert asech(sqrt(2 - 2/sqrt(5))) == I*pi / 10
773
+ assert asech(-sqrt(2 - 2/sqrt(5))) == 9*I*pi / 10
774
+ assert asech(2 / sqrt(2 + sqrt(2))) == I*pi / 8
775
+ assert asech(-2 / sqrt(2 + sqrt(2))) == 7*I*pi / 8
776
+ assert asech(sqrt(5) - 1) == I*pi / 5
777
+ assert asech(1 - sqrt(5)) == 4*I*pi / 5
778
+ assert asech(-sqrt(2*(2 + sqrt(2)))) == 5*I*pi / 8
779
+
780
+ # properties
781
+ # asech(x) == acosh(1/x)
782
+ assert asech(sqrt(2)) == acosh(1/sqrt(2))
783
+ assert asech(2/sqrt(3)) == acosh(sqrt(3)/2)
784
+ assert asech(2/sqrt(2 + sqrt(2))) == acosh(sqrt(2 + sqrt(2))/2)
785
+ assert asech(2) == acosh(S.Half)
786
+
787
+ # asech(x) == I*acos(1/x)
788
+ # (Note: the exact formula is asech(x) == +/- I*acos(1/x))
789
+ assert asech(-sqrt(2)) == I*acos(-1/sqrt(2))
790
+ assert asech(-2/sqrt(3)) == I*acos(-sqrt(3)/2)
791
+ assert asech(-S(2)) == I*acos(Rational(-1, 2))
792
+ assert asech(-2/sqrt(2)) == I*acos(-sqrt(2)/2)
793
+
794
+ # sech(asech(x)) / x == 1
795
+ assert expand_mul(sech(asech(sqrt(6) - sqrt(2))) / (sqrt(6) - sqrt(2))) == 1
796
+ assert expand_mul(sech(asech(sqrt(6) + sqrt(2))) / (sqrt(6) + sqrt(2))) == 1
797
+ assert (sech(asech(sqrt(2 + 2/sqrt(5)))) / (sqrt(2 + 2/sqrt(5)))).simplify() == 1
798
+ assert (sech(asech(-sqrt(2 + 2/sqrt(5)))) / (-sqrt(2 + 2/sqrt(5)))).simplify() == 1
799
+ assert (sech(asech(sqrt(2*(2 + sqrt(2))))) / (sqrt(2*(2 + sqrt(2))))).simplify() == 1
800
+ assert expand_mul(sech(asech(1 + sqrt(5))) / (1 + sqrt(5))) == 1
801
+ assert expand_mul(sech(asech(-1 - sqrt(5))) / (-1 - sqrt(5))) == 1
802
+ assert expand_mul(sech(asech(-sqrt(6) - sqrt(2))) / (-sqrt(6) - sqrt(2))) == 1
803
+
804
+ # numerical evaluation
805
+ assert str(asech(5*I).n(6)) == '0.19869 - 1.5708*I'
806
+ assert str(asech(-5*I).n(6)) == '0.19869 + 1.5708*I'
807
+
808
+
809
+ def test_asech_leading_term():
810
+ x = Symbol('x')
811
+ # Tests concerning branch points
812
+ assert asech(x).as_leading_term(x, cdir=1) == -log(x) + log(2)
813
+ assert asech(x).as_leading_term(x, cdir=-1) == -log(x) + log(2) + 2*I*pi
814
+ assert asech(x + 1).as_leading_term(x, cdir=1) == sqrt(2)*I*sqrt(x)
815
+ assert asech(1/x).as_leading_term(x, cdir=1) == I*pi/2
816
+ # Tests concerning points lying on branch cuts
817
+ assert asech(x - 1).as_leading_term(x, cdir=1) == I*pi
818
+ assert asech(I*x + 3).as_leading_term(x, cdir=1) == -asech(3)
819
+ assert asech(-I*x + 3).as_leading_term(x, cdir=1) == asech(3)
820
+ assert asech(I*x - 3).as_leading_term(x, cdir=1) == -asech(-3)
821
+ assert asech(-I*x - 3).as_leading_term(x, cdir=1) == asech(-3)
822
+ assert asech(I*x - S(1)/3).as_leading_term(x, cdir=1) == -2*I*pi + asech(-S(1)/3)
823
+ assert asech(I*x - S(1)/3).as_leading_term(x, cdir=-1) == asech(-S(1)/3)
824
+ # Tests concerning im(ndir) == 0
825
+ assert asech(-I*x**2 + x - 3).as_leading_term(x, cdir=1) == log(-S(1)/3 + 2*sqrt(2)*I/3)
826
+ assert asech(-I*x**2 + x - 3).as_leading_term(x, cdir=-1) == log(-S(1)/3 + 2*sqrt(2)*I/3)
827
+
828
+
829
+ def test_asech_series():
830
+ x = Symbol('x')
831
+ assert asech(x).series(x, 0, 9, cdir=1) == log(2) - log(x) - x**2/4 - 3*x**4/32 \
832
+ - 5*x**6/96 - 35*x**8/1024 + O(x**9)
833
+ assert asech(x).series(x, 0, 9, cdir=-1) == I*pi + log(2) - log(-x) - x**2/4 - \
834
+ 3*x**4/32 - 5*x**6/96 - 35*x**8/1024 + O(x**9)
835
+ t6 = asech(x).taylor_term(6, x)
836
+ assert t6 == -5*x**6/96
837
+ assert asech(x).taylor_term(8, x, t6, 0) == -35*x**8/1024
838
+
839
+
840
+ def test_asech_nseries():
841
+ x = Symbol('x')
842
+ # Tests concerning branch points
843
+ assert asech(x + 1)._eval_nseries(x, 4, None) == sqrt(2)*sqrt(-x) + 5*sqrt(2)*(-x)**(S(3)/2)/12 + \
844
+ 43*sqrt(2)*(-x)**(S(5)/2)/160 + 177*sqrt(2)*(-x)**(S(7)/2)/896 + O(x**4)
845
+ # Tests concerning points lying on branch cuts
846
+ assert asech(x - 1)._eval_nseries(x, 4, None) == I*pi + sqrt(2)*sqrt(x) + \
847
+ 5*sqrt(2)*x**(S(3)/2)/12 + 43*sqrt(2)*x**(S(5)/2)/160 + 177*sqrt(2)*x**(S(7)/2)/896 + O(x**4)
848
+ assert asech(I*x + 3)._eval_nseries(x, 4, None) == -asech(3) + sqrt(2)*x/12 - \
849
+ 17*sqrt(2)*I*x**2/576 - 443*sqrt(2)*x**3/41472 + O(x**4)
850
+ assert asech(-I*x + 3)._eval_nseries(x, 4, None) == asech(3) + sqrt(2)*x/12 + \
851
+ 17*sqrt(2)*I*x**2/576 - 443*sqrt(2)*x**3/41472 + O(x**4)
852
+ assert asech(I*x - 3)._eval_nseries(x, 4, None) == -asech(-3) - sqrt(2)*x/12 - \
853
+ 17*sqrt(2)*I*x**2/576 + 443*sqrt(2)*x**3/41472 + O(x**4)
854
+ assert asech(-I*x - 3)._eval_nseries(x, 4, None) == asech(-3) - sqrt(2)*x/12 + \
855
+ 17*sqrt(2)*I*x**2/576 + 443*sqrt(2)*x**3/41472 + O(x**4)
856
+ # Tests concerning im(ndir) == 0
857
+ assert asech(-I*x**2 + x - 2)._eval_nseries(x, 3, None) == 2*I*pi/3 + sqrt(3)*I*x/6 + \
858
+ x**2*(sqrt(3)/6 + 7*sqrt(3)*I/72) + O(x**3)
859
+
860
+
861
+ def test_asech_rewrite():
862
+ x = Symbol('x')
863
+ assert asech(x).rewrite(log) == log(1/x + sqrt(1/x - 1) * sqrt(1/x + 1))
864
+ assert asech(x).rewrite(acosh) == acosh(1/x)
865
+ assert asech(x).rewrite(asinh) == sqrt(-1 + 1/x)*(-asin(1/x) + pi/2)/sqrt(1 - 1/x)
866
+ assert asech(x).rewrite(atanh) == \
867
+ sqrt(x + 1)*sqrt(1/(x + 1))*atanh(sqrt(1 - x**2)) + I*pi*(-sqrt(x)*sqrt(1/x) + 1 - I*sqrt(x**2)/(2*sqrt(-x**2)) - I*sqrt(-x)/(2*sqrt(x)))
868
+
869
+
870
+ def test_asech_fdiff():
871
+ x = Symbol('x')
872
+ raises(ArgumentIndexError, lambda: asech(x).fdiff(2))
873
+
874
+
875
+ def test_acsch():
876
+ x = Symbol('x')
877
+
878
+ assert unchanged(acsch, x)
879
+ assert acsch(-x) == -acsch(x)
880
+
881
+ # values at fixed points
882
+ assert acsch(1) == log(1 + sqrt(2))
883
+ assert acsch(-1) == - log(1 + sqrt(2))
884
+ assert acsch(0) is zoo
885
+ assert acsch(2) == log((1+sqrt(5))/2)
886
+ assert acsch(-2) == - log((1+sqrt(5))/2)
887
+
888
+ assert acsch(I) == - I*pi/2
889
+ assert acsch(-I) == I*pi/2
890
+ assert acsch(-I*(sqrt(6) + sqrt(2))) == I*pi / 12
891
+ assert acsch(I*(sqrt(2) + sqrt(6))) == -I*pi / 12
892
+ assert acsch(-I*(1 + sqrt(5))) == I*pi / 10
893
+ assert acsch(I*(1 + sqrt(5))) == -I*pi / 10
894
+ assert acsch(-I*2 / sqrt(2 - sqrt(2))) == I*pi / 8
895
+ assert acsch(I*2 / sqrt(2 - sqrt(2))) == -I*pi / 8
896
+ assert acsch(-I*2) == I*pi / 6
897
+ assert acsch(I*2) == -I*pi / 6
898
+ assert acsch(-I*sqrt(2 + 2/sqrt(5))) == I*pi / 5
899
+ assert acsch(I*sqrt(2 + 2/sqrt(5))) == -I*pi / 5
900
+ assert acsch(-I*sqrt(2)) == I*pi / 4
901
+ assert acsch(I*sqrt(2)) == -I*pi / 4
902
+ assert acsch(-I*(sqrt(5)-1)) == 3*I*pi / 10
903
+ assert acsch(I*(sqrt(5)-1)) == -3*I*pi / 10
904
+ assert acsch(-I*2 / sqrt(3)) == I*pi / 3
905
+ assert acsch(I*2 / sqrt(3)) == -I*pi / 3
906
+ assert acsch(-I*2 / sqrt(2 + sqrt(2))) == 3*I*pi / 8
907
+ assert acsch(I*2 / sqrt(2 + sqrt(2))) == -3*I*pi / 8
908
+ assert acsch(-I*sqrt(2 - 2/sqrt(5))) == 2*I*pi / 5
909
+ assert acsch(I*sqrt(2 - 2/sqrt(5))) == -2*I*pi / 5
910
+ assert acsch(-I*(sqrt(6) - sqrt(2))) == 5*I*pi / 12
911
+ assert acsch(I*(sqrt(6) - sqrt(2))) == -5*I*pi / 12
912
+ assert acsch(nan) is nan
913
+
914
+ # properties
915
+ # acsch(x) == asinh(1/x)
916
+ assert acsch(-I*sqrt(2)) == asinh(I/sqrt(2))
917
+ assert acsch(-I*2 / sqrt(3)) == asinh(I*sqrt(3) / 2)
918
+
919
+ # acsch(x) == -I*asin(I/x)
920
+ assert acsch(-I*sqrt(2)) == -I*asin(-1/sqrt(2))
921
+ assert acsch(-I*2 / sqrt(3)) == -I*asin(-sqrt(3)/2)
922
+
923
+ # csch(acsch(x)) / x == 1
924
+ assert expand_mul(csch(acsch(-I*(sqrt(6) + sqrt(2)))) / (-I*(sqrt(6) + sqrt(2)))) == 1
925
+ assert expand_mul(csch(acsch(I*(1 + sqrt(5)))) / (I*(1 + sqrt(5)))) == 1
926
+ assert (csch(acsch(I*sqrt(2 - 2/sqrt(5)))) / (I*sqrt(2 - 2/sqrt(5)))).simplify() == 1
927
+ assert (csch(acsch(-I*sqrt(2 - 2/sqrt(5)))) / (-I*sqrt(2 - 2/sqrt(5)))).simplify() == 1
928
+
929
+ # numerical evaluation
930
+ assert str(acsch(5*I+1).n(6)) == '0.0391819 - 0.193363*I'
931
+ assert str(acsch(-5*I+1).n(6)) == '0.0391819 + 0.193363*I'
932
+
933
+
934
+ def test_acsch_infinities():
935
+ assert acsch(oo) == 0
936
+ assert acsch(-oo) == 0
937
+ assert acsch(zoo) == 0
938
+
939
+
940
+ def test_acsch_leading_term():
941
+ x = Symbol('x')
942
+ assert acsch(1/x).as_leading_term(x) == x
943
+ # Tests concerning branch points
944
+ assert acsch(x + I).as_leading_term(x) == -I*pi/2
945
+ assert acsch(x - I).as_leading_term(x) == I*pi/2
946
+ # Tests concerning points lying on branch cuts
947
+ assert acsch(x).as_leading_term(x, cdir=1) == -log(x) + log(2)
948
+ assert acsch(x).as_leading_term(x, cdir=-1) == log(x) - log(2) - I*pi
949
+ assert acsch(x + I/2).as_leading_term(x, cdir=1) == -I*pi - acsch(I/2)
950
+ assert acsch(x + I/2).as_leading_term(x, cdir=-1) == acsch(I/2)
951
+ assert acsch(x - I/2).as_leading_term(x, cdir=1) == -acsch(I/2)
952
+ assert acsch(x - I/2).as_leading_term(x, cdir=-1) == acsch(I/2) + I*pi
953
+ # Tests concerning re(ndir) == 0
954
+ assert acsch(I/2 + I*x - x**2).as_leading_term(x, cdir=1) == log(2 - sqrt(3)) - I*pi/2
955
+ assert acsch(I/2 + I*x - x**2).as_leading_term(x, cdir=-1) == log(2 - sqrt(3)) - I*pi/2
956
+
957
+
958
+ def test_acsch_series():
959
+ x = Symbol('x')
960
+ assert acsch(x).series(x, 0, 9) == log(2) - log(x) + x**2/4 - 3*x**4/32 \
961
+ + 5*x**6/96 - 35*x**8/1024 + O(x**9)
962
+ t4 = acsch(x).taylor_term(4, x)
963
+ assert t4 == -3*x**4/32
964
+ assert acsch(x).taylor_term(6, x, t4, 0) == 5*x**6/96
965
+
966
+
967
+ def test_acsch_nseries():
968
+ x = Symbol('x')
969
+ # Tests concerning branch points
970
+ assert acsch(x + I)._eval_nseries(x, 4, None) == -I*pi/2 + I*sqrt(x) + \
971
+ sqrt(x) + 5*I*x**(S(3)/2)/12 - 5*x**(S(3)/2)/12 - 43*I*x**(S(5)/2)/160 - \
972
+ 43*x**(S(5)/2)/160 - 177*I*x**(S(7)/2)/896 + 177*x**(S(7)/2)/896 + O(x**4)
973
+ assert acsch(x - I)._eval_nseries(x, 4, None) == I*pi/2 - I*sqrt(x) + \
974
+ sqrt(x) - 5*I*x**(S(3)/2)/12 - 5*x**(S(3)/2)/12 + 43*I*x**(S(5)/2)/160 - \
975
+ 43*x**(S(5)/2)/160 + 177*I*x**(S(7)/2)/896 + 177*x**(S(7)/2)/896 + O(x**4)
976
+ # Tests concerning points lying on branch cuts
977
+ assert acsch(x + I/2)._eval_nseries(x, 4, None, cdir=1) == -acsch(I/2) - \
978
+ I*pi + 4*sqrt(3)*I*x/3 - 8*sqrt(3)*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
979
+ assert acsch(x + I/2)._eval_nseries(x, 4, None, cdir=-1) == acsch(I/2) - \
980
+ 4*sqrt(3)*I*x/3 + 8*sqrt(3)*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
981
+ assert acsch(x - I/2)._eval_nseries(x, 4, None, cdir=1) == -acsch(I/2) - \
982
+ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
983
+ assert acsch(x - I/2)._eval_nseries(x, 4, None, cdir=-1) == I*pi + \
984
+ acsch(I/2) + 4*sqrt(3)*I*x/3 + 8*sqrt(3)*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
985
+ # TODO: Tests concerning re(ndir) == 0
986
+ assert acsch(I/2 + I*x - x**2)._eval_nseries(x, 4, None) == -I*pi/2 + \
987
+ log(2 - sqrt(3)) + 4*sqrt(3)*x/3 + x**2*(-8*sqrt(3)/9 + 4*sqrt(3)*I/3) + \
988
+ x**3*(16*sqrt(3)/9 - 16*sqrt(3)*I/9) + O(x**4)
989
+
990
+
991
+ def test_acsch_rewrite():
992
+ x = Symbol('x')
993
+ assert acsch(x).rewrite(log) == log(1/x + sqrt(1/x**2 + 1))
994
+ assert acsch(x).rewrite(asinh) == asinh(1/x)
995
+ assert acsch(x).rewrite(atanh) == (sqrt(-x**2)*(-sqrt(-(x**2 + 1)**2)
996
+ *atanh(sqrt(x**2 + 1))/(x**2 + 1)
997
+ + pi/2)/x)
998
+
999
+
1000
+ def test_acsch_fdiff():
1001
+ x = Symbol('x')
1002
+ raises(ArgumentIndexError, lambda: acsch(x).fdiff(2))
1003
+
1004
+
1005
+ def test_atanh():
1006
+ x = Symbol('x')
1007
+
1008
+ #at specific points
1009
+ assert atanh(0) == 0
1010
+ assert atanh(I) == I*pi/4
1011
+ assert atanh(-I) == -I*pi/4
1012
+ assert atanh(1) is oo
1013
+ assert atanh(-1) is -oo
1014
+ assert atanh(nan) is nan
1015
+
1016
+ # at infinites
1017
+ assert atanh(oo) == -I*pi/2
1018
+ assert atanh(-oo) == I*pi/2
1019
+
1020
+ assert atanh(I*oo) == I*pi/2
1021
+ assert atanh(-I*oo) == -I*pi/2
1022
+
1023
+ assert atanh(zoo) == I*AccumBounds(-pi/2, pi/2)
1024
+
1025
+ #properties
1026
+ assert atanh(-x) == -atanh(x)
1027
+
1028
+ assert atanh(I/sqrt(3)) == I*pi/6
1029
+ assert atanh(-I/sqrt(3)) == -I*pi/6
1030
+ assert atanh(I*sqrt(3)) == I*pi/3
1031
+ assert atanh(-I*sqrt(3)) == -I*pi/3
1032
+ assert atanh(I*(1 + sqrt(2))) == pi*I*Rational(3, 8)
1033
+ assert atanh(I*(sqrt(2) - 1)) == pi*I/8
1034
+ assert atanh(I*(1 - sqrt(2))) == -pi*I/8
1035
+ assert atanh(-I*(1 + sqrt(2))) == pi*I*Rational(-3, 8)
1036
+ assert atanh(I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(2, 5)
1037
+ assert atanh(-I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(-2, 5)
1038
+ assert atanh(I*(2 - sqrt(3))) == pi*I/12
1039
+ assert atanh(I*(sqrt(3) - 2)) == -pi*I/12
1040
+ assert atanh(oo) == -I*pi/2
1041
+
1042
+ # Symmetry
1043
+ assert atanh(Rational(-1, 2)) == -atanh(S.Half)
1044
+
1045
+ # inverse composition
1046
+ assert unchanged(atanh, tanh(Symbol('v1')))
1047
+
1048
+ assert atanh(tanh(-5, evaluate=False)) == -5
1049
+ assert atanh(tanh(0, evaluate=False)) == 0
1050
+ assert atanh(tanh(7, evaluate=False)) == 7
1051
+ assert atanh(tanh(I, evaluate=False)) == I
1052
+ assert atanh(tanh(-I, evaluate=False)) == -I
1053
+ assert atanh(tanh(-11*I, evaluate=False)) == -11*I + 4*I*pi
1054
+ assert atanh(tanh(3 + I)) == 3 + I
1055
+ assert atanh(tanh(4 + 5*I)) == 4 - 2*I*pi + 5*I
1056
+ assert atanh(tanh(pi/2)) == pi/2
1057
+ assert atanh(tanh(pi)) == pi
1058
+ assert atanh(tanh(-3 + 7*I)) == -3 - 2*I*pi + 7*I
1059
+ assert atanh(tanh(9 - I*2/3)) == 9 - I*2/3
1060
+ assert atanh(tanh(-32 - 123*I)) == -32 - 123*I + 39*I*pi
1061
+
1062
+
1063
+ def test_atanh_rewrite():
1064
+ x = Symbol('x')
1065
+ assert atanh(x).rewrite(log) == (log(1 + x) - log(1 - x)) / 2
1066
+ assert atanh(x).rewrite(asinh) == \
1067
+ pi*x/(2*sqrt(-x**2)) - sqrt(-x)*sqrt(1 - x**2)*sqrt(1/(x**2 - 1))*asinh(sqrt(1/(x**2 - 1)))/sqrt(x)
1068
+
1069
+
1070
+ def test_atanh_leading_term():
1071
+ x = Symbol('x')
1072
+ assert atanh(x).as_leading_term(x) == x
1073
+ # Tests concerning branch points
1074
+ assert atanh(x + 1).as_leading_term(x, cdir=1) == -log(x)/2 + log(2)/2 - I*pi/2
1075
+ assert atanh(x + 1).as_leading_term(x, cdir=-1) == -log(x)/2 + log(2)/2 + I*pi/2
1076
+ assert atanh(x - 1).as_leading_term(x, cdir=1) == log(x)/2 - log(2)/2
1077
+ assert atanh(x - 1).as_leading_term(x, cdir=-1) == log(x)/2 - log(2)/2
1078
+ assert atanh(1/x).as_leading_term(x, cdir=1) == -I*pi/2
1079
+ assert atanh(1/x).as_leading_term(x, cdir=-1) == I*pi/2
1080
+ # Tests concerning points lying on branch cuts
1081
+ assert atanh(I*x + 2).as_leading_term(x, cdir=1) == atanh(2) + I*pi
1082
+ assert atanh(-I*x + 2).as_leading_term(x, cdir=1) == atanh(2)
1083
+ assert atanh(I*x - 2).as_leading_term(x, cdir=1) == -atanh(2)
1084
+ assert atanh(-I*x - 2).as_leading_term(x, cdir=1) == -I*pi - atanh(2)
1085
+ # Tests concerning im(ndir) == 0
1086
+ assert atanh(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == -log(3)/2 - I*pi/2
1087
+ assert atanh(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == -log(3)/2 - I*pi/2
1088
+
1089
+
1090
+ def test_atanh_series():
1091
+ x = Symbol('x')
1092
+ assert atanh(x).series(x, 0, 10) == \
1093
+ x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10)
1094
+
1095
+
1096
+ def test_atanh_nseries():
1097
+ x = Symbol('x')
1098
+ # Tests concerning branch points
1099
+ assert atanh(x + 1)._eval_nseries(x, 4, None, cdir=1) == -I*pi/2 + log(2)/2 - \
1100
+ log(x)/2 + x/4 - x**2/16 + x**3/48 + O(x**4)
1101
+ assert atanh(x + 1)._eval_nseries(x, 4, None, cdir=-1) == I*pi/2 + log(2)/2 - \
1102
+ log(x)/2 + x/4 - x**2/16 + x**3/48 + O(x**4)
1103
+ assert atanh(x - 1)._eval_nseries(x, 4, None, cdir=1) == -log(2)/2 + log(x)/2 + \
1104
+ x/4 + x**2/16 + x**3/48 + O(x**4)
1105
+ assert atanh(x - 1)._eval_nseries(x, 4, None, cdir=-1) == -log(2)/2 + log(x)/2 + \
1106
+ x/4 + x**2/16 + x**3/48 + O(x**4)
1107
+ # Tests concerning points lying on branch cuts
1108
+ assert atanh(I*x + 2)._eval_nseries(x, 4, None, cdir=1) == I*pi + atanh(2) - \
1109
+ I*x/3 - 2*x**2/9 + 13*I*x**3/81 + O(x**4)
1110
+ assert atanh(I*x + 2)._eval_nseries(x, 4, None, cdir=-1) == atanh(2) - I*x/3 - \
1111
+ 2*x**2/9 + 13*I*x**3/81 + O(x**4)
1112
+ assert atanh(I*x - 2)._eval_nseries(x, 4, None, cdir=1) == -atanh(2) - I*x/3 + \
1113
+ 2*x**2/9 + 13*I*x**3/81 + O(x**4)
1114
+ assert atanh(I*x - 2)._eval_nseries(x, 4, None, cdir=-1) == -atanh(2) - I*pi - \
1115
+ I*x/3 + 2*x**2/9 + 13*I*x**3/81 + O(x**4)
1116
+ # Tests concerning im(ndir) == 0
1117
+ assert atanh(-I*x**2 + x - 2)._eval_nseries(x, 4, None) == -I*pi/2 - log(3)/2 - x/3 + \
1118
+ x**2*(-S(1)/4 + I/2) + x**2*(S(1)/36 - I/6) + x**3*(-S(1)/6 + I/2) + x**3*(S(1)/162 - I/18) + O(x**4)
1119
+
1120
+
1121
+ def test_atanh_fdiff():
1122
+ x = Symbol('x')
1123
+ raises(ArgumentIndexError, lambda: atanh(x).fdiff(2))
1124
+
1125
+
1126
+ def test_acoth():
1127
+ x = Symbol('x')
1128
+
1129
+ #at specific points
1130
+ assert acoth(0) == I*pi/2
1131
+ assert acoth(I) == -I*pi/4
1132
+ assert acoth(-I) == I*pi/4
1133
+ assert acoth(1) is oo
1134
+ assert acoth(-1) is -oo
1135
+ assert acoth(nan) is nan
1136
+
1137
+ # at infinites
1138
+ assert acoth(oo) == 0
1139
+ assert acoth(-oo) == 0
1140
+ assert acoth(I*oo) == 0
1141
+ assert acoth(-I*oo) == 0
1142
+ assert acoth(zoo) == 0
1143
+
1144
+ #properties
1145
+ assert acoth(-x) == -acoth(x)
1146
+
1147
+ assert acoth(I/sqrt(3)) == -I*pi/3
1148
+ assert acoth(-I/sqrt(3)) == I*pi/3
1149
+ assert acoth(I*sqrt(3)) == -I*pi/6
1150
+ assert acoth(-I*sqrt(3)) == I*pi/6
1151
+ assert acoth(I*(1 + sqrt(2))) == -pi*I/8
1152
+ assert acoth(-I*(sqrt(2) + 1)) == pi*I/8
1153
+ assert acoth(I*(1 - sqrt(2))) == pi*I*Rational(3, 8)
1154
+ assert acoth(I*(sqrt(2) - 1)) == pi*I*Rational(-3, 8)
1155
+ assert acoth(I*sqrt(5 + 2*sqrt(5))) == -I*pi/10
1156
+ assert acoth(-I*sqrt(5 + 2*sqrt(5))) == I*pi/10
1157
+ assert acoth(I*(2 + sqrt(3))) == -pi*I/12
1158
+ assert acoth(-I*(2 + sqrt(3))) == pi*I/12
1159
+ assert acoth(I*(2 - sqrt(3))) == pi*I*Rational(-5, 12)
1160
+ assert acoth(I*(sqrt(3) - 2)) == pi*I*Rational(5, 12)
1161
+
1162
+ # Symmetry
1163
+ assert acoth(Rational(-1, 2)) == -acoth(S.Half)
1164
+
1165
+
1166
+ def test_acoth_rewrite():
1167
+ x = Symbol('x')
1168
+ assert acoth(x).rewrite(log) == (log(1 + 1/x) - log(1 - 1/x)) / 2
1169
+ assert acoth(x).rewrite(atanh) == atanh(1/x)
1170
+ assert acoth(x).rewrite(asinh) == \
1171
+ x*sqrt(x**(-2))*asinh(sqrt(1/(x**2 - 1))) + I*pi*(sqrt((x - 1)/x)*sqrt(x/(x - 1)) - sqrt(x/(x + 1))*sqrt(1 + 1/x))/2
1172
+
1173
+
1174
+ def test_acoth_leading_term():
1175
+ x = Symbol('x')
1176
+ # Tests concerning branch points
1177
+ assert acoth(x + 1).as_leading_term(x, cdir=1) == -log(x)/2 + log(2)/2
1178
+ assert acoth(x + 1).as_leading_term(x, cdir=-1) == -log(x)/2 + log(2)/2
1179
+ assert acoth(x - 1).as_leading_term(x, cdir=1) == log(x)/2 - log(2)/2 + I*pi/2
1180
+ assert acoth(x - 1).as_leading_term(x, cdir=-1) == log(x)/2 - log(2)/2 - I*pi/2
1181
+ # Tests concerning points lying on branch cuts
1182
+ assert acoth(x).as_leading_term(x, cdir=-1) == I*pi/2
1183
+ assert acoth(x).as_leading_term(x, cdir=1) == -I*pi/2
1184
+ assert acoth(I*x + 1/2).as_leading_term(x, cdir=1) == acoth(1/2)
1185
+ assert acoth(-I*x + 1/2).as_leading_term(x, cdir=1) == acoth(1/2) + I*pi
1186
+ assert acoth(I*x - 1/2).as_leading_term(x, cdir=1) == -I*pi - acoth(1/2)
1187
+ assert acoth(-I*x - 1/2).as_leading_term(x, cdir=1) == -acoth(1/2)
1188
+ # Tests concerning im(ndir) == 0
1189
+ assert acoth(-I*x**2 - x - S(1)/2).as_leading_term(x, cdir=1) == -log(3)/2 + I*pi/2
1190
+ assert acoth(-I*x**2 - x - S(1)/2).as_leading_term(x, cdir=-1) == -log(3)/2 + I*pi/2
1191
+
1192
+
1193
+ def test_acoth_series():
1194
+ x = Symbol('x')
1195
+ assert acoth(x).series(x, 0, 10) == \
1196
+ -I*pi/2 + x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10)
1197
+
1198
+
1199
+ def test_acoth_nseries():
1200
+ x = Symbol('x')
1201
+ # Tests concerning branch points
1202
+ assert acoth(x + 1)._eval_nseries(x, 4, None) == log(2)/2 - log(x)/2 + x/4 - \
1203
+ x**2/16 + x**3/48 + O(x**4)
1204
+ assert acoth(x - 1)._eval_nseries(x, 4, None, cdir=1) == I*pi/2 - log(2)/2 + \
1205
+ log(x)/2 + x/4 + x**2/16 + x**3/48 + O(x**4)
1206
+ assert acoth(x - 1)._eval_nseries(x, 4, None, cdir=-1) == -I*pi/2 - log(2)/2 + \
1207
+ log(x)/2 + x/4 + x**2/16 + x**3/48 + O(x**4)
1208
+ # Tests concerning points lying on branch cuts
1209
+ assert acoth(I*x + S(1)/2)._eval_nseries(x, 4, None, cdir=1) == acoth(S(1)/2) + \
1210
+ 4*I*x/3 - 8*x**2/9 - 112*I*x**3/81 + O(x**4)
1211
+ assert acoth(I*x + S(1)/2)._eval_nseries(x, 4, None, cdir=-1) == I*pi + \
1212
+ acoth(S(1)/2) + 4*I*x/3 - 8*x**2/9 - 112*I*x**3/81 + O(x**4)
1213
+ assert acoth(I*x - S(1)/2)._eval_nseries(x, 4, None, cdir=1) == -acoth(S(1)/2) - \
1214
+ I*pi + 4*I*x/3 + 8*x**2/9 - 112*I*x**3/81 + O(x**4)
1215
+ assert acoth(I*x - S(1)/2)._eval_nseries(x, 4, None, cdir=-1) == -acoth(S(1)/2) + \
1216
+ 4*I*x/3 + 8*x**2/9 - 112*I*x**3/81 + O(x**4)
1217
+ # Tests concerning im(ndir) == 0
1218
+ assert acoth(-I*x**2 - x - S(1)/2)._eval_nseries(x, 4, None) == I*pi/2 - log(3)/2 - \
1219
+ 4*x/3 + x**2*(-S(8)/9 + 2*I/3) - 2*I*x**2 + x**3*(S(104)/81 - 16*I/9) - 8*x**3/3 + O(x**4)
1220
+
1221
+
1222
+ def test_acoth_fdiff():
1223
+ x = Symbol('x')
1224
+ raises(ArgumentIndexError, lambda: acoth(x).fdiff(2))
1225
+
1226
+
1227
+ def test_inverses():
1228
+ x = Symbol('x')
1229
+ assert sinh(x).inverse() == asinh
1230
+ raises(AttributeError, lambda: cosh(x).inverse())
1231
+ assert tanh(x).inverse() == atanh
1232
+ assert coth(x).inverse() == acoth
1233
+ assert asinh(x).inverse() == sinh
1234
+ assert acosh(x).inverse() == cosh
1235
+ assert atanh(x).inverse() == tanh
1236
+ assert acoth(x).inverse() == coth
1237
+ assert asech(x).inverse() == sech
1238
+ assert acsch(x).inverse() == csch
1239
+
1240
+
1241
+ def test_leading_term():
1242
+ x = Symbol('x')
1243
+ assert cosh(x).as_leading_term(x) == 1
1244
+ assert coth(x).as_leading_term(x) == 1/x
1245
+ for func in [sinh, tanh]:
1246
+ assert func(x).as_leading_term(x) == x
1247
+ for func in [sinh, cosh, tanh, coth]:
1248
+ for ar in (1/x, S.Half):
1249
+ eq = func(ar)
1250
+ assert eq.as_leading_term(x) == eq
1251
+ for func in [csch, sech]:
1252
+ eq = func(S.Half)
1253
+ assert eq.as_leading_term(x) == eq
1254
+
1255
+
1256
+ def test_complex():
1257
+ a, b = symbols('a,b', real=True)
1258
+ z = a + b*I
1259
+ for func in [sinh, cosh, tanh, coth, sech, csch]:
1260
+ assert func(z).conjugate() == func(a - b*I)
1261
+ for deep in [True, False]:
1262
+ assert sinh(z).expand(
1263
+ complex=True, deep=deep) == sinh(a)*cos(b) + I*cosh(a)*sin(b)
1264
+ assert cosh(z).expand(
1265
+ complex=True, deep=deep) == cosh(a)*cos(b) + I*sinh(a)*sin(b)
1266
+ assert tanh(z).expand(complex=True, deep=deep) == sinh(a)*cosh(
1267
+ a)/(cos(b)**2 + sinh(a)**2) + I*sin(b)*cos(b)/(cos(b)**2 + sinh(a)**2)
1268
+ assert coth(z).expand(complex=True, deep=deep) == sinh(a)*cosh(
1269
+ a)/(sin(b)**2 + sinh(a)**2) - I*sin(b)*cos(b)/(sin(b)**2 + sinh(a)**2)
1270
+ assert csch(z).expand(complex=True, deep=deep) == cos(b) * sinh(a) / (sin(b)**2\
1271
+ *cosh(a)**2 + cos(b)**2 * sinh(a)**2) - I*sin(b) * cosh(a) / (sin(b)**2\
1272
+ *cosh(a)**2 + cos(b)**2 * sinh(a)**2)
1273
+ assert sech(z).expand(complex=True, deep=deep) == cos(b) * cosh(a) / (sin(b)**2\
1274
+ *sinh(a)**2 + cos(b)**2 * cosh(a)**2) - I*sin(b) * sinh(a) / (sin(b)**2\
1275
+ *sinh(a)**2 + cos(b)**2 * cosh(a)**2)
1276
+
1277
+
1278
+ def test_complex_2899():
1279
+ a, b = symbols('a,b', real=True)
1280
+ for deep in [True, False]:
1281
+ for func in [sinh, cosh, tanh, coth]:
1282
+ assert func(a).expand(complex=True, deep=deep) == func(a)
1283
+
1284
+
1285
+ def test_simplifications():
1286
+ x = Symbol('x')
1287
+ assert sinh(asinh(x)) == x
1288
+ assert sinh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1)
1289
+ assert sinh(atanh(x)) == x/sqrt(1 - x**2)
1290
+ assert sinh(acoth(x)) == 1/(sqrt(x - 1) * sqrt(x + 1))
1291
+
1292
+ assert cosh(asinh(x)) == sqrt(1 + x**2)
1293
+ assert cosh(acosh(x)) == x
1294
+ assert cosh(atanh(x)) == 1/sqrt(1 - x**2)
1295
+ assert cosh(acoth(x)) == x/(sqrt(x - 1) * sqrt(x + 1))
1296
+
1297
+ assert tanh(asinh(x)) == x/sqrt(1 + x**2)
1298
+ assert tanh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1) / x
1299
+ assert tanh(atanh(x)) == x
1300
+ assert tanh(acoth(x)) == 1/x
1301
+
1302
+ assert coth(asinh(x)) == sqrt(1 + x**2)/x
1303
+ assert coth(acosh(x)) == x/(sqrt(x - 1) * sqrt(x + 1))
1304
+ assert coth(atanh(x)) == 1/x
1305
+ assert coth(acoth(x)) == x
1306
+
1307
+ assert csch(asinh(x)) == 1/x
1308
+ assert csch(acosh(x)) == 1/(sqrt(x - 1) * sqrt(x + 1))
1309
+ assert csch(atanh(x)) == sqrt(1 - x**2)/x
1310
+ assert csch(acoth(x)) == sqrt(x - 1) * sqrt(x + 1)
1311
+
1312
+ assert sech(asinh(x)) == 1/sqrt(1 + x**2)
1313
+ assert sech(acosh(x)) == 1/x
1314
+ assert sech(atanh(x)) == sqrt(1 - x**2)
1315
+ assert sech(acoth(x)) == sqrt(x - 1) * sqrt(x + 1)/x
1316
+
1317
+
1318
+ def test_issue_4136():
1319
+ assert cosh(asinh(Integer(3)/2)) == sqrt(Integer(13)/4)
1320
+
1321
+
1322
+ def test_sinh_rewrite():
1323
+ x = Symbol('x')
1324
+ assert sinh(x).rewrite(exp) == (exp(x) - exp(-x))/2 \
1325
+ == sinh(x).rewrite('tractable')
1326
+ assert sinh(x).rewrite(cosh) == -I*cosh(x + I*pi/2)
1327
+ tanh_half = tanh(S.Half*x)
1328
+ assert sinh(x).rewrite(tanh) == 2*tanh_half/(1 - tanh_half**2)
1329
+ coth_half = coth(S.Half*x)
1330
+ assert sinh(x).rewrite(coth) == 2*coth_half/(coth_half**2 - 1)
1331
+
1332
+
1333
+ def test_cosh_rewrite():
1334
+ x = Symbol('x')
1335
+ assert cosh(x).rewrite(exp) == (exp(x) + exp(-x))/2 \
1336
+ == cosh(x).rewrite('tractable')
1337
+ assert cosh(x).rewrite(sinh) == -I*sinh(x + I*pi/2)
1338
+ tanh_half = tanh(S.Half*x)**2
1339
+ assert cosh(x).rewrite(tanh) == (1 + tanh_half)/(1 - tanh_half)
1340
+ coth_half = coth(S.Half*x)**2
1341
+ assert cosh(x).rewrite(coth) == (coth_half + 1)/(coth_half - 1)
1342
+
1343
+
1344
+ def test_tanh_rewrite():
1345
+ x = Symbol('x')
1346
+ assert tanh(x).rewrite(exp) == (exp(x) - exp(-x))/(exp(x) + exp(-x)) \
1347
+ == tanh(x).rewrite('tractable')
1348
+ assert tanh(x).rewrite(sinh) == I*sinh(x)/sinh(I*pi/2 - x)
1349
+ assert tanh(x).rewrite(cosh) == I*cosh(I*pi/2 - x)/cosh(x)
1350
+ assert tanh(x).rewrite(coth) == 1/coth(x)
1351
+
1352
+
1353
+ def test_coth_rewrite():
1354
+ x = Symbol('x')
1355
+ assert coth(x).rewrite(exp) == (exp(x) + exp(-x))/(exp(x) - exp(-x)) \
1356
+ == coth(x).rewrite('tractable')
1357
+ assert coth(x).rewrite(sinh) == -I*sinh(I*pi/2 - x)/sinh(x)
1358
+ assert coth(x).rewrite(cosh) == -I*cosh(x)/cosh(I*pi/2 - x)
1359
+ assert coth(x).rewrite(tanh) == 1/tanh(x)
1360
+
1361
+
1362
+ def test_csch_rewrite():
1363
+ x = Symbol('x')
1364
+ assert csch(x).rewrite(exp) == 1 / (exp(x)/2 - exp(-x)/2) \
1365
+ == csch(x).rewrite('tractable')
1366
+ assert csch(x).rewrite(cosh) == I/cosh(x + I*pi/2)
1367
+ tanh_half = tanh(S.Half*x)
1368
+ assert csch(x).rewrite(tanh) == (1 - tanh_half**2)/(2*tanh_half)
1369
+ coth_half = coth(S.Half*x)
1370
+ assert csch(x).rewrite(coth) == (coth_half**2 - 1)/(2*coth_half)
1371
+
1372
+
1373
+ def test_sech_rewrite():
1374
+ x = Symbol('x')
1375
+ assert sech(x).rewrite(exp) == 1 / (exp(x)/2 + exp(-x)/2) \
1376
+ == sech(x).rewrite('tractable')
1377
+ assert sech(x).rewrite(sinh) == I/sinh(x + I*pi/2)
1378
+ tanh_half = tanh(S.Half*x)**2
1379
+ assert sech(x).rewrite(tanh) == (1 - tanh_half)/(1 + tanh_half)
1380
+ coth_half = coth(S.Half*x)**2
1381
+ assert sech(x).rewrite(coth) == (coth_half - 1)/(coth_half + 1)
1382
+
1383
+
1384
+ def test_derivs():
1385
+ x = Symbol('x')
1386
+ assert coth(x).diff(x) == -sinh(x)**(-2)
1387
+ assert sinh(x).diff(x) == cosh(x)
1388
+ assert cosh(x).diff(x) == sinh(x)
1389
+ assert tanh(x).diff(x) == -tanh(x)**2 + 1
1390
+ assert csch(x).diff(x) == -coth(x)*csch(x)
1391
+ assert sech(x).diff(x) == -tanh(x)*sech(x)
1392
+ assert acoth(x).diff(x) == 1/(-x**2 + 1)
1393
+ assert asinh(x).diff(x) == 1/sqrt(x**2 + 1)
1394
+ assert acosh(x).diff(x) == 1/(sqrt(x - 1)*sqrt(x + 1))
1395
+ assert acosh(x).diff(x) == acosh(x).rewrite(log).diff(x).together()
1396
+ assert atanh(x).diff(x) == 1/(-x**2 + 1)
1397
+ assert asech(x).diff(x) == -1/(x*sqrt(1 - x**2))
1398
+ assert acsch(x).diff(x) == -1/(x**2*sqrt(1 + x**(-2)))
1399
+
1400
+
1401
+ def test_sinh_expansion():
1402
+ x, y = symbols('x,y')
1403
+ assert sinh(x+y).expand(trig=True) == sinh(x)*cosh(y) + cosh(x)*sinh(y)
1404
+ assert sinh(2*x).expand(trig=True) == 2*sinh(x)*cosh(x)
1405
+ assert sinh(3*x).expand(trig=True).expand() == \
1406
+ sinh(x)**3 + 3*sinh(x)*cosh(x)**2
1407
+
1408
+
1409
+ def test_cosh_expansion():
1410
+ x, y = symbols('x,y')
1411
+ assert cosh(x+y).expand(trig=True) == cosh(x)*cosh(y) + sinh(x)*sinh(y)
1412
+ assert cosh(2*x).expand(trig=True) == cosh(x)**2 + sinh(x)**2
1413
+ assert cosh(3*x).expand(trig=True).expand() == \
1414
+ 3*sinh(x)**2*cosh(x) + cosh(x)**3
1415
+
1416
+ def test_cosh_positive():
1417
+ # See issue 11721
1418
+ # cosh(x) is positive for real values of x
1419
+ k = symbols('k', real=True)
1420
+ n = symbols('n', integer=True)
1421
+
1422
+ assert cosh(k, evaluate=False).is_positive is True
1423
+ assert cosh(k + 2*n*pi*I, evaluate=False).is_positive is True
1424
+ assert cosh(I*pi/4, evaluate=False).is_positive is True
1425
+ assert cosh(3*I*pi/4, evaluate=False).is_positive is False
1426
+
1427
+ def test_cosh_nonnegative():
1428
+ k = symbols('k', real=True)
1429
+ n = symbols('n', integer=True)
1430
+
1431
+ assert cosh(k, evaluate=False).is_nonnegative is True
1432
+ assert cosh(k + 2*n*pi*I, evaluate=False).is_nonnegative is True
1433
+ assert cosh(I*pi/4, evaluate=False).is_nonnegative is True
1434
+ assert cosh(3*I*pi/4, evaluate=False).is_nonnegative is False
1435
+ assert cosh(S.Zero, evaluate=False).is_nonnegative is True
1436
+
1437
+ def test_real_assumptions():
1438
+ z = Symbol('z', real=False)
1439
+ assert sinh(z).is_real is None
1440
+ assert cosh(z).is_real is None
1441
+ assert tanh(z).is_real is None
1442
+ assert sech(z).is_real is None
1443
+ assert csch(z).is_real is None
1444
+ assert coth(z).is_real is None
1445
+
1446
+ def test_sign_assumptions():
1447
+ p = Symbol('p', positive=True)
1448
+ n = Symbol('n', negative=True)
1449
+ assert sinh(n).is_negative is True
1450
+ assert sinh(p).is_positive is True
1451
+ assert cosh(n).is_positive is True
1452
+ assert cosh(p).is_positive is True
1453
+ assert tanh(n).is_negative is True
1454
+ assert tanh(p).is_positive is True
1455
+ assert csch(n).is_negative is True
1456
+ assert csch(p).is_positive is True
1457
+ assert sech(n).is_positive is True
1458
+ assert sech(p).is_positive is True
1459
+ assert coth(n).is_negative is True
1460
+ assert coth(p).is_positive is True
venv/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_integers.py ADDED
@@ -0,0 +1,632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.calculus.accumulationbounds import AccumBounds
2
+ from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
3
+ from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import (Symbol, symbols)
6
+ from sympy.functions.combinatorial.factorials import factorial
7
+ from sympy.functions.elementary.exponential import (exp, log)
8
+ from sympy.functions.elementary.integers import (ceiling, floor, frac)
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.functions.elementary.trigonometric import sin, cos, tan
11
+
12
+ from sympy.core.expr import unchanged
13
+ from sympy.testing.pytest import XFAIL
14
+
15
+ x = Symbol('x')
16
+ i = Symbol('i', imaginary=True)
17
+ y = Symbol('y', real=True)
18
+ k, n = symbols('k,n', integer=True)
19
+
20
+
21
+ def test_floor():
22
+
23
+ assert floor(nan) is nan
24
+
25
+ assert floor(oo) is oo
26
+ assert floor(-oo) is -oo
27
+ assert floor(zoo) is zoo
28
+
29
+ assert floor(0) == 0
30
+
31
+ assert floor(1) == 1
32
+ assert floor(-1) == -1
33
+
34
+ assert floor(E) == 2
35
+ assert floor(-E) == -3
36
+
37
+ assert floor(2*E) == 5
38
+ assert floor(-2*E) == -6
39
+
40
+ assert floor(pi) == 3
41
+ assert floor(-pi) == -4
42
+
43
+ assert floor(S.Half) == 0
44
+ assert floor(Rational(-1, 2)) == -1
45
+
46
+ assert floor(Rational(7, 3)) == 2
47
+ assert floor(Rational(-7, 3)) == -3
48
+ assert floor(-Rational(7, 3)) == -3
49
+
50
+ assert floor(Float(17.0)) == 17
51
+ assert floor(-Float(17.0)) == -17
52
+
53
+ assert floor(Float(7.69)) == 7
54
+ assert floor(-Float(7.69)) == -8
55
+
56
+ assert floor(I) == I
57
+ assert floor(-I) == -I
58
+ e = floor(i)
59
+ assert e.func is floor and e.args[0] == i
60
+
61
+ assert floor(oo*I) == oo*I
62
+ assert floor(-oo*I) == -oo*I
63
+ assert floor(exp(I*pi/4)*oo) == exp(I*pi/4)*oo
64
+
65
+ assert floor(2*I) == 2*I
66
+ assert floor(-2*I) == -2*I
67
+
68
+ assert floor(I/2) == 0
69
+ assert floor(-I/2) == -I
70
+
71
+ assert floor(E + 17) == 19
72
+ assert floor(pi + 2) == 5
73
+
74
+ assert floor(E + pi) == 5
75
+ assert floor(I + pi) == 3 + I
76
+
77
+ assert floor(floor(pi)) == 3
78
+ assert floor(floor(y)) == floor(y)
79
+ assert floor(floor(x)) == floor(x)
80
+
81
+ assert unchanged(floor, x)
82
+ assert unchanged(floor, 2*x)
83
+ assert unchanged(floor, k*x)
84
+
85
+ assert floor(k) == k
86
+ assert floor(2*k) == 2*k
87
+ assert floor(k*n) == k*n
88
+
89
+ assert unchanged(floor, k/2)
90
+
91
+ assert unchanged(floor, x + y)
92
+
93
+ assert floor(x + 3) == floor(x) + 3
94
+ assert floor(x + k) == floor(x) + k
95
+
96
+ assert floor(y + 3) == floor(y) + 3
97
+ assert floor(y + k) == floor(y) + k
98
+
99
+ assert floor(3 + I*y + pi) == 6 + floor(y)*I
100
+
101
+ assert floor(k + n) == k + n
102
+
103
+ assert unchanged(floor, x*I)
104
+ assert floor(k*I) == k*I
105
+
106
+ assert floor(Rational(23, 10) - E*I) == 2 - 3*I
107
+
108
+ assert floor(sin(1)) == 0
109
+ assert floor(sin(-1)) == -1
110
+
111
+ assert floor(exp(2)) == 7
112
+
113
+ assert floor(log(8)/log(2)) != 2
114
+ assert int(floor(log(8)/log(2)).evalf(chop=True)) == 3
115
+
116
+ assert floor(factorial(50)/exp(1)) == \
117
+ 11188719610782480504630258070757734324011354208865721592720336800
118
+
119
+ assert (floor(y) < y) == False
120
+ assert (floor(y) <= y) == True
121
+ assert (floor(y) > y) == False
122
+ assert (floor(y) >= y) == False
123
+ assert (floor(x) <= x).is_Relational # x could be non-real
124
+ assert (floor(x) > x).is_Relational
125
+ assert (floor(x) <= y).is_Relational # arg is not same as rhs
126
+ assert (floor(x) > y).is_Relational
127
+ assert (floor(y) <= oo) == True
128
+ assert (floor(y) < oo) == True
129
+ assert (floor(y) >= -oo) == True
130
+ assert (floor(y) > -oo) == True
131
+
132
+ assert floor(y).rewrite(frac) == y - frac(y)
133
+ assert floor(y).rewrite(ceiling) == -ceiling(-y)
134
+ assert floor(y).rewrite(frac).subs(y, -pi) == floor(-pi)
135
+ assert floor(y).rewrite(frac).subs(y, E) == floor(E)
136
+ assert floor(y).rewrite(ceiling).subs(y, E) == -ceiling(-E)
137
+ assert floor(y).rewrite(ceiling).subs(y, -pi) == -ceiling(pi)
138
+
139
+ assert Eq(floor(y), y - frac(y))
140
+ assert Eq(floor(y), -ceiling(-y))
141
+
142
+ neg = Symbol('neg', negative=True)
143
+ nn = Symbol('nn', nonnegative=True)
144
+ pos = Symbol('pos', positive=True)
145
+ np = Symbol('np', nonpositive=True)
146
+
147
+ assert (floor(neg) < 0) == True
148
+ assert (floor(neg) <= 0) == True
149
+ assert (floor(neg) > 0) == False
150
+ assert (floor(neg) >= 0) == False
151
+ assert (floor(neg) <= -1) == True
152
+ assert (floor(neg) >= -3) == (neg >= -3)
153
+ assert (floor(neg) < 5) == (neg < 5)
154
+
155
+ assert (floor(nn) < 0) == False
156
+ assert (floor(nn) >= 0) == True
157
+
158
+ assert (floor(pos) < 0) == False
159
+ assert (floor(pos) <= 0) == (pos < 1)
160
+ assert (floor(pos) > 0) == (pos >= 1)
161
+ assert (floor(pos) >= 0) == True
162
+ assert (floor(pos) >= 3) == (pos >= 3)
163
+
164
+ assert (floor(np) <= 0) == True
165
+ assert (floor(np) > 0) == False
166
+
167
+ assert floor(neg).is_negative == True
168
+ assert floor(neg).is_nonnegative == False
169
+ assert floor(nn).is_negative == False
170
+ assert floor(nn).is_nonnegative == True
171
+ assert floor(pos).is_negative == False
172
+ assert floor(pos).is_nonnegative == True
173
+ assert floor(np).is_negative is None
174
+ assert floor(np).is_nonnegative is None
175
+
176
+ assert (floor(7, evaluate=False) >= 7) == True
177
+ assert (floor(7, evaluate=False) > 7) == False
178
+ assert (floor(7, evaluate=False) <= 7) == True
179
+ assert (floor(7, evaluate=False) < 7) == False
180
+
181
+ assert (floor(7, evaluate=False) >= 6) == True
182
+ assert (floor(7, evaluate=False) > 6) == True
183
+ assert (floor(7, evaluate=False) <= 6) == False
184
+ assert (floor(7, evaluate=False) < 6) == False
185
+
186
+ assert (floor(7, evaluate=False) >= 8) == False
187
+ assert (floor(7, evaluate=False) > 8) == False
188
+ assert (floor(7, evaluate=False) <= 8) == True
189
+ assert (floor(7, evaluate=False) < 8) == True
190
+
191
+ assert (floor(x) <= 5.5) == Le(floor(x), 5.5, evaluate=False)
192
+ assert (floor(x) >= -3.2) == Ge(floor(x), -3.2, evaluate=False)
193
+ assert (floor(x) < 2.9) == Lt(floor(x), 2.9, evaluate=False)
194
+ assert (floor(x) > -1.7) == Gt(floor(x), -1.7, evaluate=False)
195
+
196
+ assert (floor(y) <= 5.5) == (y < 6)
197
+ assert (floor(y) >= -3.2) == (y >= -3)
198
+ assert (floor(y) < 2.9) == (y < 3)
199
+ assert (floor(y) > -1.7) == (y >= -1)
200
+
201
+ assert (floor(y) <= n) == (y < n + 1)
202
+ assert (floor(y) >= n) == (y >= n)
203
+ assert (floor(y) < n) == (y < n)
204
+ assert (floor(y) > n) == (y >= n + 1)
205
+
206
+
207
+ def test_ceiling():
208
+
209
+ assert ceiling(nan) is nan
210
+
211
+ assert ceiling(oo) is oo
212
+ assert ceiling(-oo) is -oo
213
+ assert ceiling(zoo) is zoo
214
+
215
+ assert ceiling(0) == 0
216
+
217
+ assert ceiling(1) == 1
218
+ assert ceiling(-1) == -1
219
+
220
+ assert ceiling(E) == 3
221
+ assert ceiling(-E) == -2
222
+
223
+ assert ceiling(2*E) == 6
224
+ assert ceiling(-2*E) == -5
225
+
226
+ assert ceiling(pi) == 4
227
+ assert ceiling(-pi) == -3
228
+
229
+ assert ceiling(S.Half) == 1
230
+ assert ceiling(Rational(-1, 2)) == 0
231
+
232
+ assert ceiling(Rational(7, 3)) == 3
233
+ assert ceiling(-Rational(7, 3)) == -2
234
+
235
+ assert ceiling(Float(17.0)) == 17
236
+ assert ceiling(-Float(17.0)) == -17
237
+
238
+ assert ceiling(Float(7.69)) == 8
239
+ assert ceiling(-Float(7.69)) == -7
240
+
241
+ assert ceiling(I) == I
242
+ assert ceiling(-I) == -I
243
+ e = ceiling(i)
244
+ assert e.func is ceiling and e.args[0] == i
245
+
246
+ assert ceiling(oo*I) == oo*I
247
+ assert ceiling(-oo*I) == -oo*I
248
+ assert ceiling(exp(I*pi/4)*oo) == exp(I*pi/4)*oo
249
+
250
+ assert ceiling(2*I) == 2*I
251
+ assert ceiling(-2*I) == -2*I
252
+
253
+ assert ceiling(I/2) == I
254
+ assert ceiling(-I/2) == 0
255
+
256
+ assert ceiling(E + 17) == 20
257
+ assert ceiling(pi + 2) == 6
258
+
259
+ assert ceiling(E + pi) == 6
260
+ assert ceiling(I + pi) == I + 4
261
+
262
+ assert ceiling(ceiling(pi)) == 4
263
+ assert ceiling(ceiling(y)) == ceiling(y)
264
+ assert ceiling(ceiling(x)) == ceiling(x)
265
+
266
+ assert unchanged(ceiling, x)
267
+ assert unchanged(ceiling, 2*x)
268
+ assert unchanged(ceiling, k*x)
269
+
270
+ assert ceiling(k) == k
271
+ assert ceiling(2*k) == 2*k
272
+ assert ceiling(k*n) == k*n
273
+
274
+ assert unchanged(ceiling, k/2)
275
+
276
+ assert unchanged(ceiling, x + y)
277
+
278
+ assert ceiling(x + 3) == ceiling(x) + 3
279
+ assert ceiling(x + k) == ceiling(x) + k
280
+
281
+ assert ceiling(y + 3) == ceiling(y) + 3
282
+ assert ceiling(y + k) == ceiling(y) + k
283
+
284
+ assert ceiling(3 + pi + y*I) == 7 + ceiling(y)*I
285
+
286
+ assert ceiling(k + n) == k + n
287
+
288
+ assert unchanged(ceiling, x*I)
289
+ assert ceiling(k*I) == k*I
290
+
291
+ assert ceiling(Rational(23, 10) - E*I) == 3 - 2*I
292
+
293
+ assert ceiling(sin(1)) == 1
294
+ assert ceiling(sin(-1)) == 0
295
+
296
+ assert ceiling(exp(2)) == 8
297
+
298
+ assert ceiling(-log(8)/log(2)) != -2
299
+ assert int(ceiling(-log(8)/log(2)).evalf(chop=True)) == -3
300
+
301
+ assert ceiling(factorial(50)/exp(1)) == \
302
+ 11188719610782480504630258070757734324011354208865721592720336801
303
+
304
+ assert (ceiling(y) >= y) == True
305
+ assert (ceiling(y) > y) == False
306
+ assert (ceiling(y) < y) == False
307
+ assert (ceiling(y) <= y) == False
308
+ assert (ceiling(x) >= x).is_Relational # x could be non-real
309
+ assert (ceiling(x) < x).is_Relational
310
+ assert (ceiling(x) >= y).is_Relational # arg is not same as rhs
311
+ assert (ceiling(x) < y).is_Relational
312
+ assert (ceiling(y) >= -oo) == True
313
+ assert (ceiling(y) > -oo) == True
314
+ assert (ceiling(y) <= oo) == True
315
+ assert (ceiling(y) < oo) == True
316
+
317
+ assert ceiling(y).rewrite(floor) == -floor(-y)
318
+ assert ceiling(y).rewrite(frac) == y + frac(-y)
319
+ assert ceiling(y).rewrite(floor).subs(y, -pi) == -floor(pi)
320
+ assert ceiling(y).rewrite(floor).subs(y, E) == -floor(-E)
321
+ assert ceiling(y).rewrite(frac).subs(y, pi) == ceiling(pi)
322
+ assert ceiling(y).rewrite(frac).subs(y, -E) == ceiling(-E)
323
+
324
+ assert Eq(ceiling(y), y + frac(-y))
325
+ assert Eq(ceiling(y), -floor(-y))
326
+
327
+ neg = Symbol('neg', negative=True)
328
+ nn = Symbol('nn', nonnegative=True)
329
+ pos = Symbol('pos', positive=True)
330
+ np = Symbol('np', nonpositive=True)
331
+
332
+ assert (ceiling(neg) <= 0) == True
333
+ assert (ceiling(neg) < 0) == (neg <= -1)
334
+ assert (ceiling(neg) > 0) == False
335
+ assert (ceiling(neg) >= 0) == (neg > -1)
336
+ assert (ceiling(neg) > -3) == (neg > -3)
337
+ assert (ceiling(neg) <= 10) == (neg <= 10)
338
+
339
+ assert (ceiling(nn) < 0) == False
340
+ assert (ceiling(nn) >= 0) == True
341
+
342
+ assert (ceiling(pos) < 0) == False
343
+ assert (ceiling(pos) <= 0) == False
344
+ assert (ceiling(pos) > 0) == True
345
+ assert (ceiling(pos) >= 0) == True
346
+ assert (ceiling(pos) >= 1) == True
347
+ assert (ceiling(pos) > 5) == (pos > 5)
348
+
349
+ assert (ceiling(np) <= 0) == True
350
+ assert (ceiling(np) > 0) == False
351
+
352
+ assert ceiling(neg).is_positive == False
353
+ assert ceiling(neg).is_nonpositive == True
354
+ assert ceiling(nn).is_positive is None
355
+ assert ceiling(nn).is_nonpositive is None
356
+ assert ceiling(pos).is_positive == True
357
+ assert ceiling(pos).is_nonpositive == False
358
+ assert ceiling(np).is_positive == False
359
+ assert ceiling(np).is_nonpositive == True
360
+
361
+ assert (ceiling(7, evaluate=False) >= 7) == True
362
+ assert (ceiling(7, evaluate=False) > 7) == False
363
+ assert (ceiling(7, evaluate=False) <= 7) == True
364
+ assert (ceiling(7, evaluate=False) < 7) == False
365
+
366
+ assert (ceiling(7, evaluate=False) >= 6) == True
367
+ assert (ceiling(7, evaluate=False) > 6) == True
368
+ assert (ceiling(7, evaluate=False) <= 6) == False
369
+ assert (ceiling(7, evaluate=False) < 6) == False
370
+
371
+ assert (ceiling(7, evaluate=False) >= 8) == False
372
+ assert (ceiling(7, evaluate=False) > 8) == False
373
+ assert (ceiling(7, evaluate=False) <= 8) == True
374
+ assert (ceiling(7, evaluate=False) < 8) == True
375
+
376
+ assert (ceiling(x) <= 5.5) == Le(ceiling(x), 5.5, evaluate=False)
377
+ assert (ceiling(x) >= -3.2) == Ge(ceiling(x), -3.2, evaluate=False)
378
+ assert (ceiling(x) < 2.9) == Lt(ceiling(x), 2.9, evaluate=False)
379
+ assert (ceiling(x) > -1.7) == Gt(ceiling(x), -1.7, evaluate=False)
380
+
381
+ assert (ceiling(y) <= 5.5) == (y <= 5)
382
+ assert (ceiling(y) >= -3.2) == (y > -4)
383
+ assert (ceiling(y) < 2.9) == (y <= 2)
384
+ assert (ceiling(y) > -1.7) == (y > -2)
385
+
386
+ assert (ceiling(y) <= n) == (y <= n)
387
+ assert (ceiling(y) >= n) == (y > n - 1)
388
+ assert (ceiling(y) < n) == (y <= n - 1)
389
+ assert (ceiling(y) > n) == (y > n)
390
+
391
+
392
+ def test_frac():
393
+ assert isinstance(frac(x), frac)
394
+ assert frac(oo) == AccumBounds(0, 1)
395
+ assert frac(-oo) == AccumBounds(0, 1)
396
+ assert frac(zoo) is nan
397
+
398
+ assert frac(n) == 0
399
+ assert frac(nan) is nan
400
+ assert frac(Rational(4, 3)) == Rational(1, 3)
401
+ assert frac(-Rational(4, 3)) == Rational(2, 3)
402
+ assert frac(Rational(-4, 3)) == Rational(2, 3)
403
+
404
+ r = Symbol('r', real=True)
405
+ assert frac(I*r) == I*frac(r)
406
+ assert frac(1 + I*r) == I*frac(r)
407
+ assert frac(0.5 + I*r) == 0.5 + I*frac(r)
408
+ assert frac(n + I*r) == I*frac(r)
409
+ assert frac(n + I*k) == 0
410
+ assert unchanged(frac, x + I*x)
411
+ assert frac(x + I*n) == frac(x)
412
+
413
+ assert frac(x).rewrite(floor) == x - floor(x)
414
+ assert frac(x).rewrite(ceiling) == x + ceiling(-x)
415
+ assert frac(y).rewrite(floor).subs(y, pi) == frac(pi)
416
+ assert frac(y).rewrite(floor).subs(y, -E) == frac(-E)
417
+ assert frac(y).rewrite(ceiling).subs(y, -pi) == frac(-pi)
418
+ assert frac(y).rewrite(ceiling).subs(y, E) == frac(E)
419
+
420
+ assert Eq(frac(y), y - floor(y))
421
+ assert Eq(frac(y), y + ceiling(-y))
422
+
423
+ r = Symbol('r', real=True)
424
+ p_i = Symbol('p_i', integer=True, positive=True)
425
+ n_i = Symbol('p_i', integer=True, negative=True)
426
+ np_i = Symbol('np_i', integer=True, nonpositive=True)
427
+ nn_i = Symbol('nn_i', integer=True, nonnegative=True)
428
+ p_r = Symbol('p_r', positive=True)
429
+ n_r = Symbol('n_r', negative=True)
430
+ np_r = Symbol('np_r', real=True, nonpositive=True)
431
+ nn_r = Symbol('nn_r', real=True, nonnegative=True)
432
+
433
+ # Real frac argument, integer rhs
434
+ assert frac(r) <= p_i
435
+ assert not frac(r) <= n_i
436
+ assert (frac(r) <= np_i).has(Le)
437
+ assert (frac(r) <= nn_i).has(Le)
438
+ assert frac(r) < p_i
439
+ assert not frac(r) < n_i
440
+ assert not frac(r) < np_i
441
+ assert (frac(r) < nn_i).has(Lt)
442
+ assert not frac(r) >= p_i
443
+ assert frac(r) >= n_i
444
+ assert frac(r) >= np_i
445
+ assert (frac(r) >= nn_i).has(Ge)
446
+ assert not frac(r) > p_i
447
+ assert frac(r) > n_i
448
+ assert (frac(r) > np_i).has(Gt)
449
+ assert (frac(r) > nn_i).has(Gt)
450
+
451
+ assert not Eq(frac(r), p_i)
452
+ assert not Eq(frac(r), n_i)
453
+ assert Eq(frac(r), np_i).has(Eq)
454
+ assert Eq(frac(r), nn_i).has(Eq)
455
+
456
+ assert Ne(frac(r), p_i)
457
+ assert Ne(frac(r), n_i)
458
+ assert Ne(frac(r), np_i).has(Ne)
459
+ assert Ne(frac(r), nn_i).has(Ne)
460
+
461
+
462
+ # Real frac argument, real rhs
463
+ assert (frac(r) <= p_r).has(Le)
464
+ assert not frac(r) <= n_r
465
+ assert (frac(r) <= np_r).has(Le)
466
+ assert (frac(r) <= nn_r).has(Le)
467
+ assert (frac(r) < p_r).has(Lt)
468
+ assert not frac(r) < n_r
469
+ assert not frac(r) < np_r
470
+ assert (frac(r) < nn_r).has(Lt)
471
+ assert (frac(r) >= p_r).has(Ge)
472
+ assert frac(r) >= n_r
473
+ assert frac(r) >= np_r
474
+ assert (frac(r) >= nn_r).has(Ge)
475
+ assert (frac(r) > p_r).has(Gt)
476
+ assert frac(r) > n_r
477
+ assert (frac(r) > np_r).has(Gt)
478
+ assert (frac(r) > nn_r).has(Gt)
479
+
480
+ assert not Eq(frac(r), n_r)
481
+ assert Eq(frac(r), p_r).has(Eq)
482
+ assert Eq(frac(r), np_r).has(Eq)
483
+ assert Eq(frac(r), nn_r).has(Eq)
484
+
485
+ assert Ne(frac(r), p_r).has(Ne)
486
+ assert Ne(frac(r), n_r)
487
+ assert Ne(frac(r), np_r).has(Ne)
488
+ assert Ne(frac(r), nn_r).has(Ne)
489
+
490
+ # Real frac argument, +/- oo rhs
491
+ assert frac(r) < oo
492
+ assert frac(r) <= oo
493
+ assert not frac(r) > oo
494
+ assert not frac(r) >= oo
495
+
496
+ assert not frac(r) < -oo
497
+ assert not frac(r) <= -oo
498
+ assert frac(r) > -oo
499
+ assert frac(r) >= -oo
500
+
501
+ assert frac(r) < 1
502
+ assert frac(r) <= 1
503
+ assert not frac(r) > 1
504
+ assert not frac(r) >= 1
505
+
506
+ assert not frac(r) < 0
507
+ assert (frac(r) <= 0).has(Le)
508
+ assert (frac(r) > 0).has(Gt)
509
+ assert frac(r) >= 0
510
+
511
+ # Some test for numbers
512
+ assert frac(r) <= sqrt(2)
513
+ assert (frac(r) <= sqrt(3) - sqrt(2)).has(Le)
514
+ assert not frac(r) <= sqrt(2) - sqrt(3)
515
+ assert not frac(r) >= sqrt(2)
516
+ assert (frac(r) >= sqrt(3) - sqrt(2)).has(Ge)
517
+ assert frac(r) >= sqrt(2) - sqrt(3)
518
+
519
+ assert not Eq(frac(r), sqrt(2))
520
+ assert Eq(frac(r), sqrt(3) - sqrt(2)).has(Eq)
521
+ assert not Eq(frac(r), sqrt(2) - sqrt(3))
522
+ assert Ne(frac(r), sqrt(2))
523
+ assert Ne(frac(r), sqrt(3) - sqrt(2)).has(Ne)
524
+ assert Ne(frac(r), sqrt(2) - sqrt(3))
525
+
526
+ assert frac(p_i, evaluate=False).is_zero
527
+ assert frac(p_i, evaluate=False).is_finite
528
+ assert frac(p_i, evaluate=False).is_integer
529
+ assert frac(p_i, evaluate=False).is_real
530
+ assert frac(r).is_finite
531
+ assert frac(r).is_real
532
+ assert frac(r).is_zero is None
533
+ assert frac(r).is_integer is None
534
+
535
+ assert frac(oo).is_finite
536
+ assert frac(oo).is_real
537
+
538
+
539
+ def test_series():
540
+ x, y = symbols('x,y')
541
+ assert floor(x).nseries(x, y, 100) == floor(y)
542
+ assert ceiling(x).nseries(x, y, 100) == ceiling(y)
543
+ assert floor(x).nseries(x, pi, 100) == 3
544
+ assert ceiling(x).nseries(x, pi, 100) == 4
545
+ assert floor(x).nseries(x, 0, 100) == 0
546
+ assert ceiling(x).nseries(x, 0, 100) == 1
547
+ assert floor(-x).nseries(x, 0, 100) == -1
548
+ assert ceiling(-x).nseries(x, 0, 100) == 0
549
+
550
+
551
+ def test_issue_14355():
552
+ # This test checks the leading term and series for the floor and ceil
553
+ # function when arg0 evaluates to S.NaN.
554
+ assert floor((x**3 + x)/(x**2 - x)).as_leading_term(x, cdir = 1) == -2
555
+ assert floor((x**3 + x)/(x**2 - x)).as_leading_term(x, cdir = -1) == -1
556
+ assert floor((cos(x) - 1)/x).as_leading_term(x, cdir = 1) == -1
557
+ assert floor((cos(x) - 1)/x).as_leading_term(x, cdir = -1) == 0
558
+ assert floor(sin(x)/x).as_leading_term(x, cdir = 1) == 0
559
+ assert floor(sin(x)/x).as_leading_term(x, cdir = -1) == 0
560
+ assert floor(-tan(x)/x).as_leading_term(x, cdir = 1) == -2
561
+ assert floor(-tan(x)/x).as_leading_term(x, cdir = -1) == -2
562
+ assert floor(sin(x)/x/3).as_leading_term(x, cdir = 1) == 0
563
+ assert floor(sin(x)/x/3).as_leading_term(x, cdir = -1) == 0
564
+ assert ceiling((x**3 + x)/(x**2 - x)).as_leading_term(x, cdir = 1) == -1
565
+ assert ceiling((x**3 + x)/(x**2 - x)).as_leading_term(x, cdir = -1) == 0
566
+ assert ceiling((cos(x) - 1)/x).as_leading_term(x, cdir = 1) == 0
567
+ assert ceiling((cos(x) - 1)/x).as_leading_term(x, cdir = -1) == 1
568
+ assert ceiling(sin(x)/x).as_leading_term(x, cdir = 1) == 1
569
+ assert ceiling(sin(x)/x).as_leading_term(x, cdir = -1) == 1
570
+ assert ceiling(-tan(x)/x).as_leading_term(x, cdir = 1) == -1
571
+ assert ceiling(-tan(x)/x).as_leading_term(x, cdir = 1) == -1
572
+ assert ceiling(sin(x)/x/3).as_leading_term(x, cdir = 1) == 1
573
+ assert ceiling(sin(x)/x/3).as_leading_term(x, cdir = -1) == 1
574
+ # test for series
575
+ assert floor(sin(x)/x).series(x, 0, 100, cdir = 1) == 0
576
+ assert floor(sin(x)/x).series(x, 0, 100, cdir = 1) == 0
577
+ assert floor((x**3 + x)/(x**2 - x)).series(x, 0, 100, cdir = 1) == -2
578
+ assert floor((x**3 + x)/(x**2 - x)).series(x, 0, 100, cdir = -1) == -1
579
+ assert ceiling(sin(x)/x).series(x, 0, 100, cdir = 1) == 1
580
+ assert ceiling(sin(x)/x).series(x, 0, 100, cdir = -1) == 1
581
+ assert ceiling((x**3 + x)/(x**2 - x)).series(x, 0, 100, cdir = 1) == -1
582
+ assert ceiling((x**3 + x)/(x**2 - x)).series(x, 0, 100, cdir = -1) == 0
583
+
584
+
585
+ def test_frac_leading_term():
586
+ assert frac(x).as_leading_term(x) == x
587
+ assert frac(x).as_leading_term(x, cdir = 1) == x
588
+ assert frac(x).as_leading_term(x, cdir = -1) == 1
589
+ assert frac(x + S.Half).as_leading_term(x, cdir = 1) == S.Half
590
+ assert frac(x + S.Half).as_leading_term(x, cdir = -1) == S.Half
591
+ assert frac(-2*x + 1).as_leading_term(x, cdir = 1) == S.One
592
+ assert frac(-2*x + 1).as_leading_term(x, cdir = -1) == -2*x
593
+ assert frac(sin(x) + 5).as_leading_term(x, cdir = 1) == x
594
+ assert frac(sin(x) + 5).as_leading_term(x, cdir = -1) == S.One
595
+ assert frac(sin(x**2) + 5).as_leading_term(x, cdir = 1) == x**2
596
+ assert frac(sin(x**2) + 5).as_leading_term(x, cdir = -1) == x**2
597
+
598
+
599
+ @XFAIL
600
+ def test_issue_4149():
601
+ assert floor(3 + pi*I + y*I) == 3 + floor(pi + y)*I
602
+ assert floor(3*I + pi*I + y*I) == floor(3 + pi + y)*I
603
+ assert floor(3 + E + pi*I + y*I) == 5 + floor(pi + y)*I
604
+
605
+
606
+ def test_issue_21651():
607
+ k = Symbol('k', positive=True, integer=True)
608
+ exp = 2*2**(-k)
609
+ assert isinstance(floor(exp), floor)
610
+
611
+
612
+ def test_issue_11207():
613
+ assert floor(floor(x)) == floor(x)
614
+ assert floor(ceiling(x)) == ceiling(x)
615
+ assert ceiling(floor(x)) == floor(x)
616
+ assert ceiling(ceiling(x)) == ceiling(x)
617
+
618
+
619
+ def test_nested_floor_ceiling():
620
+ assert floor(-floor(ceiling(x**3)/y)) == -floor(ceiling(x**3)/y)
621
+ assert ceiling(-floor(ceiling(x**3)/y)) == -floor(ceiling(x**3)/y)
622
+ assert floor(ceiling(-floor(x**Rational(7, 2)/y))) == -floor(x**Rational(7, 2)/y)
623
+ assert -ceiling(-ceiling(floor(x)/y)) == ceiling(floor(x)/y)
624
+
625
+ def test_issue_18689():
626
+ assert floor(floor(floor(x)) + 3) == floor(x) + 3
627
+ assert ceiling(ceiling(ceiling(x)) + 1) == ceiling(x) + 1
628
+ assert ceiling(ceiling(floor(x)) + 3) == floor(x) + 3
629
+
630
+ def test_issue_18421():
631
+ assert floor(float(0)) is S.Zero
632
+ assert ceiling(float(0)) is S.Zero
venv/lib/python3.10/site-packages/sympy/functions/special/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Stub __init__.py for the sympy.functions.special package
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (191 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/bessel.cpython-310.pyc ADDED
Binary file (58.7 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/beta_functions.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/bsplines.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/delta_functions.cpython-310.pyc ADDED
Binary file (18.6 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/elliptic_integrals.cpython-310.pyc ADDED
Binary file (14.5 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/error_functions.cpython-310.pyc ADDED
Binary file (78.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/gamma_functions.cpython-310.pyc ADDED
Binary file (41.3 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/hyper.cpython-310.pyc ADDED
Binary file (40.3 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/mathieu_functions.cpython-310.pyc ADDED
Binary file (7.08 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/polynomials.cpython-310.pyc ADDED
Binary file (39.4 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/singularity_functions.cpython-310.pyc ADDED
Binary file (7.95 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/spherical_harmonics.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/tensor_functions.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/__pycache__/zeta_functions.cpython-310.pyc ADDED
Binary file (23.1 kB). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/functions/special/benchmarks/__pycache__/bench_special.cpython-310.pyc ADDED
Binary file (491 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/functions/special/benchmarks/bench_special.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import symbols
2
+ from sympy.functions.special.spherical_harmonics import Ynm
3
+
4
+ x, y = symbols('x,y')
5
+
6
+
7
+ def timeit_Ynm_xy():
8
+ Ynm(1, 1, x, y)
venv/lib/python3.10/site-packages/sympy/functions/special/bessel.py ADDED
@@ -0,0 +1,2089 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import wraps
2
+
3
+ from sympy.core import S
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, _mexpand
8
+ from sympy.core.logic import fuzzy_or, fuzzy_not
9
+ from sympy.core.numbers import Rational, pi, I
10
+ from sympy.core.power import Pow
11
+ from sympy.core.symbol import Dummy, Wild
12
+ from sympy.core.sympify import sympify
13
+ from sympy.functions.combinatorial.factorials import factorial
14
+ from sympy.functions.elementary.trigonometric import sin, cos, csc, cot
15
+ from sympy.functions.elementary.integers import ceiling
16
+ from sympy.functions.elementary.exponential import exp, log
17
+ from sympy.functions.elementary.miscellaneous import cbrt, sqrt, root
18
+ from sympy.functions.elementary.complexes import (Abs, re, im, polar_lift, unpolarify)
19
+ from sympy.functions.special.gamma_functions import gamma, digamma, uppergamma
20
+ from sympy.functions.special.hyper import hyper
21
+ from sympy.polys.orthopolys import spherical_bessel_fn
22
+
23
+ from mpmath import mp, workprec
24
+
25
+ # TODO
26
+ # o Scorer functions G1 and G2
27
+ # o Asymptotic expansions
28
+ # These are possible, e.g. for fixed order, but since the bessel type
29
+ # functions are oscillatory they are not actually tractable at
30
+ # infinity, so this is not particularly useful right now.
31
+ # o Nicer series expansions.
32
+ # o More rewriting.
33
+ # o Add solvers to ode.py (or rather add solvers for the hypergeometric equation).
34
+
35
+
36
+ class BesselBase(Function):
37
+ """
38
+ Abstract base class for Bessel-type functions.
39
+
40
+ This class is meant to reduce code duplication.
41
+ All Bessel-type functions can 1) be differentiated, with the derivatives
42
+ expressed in terms of similar functions, and 2) be rewritten in terms
43
+ of other Bessel-type functions.
44
+
45
+ Here, Bessel-type functions are assumed to have one complex parameter.
46
+
47
+ To use this base class, define class attributes ``_a`` and ``_b`` such that
48
+ ``2*F_n' = -_a*F_{n+1} + b*F_{n-1}``.
49
+
50
+ """
51
+
52
+ @property
53
+ def order(self):
54
+ """ The order of the Bessel-type function. """
55
+ return self.args[0]
56
+
57
+ @property
58
+ def argument(self):
59
+ """ The argument of the Bessel-type function. """
60
+ return self.args[1]
61
+
62
+ @classmethod
63
+ def eval(cls, nu, z):
64
+ return
65
+
66
+ def fdiff(self, argindex=2):
67
+ if argindex != 2:
68
+ raise ArgumentIndexError(self, argindex)
69
+ return (self._b/2 * self.__class__(self.order - 1, self.argument) -
70
+ self._a/2 * self.__class__(self.order + 1, self.argument))
71
+
72
+ def _eval_conjugate(self):
73
+ z = self.argument
74
+ if z.is_extended_negative is False:
75
+ return self.__class__(self.order.conjugate(), z.conjugate())
76
+
77
+ def _eval_is_meromorphic(self, x, a):
78
+ nu, z = self.order, self.argument
79
+
80
+ if nu.has(x):
81
+ return False
82
+ if not z._eval_is_meromorphic(x, a):
83
+ return None
84
+ z0 = z.subs(x, a)
85
+ if nu.is_integer:
86
+ if isinstance(self, (besselj, besseli, hn1, hn2, jn, yn)) or not nu.is_zero:
87
+ return fuzzy_not(z0.is_infinite)
88
+ return fuzzy_not(fuzzy_or([z0.is_zero, z0.is_infinite]))
89
+
90
+ def _eval_expand_func(self, **hints):
91
+ nu, z, f = self.order, self.argument, self.__class__
92
+ if nu.is_real:
93
+ if (nu - 1).is_positive:
94
+ return (-self._a*self._b*f(nu - 2, z)._eval_expand_func() +
95
+ 2*self._a*(nu - 1)*f(nu - 1, z)._eval_expand_func()/z)
96
+ elif (nu + 1).is_negative:
97
+ return (2*self._b*(nu + 1)*f(nu + 1, z)._eval_expand_func()/z -
98
+ self._a*self._b*f(nu + 2, z)._eval_expand_func())
99
+ return self
100
+
101
+ def _eval_simplify(self, **kwargs):
102
+ from sympy.simplify.simplify import besselsimp
103
+ return besselsimp(self)
104
+
105
+
106
+ class besselj(BesselBase):
107
+ r"""
108
+ Bessel function of the first kind.
109
+
110
+ Explanation
111
+ ===========
112
+
113
+ The Bessel $J$ function of order $\nu$ is defined to be the function
114
+ satisfying Bessel's differential equation
115
+
116
+ .. math ::
117
+ z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2}
118
+ + z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 - \nu^2) w = 0,
119
+
120
+ with Laurent expansion
121
+
122
+ .. math ::
123
+ J_\nu(z) = z^\nu \left(\frac{1}{\Gamma(\nu + 1) 2^\nu} + O(z^2) \right),
124
+
125
+ if $\nu$ is not a negative integer. If $\nu=-n \in \mathbb{Z}_{<0}$
126
+ *is* a negative integer, then the definition is
127
+
128
+ .. math ::
129
+ J_{-n}(z) = (-1)^n J_n(z).
130
+
131
+ Examples
132
+ ========
133
+
134
+ Create a Bessel function object:
135
+
136
+ >>> from sympy import besselj, jn
137
+ >>> from sympy.abc import z, n
138
+ >>> b = besselj(n, z)
139
+
140
+ Differentiate it:
141
+
142
+ >>> b.diff(z)
143
+ besselj(n - 1, z)/2 - besselj(n + 1, z)/2
144
+
145
+ Rewrite in terms of spherical Bessel functions:
146
+
147
+ >>> b.rewrite(jn)
148
+ sqrt(2)*sqrt(z)*jn(n - 1/2, z)/sqrt(pi)
149
+
150
+ Access the parameter and argument:
151
+
152
+ >>> b.order
153
+ n
154
+ >>> b.argument
155
+ z
156
+
157
+ See Also
158
+ ========
159
+
160
+ bessely, besseli, besselk
161
+
162
+ References
163
+ ==========
164
+
165
+ .. [1] Abramowitz, Milton; Stegun, Irene A., eds. (1965), "Chapter 9",
166
+ Handbook of Mathematical Functions with Formulas, Graphs, and
167
+ Mathematical Tables
168
+ .. [2] Luke, Y. L. (1969), The Special Functions and Their
169
+ Approximations, Volume 1
170
+ .. [3] https://en.wikipedia.org/wiki/Bessel_function
171
+ .. [4] https://functions.wolfram.com/Bessel-TypeFunctions/BesselJ/
172
+
173
+ """
174
+
175
+ _a = S.One
176
+ _b = S.One
177
+
178
+ @classmethod
179
+ def eval(cls, nu, z):
180
+ if z.is_zero:
181
+ if nu.is_zero:
182
+ return S.One
183
+ elif (nu.is_integer and nu.is_zero is False) or re(nu).is_positive:
184
+ return S.Zero
185
+ elif re(nu).is_negative and not (nu.is_integer is True):
186
+ return S.ComplexInfinity
187
+ elif nu.is_imaginary:
188
+ return S.NaN
189
+ if z in (S.Infinity, S.NegativeInfinity):
190
+ return S.Zero
191
+
192
+ if z.could_extract_minus_sign():
193
+ return (z)**nu*(-z)**(-nu)*besselj(nu, -z)
194
+ if nu.is_integer:
195
+ if nu.could_extract_minus_sign():
196
+ return S.NegativeOne**(-nu)*besselj(-nu, z)
197
+ newz = z.extract_multiplicatively(I)
198
+ if newz: # NOTE we don't want to change the function if z==0
199
+ return I**(nu)*besseli(nu, newz)
200
+
201
+ # branch handling:
202
+ if nu.is_integer:
203
+ newz = unpolarify(z)
204
+ if newz != z:
205
+ return besselj(nu, newz)
206
+ else:
207
+ newz, n = z.extract_branch_factor()
208
+ if n != 0:
209
+ return exp(2*n*pi*nu*I)*besselj(nu, newz)
210
+ nnu = unpolarify(nu)
211
+ if nu != nnu:
212
+ return besselj(nnu, z)
213
+
214
+ def _eval_rewrite_as_besseli(self, nu, z, **kwargs):
215
+ return exp(I*pi*nu/2)*besseli(nu, polar_lift(-I)*z)
216
+
217
+ def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
218
+ if nu.is_integer is False:
219
+ return csc(pi*nu)*bessely(-nu, z) - cot(pi*nu)*bessely(nu, z)
220
+
221
+ def _eval_rewrite_as_jn(self, nu, z, **kwargs):
222
+ return sqrt(2*z/pi)*jn(nu - S.Half, self.argument)
223
+
224
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
225
+ nu, z = self.args
226
+ try:
227
+ arg = z.as_leading_term(x)
228
+ except NotImplementedError:
229
+ return self
230
+ c, e = arg.as_coeff_exponent(x)
231
+
232
+ if e.is_positive:
233
+ return arg**nu/(2**nu*gamma(nu + 1))
234
+ elif e.is_negative:
235
+ cdir = 1 if cdir == 0 else cdir
236
+ sign = c*cdir**e
237
+ if not sign.is_negative:
238
+ # Refer Abramowitz and Stegun 1965, p. 364 for more information on
239
+ # asymptotic approximation of besselj function.
240
+ return sqrt(2)*cos(z - pi*(2*nu + 1)/4)/sqrt(pi*z)
241
+ return self
242
+
243
+ return super(besselj, self)._eval_as_leading_term(x, logx, cdir)
244
+
245
+ def _eval_is_extended_real(self):
246
+ nu, z = self.args
247
+ if nu.is_integer and z.is_extended_real:
248
+ return True
249
+
250
+ def _eval_nseries(self, x, n, logx, cdir=0):
251
+ # Refer https://functions.wolfram.com/Bessel-TypeFunctions/BesselJ/06/01/04/01/01/0003/
252
+ # for more information on nseries expansion of besselj function.
253
+ from sympy.series.order import Order
254
+ nu, z = self.args
255
+
256
+ # In case of powers less than 1, number of terms need to be computed
257
+ # separately to avoid repeated callings of _eval_nseries with wrong n
258
+ try:
259
+ _, exp = z.leadterm(x)
260
+ except (ValueError, NotImplementedError):
261
+ return self
262
+
263
+ if exp.is_positive:
264
+ newn = ceiling(n/exp)
265
+ o = Order(x**n, x)
266
+ r = (z/2)._eval_nseries(x, n, logx, cdir).removeO()
267
+ if r is S.Zero:
268
+ return o
269
+ t = (_mexpand(r**2) + o).removeO()
270
+
271
+ term = r**nu/gamma(nu + 1)
272
+ s = [term]
273
+ for k in range(1, (newn + 1)//2):
274
+ term *= -t/(k*(nu + k))
275
+ term = (_mexpand(term) + o).removeO()
276
+ s.append(term)
277
+ return Add(*s) + o
278
+
279
+ return super(besselj, self)._eval_nseries(x, n, logx, cdir)
280
+
281
+
282
+ class bessely(BesselBase):
283
+ r"""
284
+ Bessel function of the second kind.
285
+
286
+ Explanation
287
+ ===========
288
+
289
+ The Bessel $Y$ function of order $\nu$ is defined as
290
+
291
+ .. math ::
292
+ Y_\nu(z) = \lim_{\mu \to \nu} \frac{J_\mu(z) \cos(\pi \mu)
293
+ - J_{-\mu}(z)}{\sin(\pi \mu)},
294
+
295
+ where $J_\mu(z)$ is the Bessel function of the first kind.
296
+
297
+ It is a solution to Bessel's equation, and linearly independent from
298
+ $J_\nu$.
299
+
300
+ Examples
301
+ ========
302
+
303
+ >>> from sympy import bessely, yn
304
+ >>> from sympy.abc import z, n
305
+ >>> b = bessely(n, z)
306
+ >>> b.diff(z)
307
+ bessely(n - 1, z)/2 - bessely(n + 1, z)/2
308
+ >>> b.rewrite(yn)
309
+ sqrt(2)*sqrt(z)*yn(n - 1/2, z)/sqrt(pi)
310
+
311
+ See Also
312
+ ========
313
+
314
+ besselj, besseli, besselk
315
+
316
+ References
317
+ ==========
318
+
319
+ .. [1] https://functions.wolfram.com/Bessel-TypeFunctions/BesselY/
320
+
321
+ """
322
+
323
+ _a = S.One
324
+ _b = S.One
325
+
326
+ @classmethod
327
+ def eval(cls, nu, z):
328
+ if z.is_zero:
329
+ if nu.is_zero:
330
+ return S.NegativeInfinity
331
+ elif re(nu).is_zero is False:
332
+ return S.ComplexInfinity
333
+ elif re(nu).is_zero:
334
+ return S.NaN
335
+ if z in (S.Infinity, S.NegativeInfinity):
336
+ return S.Zero
337
+ if z == I*S.Infinity:
338
+ return exp(I*pi*(nu + 1)/2) * S.Infinity
339
+ if z == I*S.NegativeInfinity:
340
+ return exp(-I*pi*(nu + 1)/2) * S.Infinity
341
+
342
+ if nu.is_integer:
343
+ if nu.could_extract_minus_sign():
344
+ return S.NegativeOne**(-nu)*bessely(-nu, z)
345
+
346
+ def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
347
+ if nu.is_integer is False:
348
+ return csc(pi*nu)*(cos(pi*nu)*besselj(nu, z) - besselj(-nu, z))
349
+
350
+ def _eval_rewrite_as_besseli(self, nu, z, **kwargs):
351
+ aj = self._eval_rewrite_as_besselj(*self.args)
352
+ if aj:
353
+ return aj.rewrite(besseli)
354
+
355
+ def _eval_rewrite_as_yn(self, nu, z, **kwargs):
356
+ return sqrt(2*z/pi) * yn(nu - S.Half, self.argument)
357
+
358
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
359
+ nu, z = self.args
360
+ try:
361
+ arg = z.as_leading_term(x)
362
+ except NotImplementedError:
363
+ return self
364
+ c, e = arg.as_coeff_exponent(x)
365
+
366
+ if e.is_positive:
367
+ term_one = ((2/pi)*log(z/2)*besselj(nu, z))
368
+ term_two = -(z/2)**(-nu)*factorial(nu - 1)/pi if (nu).is_positive else S.Zero
369
+ term_three = -(z/2)**nu/(pi*factorial(nu))*(digamma(nu + 1) - S.EulerGamma)
370
+ arg = Add(*[term_one, term_two, term_three]).as_leading_term(x, logx=logx)
371
+ return arg
372
+ elif e.is_negative:
373
+ cdir = 1 if cdir == 0 else cdir
374
+ sign = c*cdir**e
375
+ if not sign.is_negative:
376
+ # Refer Abramowitz and Stegun 1965, p. 364 for more information on
377
+ # asymptotic approximation of bessely function.
378
+ return sqrt(2)*(-sin(pi*nu/2 - z + pi/4) + 3*cos(pi*nu/2 - z + pi/4)/(8*z))*sqrt(1/z)/sqrt(pi)
379
+ return self
380
+
381
+ return super(bessely, self)._eval_as_leading_term(x, logx, cdir)
382
+
383
+ def _eval_is_extended_real(self):
384
+ nu, z = self.args
385
+ if nu.is_integer and z.is_positive:
386
+ return True
387
+
388
+ def _eval_nseries(self, x, n, logx, cdir=0):
389
+ # Refer https://functions.wolfram.com/Bessel-TypeFunctions/BesselY/06/01/04/01/02/0008/
390
+ # for more information on nseries expansion of bessely function.
391
+ from sympy.series.order import Order
392
+ nu, z = self.args
393
+
394
+ # In case of powers less than 1, number of terms need to be computed
395
+ # separately to avoid repeated callings of _eval_nseries with wrong n
396
+ try:
397
+ _, exp = z.leadterm(x)
398
+ except (ValueError, NotImplementedError):
399
+ return self
400
+
401
+ if exp.is_positive and nu.is_integer:
402
+ newn = ceiling(n/exp)
403
+ bn = besselj(nu, z)
404
+ a = ((2/pi)*log(z/2)*bn)._eval_nseries(x, n, logx, cdir)
405
+
406
+ b, c = [], []
407
+ o = Order(x**n, x)
408
+ r = (z/2)._eval_nseries(x, n, logx, cdir).removeO()
409
+ if r is S.Zero:
410
+ return o
411
+ t = (_mexpand(r**2) + o).removeO()
412
+
413
+ if nu > S.Zero:
414
+ term = r**(-nu)*factorial(nu - 1)/pi
415
+ b.append(term)
416
+ for k in range(1, nu):
417
+ denom = (nu - k)*k
418
+ if denom == S.Zero:
419
+ term *= t/k
420
+ else:
421
+ term *= t/denom
422
+ term = (_mexpand(term) + o).removeO()
423
+ b.append(term)
424
+
425
+ p = r**nu/(pi*factorial(nu))
426
+ term = p*(digamma(nu + 1) - S.EulerGamma)
427
+ c.append(term)
428
+ for k in range(1, (newn + 1)//2):
429
+ p *= -t/(k*(k + nu))
430
+ p = (_mexpand(p) + o).removeO()
431
+ term = p*(digamma(k + nu + 1) + digamma(k + 1))
432
+ c.append(term)
433
+ return a - Add(*b) - Add(*c) # Order term comes from a
434
+
435
+ return super(bessely, self)._eval_nseries(x, n, logx, cdir)
436
+
437
+
438
+ class besseli(BesselBase):
439
+ r"""
440
+ Modified Bessel function of the first kind.
441
+
442
+ Explanation
443
+ ===========
444
+
445
+ The Bessel $I$ function is a solution to the modified Bessel equation
446
+
447
+ .. math ::
448
+ z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2}
449
+ + z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 + \nu^2)^2 w = 0.
450
+
451
+ It can be defined as
452
+
453
+ .. math ::
454
+ I_\nu(z) = i^{-\nu} J_\nu(iz),
455
+
456
+ where $J_\nu(z)$ is the Bessel function of the first kind.
457
+
458
+ Examples
459
+ ========
460
+
461
+ >>> from sympy import besseli
462
+ >>> from sympy.abc import z, n
463
+ >>> besseli(n, z).diff(z)
464
+ besseli(n - 1, z)/2 + besseli(n + 1, z)/2
465
+
466
+ See Also
467
+ ========
468
+
469
+ besselj, bessely, besselk
470
+
471
+ References
472
+ ==========
473
+
474
+ .. [1] https://functions.wolfram.com/Bessel-TypeFunctions/BesselI/
475
+
476
+ """
477
+
478
+ _a = -S.One
479
+ _b = S.One
480
+
481
+ @classmethod
482
+ def eval(cls, nu, z):
483
+ if z.is_zero:
484
+ if nu.is_zero:
485
+ return S.One
486
+ elif (nu.is_integer and nu.is_zero is False) or re(nu).is_positive:
487
+ return S.Zero
488
+ elif re(nu).is_negative and not (nu.is_integer is True):
489
+ return S.ComplexInfinity
490
+ elif nu.is_imaginary:
491
+ return S.NaN
492
+ if im(z) in (S.Infinity, S.NegativeInfinity):
493
+ return S.Zero
494
+ if z is S.Infinity:
495
+ return S.Infinity
496
+ if z is S.NegativeInfinity:
497
+ return (-1)**nu*S.Infinity
498
+
499
+ if z.could_extract_minus_sign():
500
+ return (z)**nu*(-z)**(-nu)*besseli(nu, -z)
501
+ if nu.is_integer:
502
+ if nu.could_extract_minus_sign():
503
+ return besseli(-nu, z)
504
+ newz = z.extract_multiplicatively(I)
505
+ if newz: # NOTE we don't want to change the function if z==0
506
+ return I**(-nu)*besselj(nu, -newz)
507
+
508
+ # branch handling:
509
+ if nu.is_integer:
510
+ newz = unpolarify(z)
511
+ if newz != z:
512
+ return besseli(nu, newz)
513
+ else:
514
+ newz, n = z.extract_branch_factor()
515
+ if n != 0:
516
+ return exp(2*n*pi*nu*I)*besseli(nu, newz)
517
+ nnu = unpolarify(nu)
518
+ if nu != nnu:
519
+ return besseli(nnu, z)
520
+
521
+ def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
522
+ return exp(-I*pi*nu/2)*besselj(nu, polar_lift(I)*z)
523
+
524
+ def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
525
+ aj = self._eval_rewrite_as_besselj(*self.args)
526
+ if aj:
527
+ return aj.rewrite(bessely)
528
+
529
+ def _eval_rewrite_as_jn(self, nu, z, **kwargs):
530
+ return self._eval_rewrite_as_besselj(*self.args).rewrite(jn)
531
+
532
+ def _eval_is_extended_real(self):
533
+ nu, z = self.args
534
+ if nu.is_integer and z.is_extended_real:
535
+ return True
536
+
537
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
538
+ nu, z = self.args
539
+ try:
540
+ arg = z.as_leading_term(x)
541
+ except NotImplementedError:
542
+ return self
543
+ c, e = arg.as_coeff_exponent(x)
544
+
545
+ if e.is_positive:
546
+ return arg**nu/(2**nu*gamma(nu + 1))
547
+ elif e.is_negative:
548
+ cdir = 1 if cdir == 0 else cdir
549
+ sign = c*cdir**e
550
+ if not sign.is_negative:
551
+ # Refer Abramowitz and Stegun 1965, p. 377 for more information on
552
+ # asymptotic approximation of besseli function.
553
+ return exp(z)/sqrt(2*pi*z)
554
+ return self
555
+
556
+ return super(besseli, self)._eval_as_leading_term(x, logx, cdir)
557
+
558
+ def _eval_nseries(self, x, n, logx, cdir=0):
559
+ # Refer https://functions.wolfram.com/Bessel-TypeFunctions/BesselI/06/01/04/01/01/0003/
560
+ # for more information on nseries expansion of besseli function.
561
+ from sympy.series.order import Order
562
+ nu, z = self.args
563
+
564
+ # In case of powers less than 1, number of terms need to be computed
565
+ # separately to avoid repeated callings of _eval_nseries with wrong n
566
+ try:
567
+ _, exp = z.leadterm(x)
568
+ except (ValueError, NotImplementedError):
569
+ return self
570
+
571
+ if exp.is_positive:
572
+ newn = ceiling(n/exp)
573
+ o = Order(x**n, x)
574
+ r = (z/2)._eval_nseries(x, n, logx, cdir).removeO()
575
+ if r is S.Zero:
576
+ return o
577
+ t = (_mexpand(r**2) + o).removeO()
578
+
579
+ term = r**nu/gamma(nu + 1)
580
+ s = [term]
581
+ for k in range(1, (newn + 1)//2):
582
+ term *= t/(k*(nu + k))
583
+ term = (_mexpand(term) + o).removeO()
584
+ s.append(term)
585
+ return Add(*s) + o
586
+
587
+ return super(besseli, self)._eval_nseries(x, n, logx, cdir)
588
+
589
+
590
+ class besselk(BesselBase):
591
+ r"""
592
+ Modified Bessel function of the second kind.
593
+
594
+ Explanation
595
+ ===========
596
+
597
+ The Bessel $K$ function of order $\nu$ is defined as
598
+
599
+ .. math ::
600
+ K_\nu(z) = \lim_{\mu \to \nu} \frac{\pi}{2}
601
+ \frac{I_{-\mu}(z) -I_\mu(z)}{\sin(\pi \mu)},
602
+
603
+ where $I_\mu(z)$ is the modified Bessel function of the first kind.
604
+
605
+ It is a solution of the modified Bessel equation, and linearly independent
606
+ from $Y_\nu$.
607
+
608
+ Examples
609
+ ========
610
+
611
+ >>> from sympy import besselk
612
+ >>> from sympy.abc import z, n
613
+ >>> besselk(n, z).diff(z)
614
+ -besselk(n - 1, z)/2 - besselk(n + 1, z)/2
615
+
616
+ See Also
617
+ ========
618
+
619
+ besselj, besseli, bessely
620
+
621
+ References
622
+ ==========
623
+
624
+ .. [1] https://functions.wolfram.com/Bessel-TypeFunctions/BesselK/
625
+
626
+ """
627
+
628
+ _a = S.One
629
+ _b = -S.One
630
+
631
+ @classmethod
632
+ def eval(cls, nu, z):
633
+ if z.is_zero:
634
+ if nu.is_zero:
635
+ return S.Infinity
636
+ elif re(nu).is_zero is False:
637
+ return S.ComplexInfinity
638
+ elif re(nu).is_zero:
639
+ return S.NaN
640
+ if z in (S.Infinity, I*S.Infinity, I*S.NegativeInfinity):
641
+ return S.Zero
642
+
643
+ if nu.is_integer:
644
+ if nu.could_extract_minus_sign():
645
+ return besselk(-nu, z)
646
+
647
+ def _eval_rewrite_as_besseli(self, nu, z, **kwargs):
648
+ if nu.is_integer is False:
649
+ return pi*csc(pi*nu)*(besseli(-nu, z) - besseli(nu, z))/2
650
+
651
+ def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
652
+ ai = self._eval_rewrite_as_besseli(*self.args)
653
+ if ai:
654
+ return ai.rewrite(besselj)
655
+
656
+ def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
657
+ aj = self._eval_rewrite_as_besselj(*self.args)
658
+ if aj:
659
+ return aj.rewrite(bessely)
660
+
661
+ def _eval_rewrite_as_yn(self, nu, z, **kwargs):
662
+ ay = self._eval_rewrite_as_bessely(*self.args)
663
+ if ay:
664
+ return ay.rewrite(yn)
665
+
666
+ def _eval_is_extended_real(self):
667
+ nu, z = self.args
668
+ if nu.is_integer and z.is_positive:
669
+ return True
670
+
671
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
672
+ nu, z = self.args
673
+ try:
674
+ arg = z.as_leading_term(x)
675
+ except NotImplementedError:
676
+ return self
677
+ _, e = arg.as_coeff_exponent(x)
678
+
679
+ if e.is_positive:
680
+ term_one = ((-1)**(nu -1)*log(z/2)*besseli(nu, z))
681
+ term_two = (z/2)**(-nu)*factorial(nu - 1)/2 if (nu).is_positive else S.Zero
682
+ term_three = (-1)**nu*(z/2)**nu/(2*factorial(nu))*(digamma(nu + 1) - S.EulerGamma)
683
+ arg = Add(*[term_one, term_two, term_three]).as_leading_term(x, logx=logx)
684
+ return arg
685
+ elif e.is_negative:
686
+ # Refer Abramowitz and Stegun 1965, p. 378 for more information on
687
+ # asymptotic approximation of besselk function.
688
+ return sqrt(pi)*exp(-z)/sqrt(2*z)
689
+
690
+ return super(besselk, self)._eval_as_leading_term(x, logx, cdir)
691
+
692
+ def _eval_nseries(self, x, n, logx, cdir=0):
693
+ # Refer https://functions.wolfram.com/Bessel-TypeFunctions/BesselK/06/01/04/01/02/0008/
694
+ # for more information on nseries expansion of besselk function.
695
+ from sympy.series.order import Order
696
+ nu, z = self.args
697
+
698
+ # In case of powers less than 1, number of terms need to be computed
699
+ # separately to avoid repeated callings of _eval_nseries with wrong n
700
+ try:
701
+ _, exp = z.leadterm(x)
702
+ except (ValueError, NotImplementedError):
703
+ return self
704
+
705
+ if exp.is_positive and nu.is_integer:
706
+ newn = ceiling(n/exp)
707
+ bn = besseli(nu, z)
708
+ a = ((-1)**(nu - 1)*log(z/2)*bn)._eval_nseries(x, n, logx, cdir)
709
+
710
+ b, c = [], []
711
+ o = Order(x**n, x)
712
+ r = (z/2)._eval_nseries(x, n, logx, cdir).removeO()
713
+ if r is S.Zero:
714
+ return o
715
+ t = (_mexpand(r**2) + o).removeO()
716
+
717
+ if nu > S.Zero:
718
+ term = r**(-nu)*factorial(nu - 1)/2
719
+ b.append(term)
720
+ for k in range(1, nu):
721
+ denom = (k - nu)*k
722
+ if denom == S.Zero:
723
+ term *= t/k
724
+ else:
725
+ term *= t/denom
726
+ term = (_mexpand(term) + o).removeO()
727
+ b.append(term)
728
+
729
+ p = r**nu*(-1)**nu/(2*factorial(nu))
730
+ term = p*(digamma(nu + 1) - S.EulerGamma)
731
+ c.append(term)
732
+ for k in range(1, (newn + 1)//2):
733
+ p *= t/(k*(k + nu))
734
+ p = (_mexpand(p) + o).removeO()
735
+ term = p*(digamma(k + nu + 1) + digamma(k + 1))
736
+ c.append(term)
737
+ return a + Add(*b) + Add(*c) # Order term comes from a
738
+
739
+ return super(besselk, self)._eval_nseries(x, n, logx, cdir)
740
+
741
+
742
+ class hankel1(BesselBase):
743
+ r"""
744
+ Hankel function of the first kind.
745
+
746
+ Explanation
747
+ ===========
748
+
749
+ This function is defined as
750
+
751
+ .. math ::
752
+ H_\nu^{(1)} = J_\nu(z) + iY_\nu(z),
753
+
754
+ where $J_\nu(z)$ is the Bessel function of the first kind, and
755
+ $Y_\nu(z)$ is the Bessel function of the second kind.
756
+
757
+ It is a solution to Bessel's equation.
758
+
759
+ Examples
760
+ ========
761
+
762
+ >>> from sympy import hankel1
763
+ >>> from sympy.abc import z, n
764
+ >>> hankel1(n, z).diff(z)
765
+ hankel1(n - 1, z)/2 - hankel1(n + 1, z)/2
766
+
767
+ See Also
768
+ ========
769
+
770
+ hankel2, besselj, bessely
771
+
772
+ References
773
+ ==========
774
+
775
+ .. [1] https://functions.wolfram.com/Bessel-TypeFunctions/HankelH1/
776
+
777
+ """
778
+
779
+ _a = S.One
780
+ _b = S.One
781
+
782
+ def _eval_conjugate(self):
783
+ z = self.argument
784
+ if z.is_extended_negative is False:
785
+ return hankel2(self.order.conjugate(), z.conjugate())
786
+
787
+
788
+ class hankel2(BesselBase):
789
+ r"""
790
+ Hankel function of the second kind.
791
+
792
+ Explanation
793
+ ===========
794
+
795
+ This function is defined as
796
+
797
+ .. math ::
798
+ H_\nu^{(2)} = J_\nu(z) - iY_\nu(z),
799
+
800
+ where $J_\nu(z)$ is the Bessel function of the first kind, and
801
+ $Y_\nu(z)$ is the Bessel function of the second kind.
802
+
803
+ It is a solution to Bessel's equation, and linearly independent from
804
+ $H_\nu^{(1)}$.
805
+
806
+ Examples
807
+ ========
808
+
809
+ >>> from sympy import hankel2
810
+ >>> from sympy.abc import z, n
811
+ >>> hankel2(n, z).diff(z)
812
+ hankel2(n - 1, z)/2 - hankel2(n + 1, z)/2
813
+
814
+ See Also
815
+ ========
816
+
817
+ hankel1, besselj, bessely
818
+
819
+ References
820
+ ==========
821
+
822
+ .. [1] https://functions.wolfram.com/Bessel-TypeFunctions/HankelH2/
823
+
824
+ """
825
+
826
+ _a = S.One
827
+ _b = S.One
828
+
829
+ def _eval_conjugate(self):
830
+ z = self.argument
831
+ if z.is_extended_negative is False:
832
+ return hankel1(self.order.conjugate(), z.conjugate())
833
+
834
+
835
+ def assume_integer_order(fn):
836
+ @wraps(fn)
837
+ def g(self, nu, z):
838
+ if nu.is_integer:
839
+ return fn(self, nu, z)
840
+ return g
841
+
842
+
843
+ class SphericalBesselBase(BesselBase):
844
+ """
845
+ Base class for spherical Bessel functions.
846
+
847
+ These are thin wrappers around ordinary Bessel functions,
848
+ since spherical Bessel functions differ from the ordinary
849
+ ones just by a slight change in order.
850
+
851
+ To use this class, define the ``_eval_evalf()`` and ``_expand()`` methods.
852
+
853
+ """
854
+
855
+ def _expand(self, **hints):
856
+ """ Expand self into a polynomial. Nu is guaranteed to be Integer. """
857
+ raise NotImplementedError('expansion')
858
+
859
+ def _eval_expand_func(self, **hints):
860
+ if self.order.is_Integer:
861
+ return self._expand(**hints)
862
+ return self
863
+
864
+ def fdiff(self, argindex=2):
865
+ if argindex != 2:
866
+ raise ArgumentIndexError(self, argindex)
867
+ return self.__class__(self.order - 1, self.argument) - \
868
+ self * (self.order + 1)/self.argument
869
+
870
+
871
+ def _jn(n, z):
872
+ return (spherical_bessel_fn(n, z)*sin(z) +
873
+ S.NegativeOne**(n + 1)*spherical_bessel_fn(-n - 1, z)*cos(z))
874
+
875
+
876
+ def _yn(n, z):
877
+ # (-1)**(n + 1) * _jn(-n - 1, z)
878
+ return (S.NegativeOne**(n + 1) * spherical_bessel_fn(-n - 1, z)*sin(z) -
879
+ spherical_bessel_fn(n, z)*cos(z))
880
+
881
+
882
+ class jn(SphericalBesselBase):
883
+ r"""
884
+ Spherical Bessel function of the first kind.
885
+
886
+ Explanation
887
+ ===========
888
+
889
+ This function is a solution to the spherical Bessel equation
890
+
891
+ .. math ::
892
+ z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2}
893
+ + 2z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 - \nu(\nu + 1)) w = 0.
894
+
895
+ It can be defined as
896
+
897
+ .. math ::
898
+ j_\nu(z) = \sqrt{\frac{\pi}{2z}} J_{\nu + \frac{1}{2}}(z),
899
+
900
+ where $J_\nu(z)$ is the Bessel function of the first kind.
901
+
902
+ The spherical Bessel functions of integral order are
903
+ calculated using the formula:
904
+
905
+ .. math:: j_n(z) = f_n(z) \sin{z} + (-1)^{n+1} f_{-n-1}(z) \cos{z},
906
+
907
+ where the coefficients $f_n(z)$ are available as
908
+ :func:`sympy.polys.orthopolys.spherical_bessel_fn`.
909
+
910
+ Examples
911
+ ========
912
+
913
+ >>> from sympy import Symbol, jn, sin, cos, expand_func, besselj, bessely
914
+ >>> z = Symbol("z")
915
+ >>> nu = Symbol("nu", integer=True)
916
+ >>> print(expand_func(jn(0, z)))
917
+ sin(z)/z
918
+ >>> expand_func(jn(1, z)) == sin(z)/z**2 - cos(z)/z
919
+ True
920
+ >>> expand_func(jn(3, z))
921
+ (-6/z**2 + 15/z**4)*sin(z) + (1/z - 15/z**3)*cos(z)
922
+ >>> jn(nu, z).rewrite(besselj)
923
+ sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(nu + 1/2, z)/2
924
+ >>> jn(nu, z).rewrite(bessely)
925
+ (-1)**nu*sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(-nu - 1/2, z)/2
926
+ >>> jn(2, 5.2+0.3j).evalf(20)
927
+ 0.099419756723640344491 - 0.054525080242173562897*I
928
+
929
+ See Also
930
+ ========
931
+
932
+ besselj, bessely, besselk, yn
933
+
934
+ References
935
+ ==========
936
+
937
+ .. [1] https://dlmf.nist.gov/10.47
938
+
939
+ """
940
+ @classmethod
941
+ def eval(cls, nu, z):
942
+ if z.is_zero:
943
+ if nu.is_zero:
944
+ return S.One
945
+ elif nu.is_integer:
946
+ if nu.is_positive:
947
+ return S.Zero
948
+ else:
949
+ return S.ComplexInfinity
950
+ if z in (S.NegativeInfinity, S.Infinity):
951
+ return S.Zero
952
+
953
+ def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
954
+ return sqrt(pi/(2*z)) * besselj(nu + S.Half, z)
955
+
956
+ def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
957
+ return S.NegativeOne**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z)
958
+
959
+ def _eval_rewrite_as_yn(self, nu, z, **kwargs):
960
+ return S.NegativeOne**(nu) * yn(-nu - 1, z)
961
+
962
+ def _expand(self, **hints):
963
+ return _jn(self.order, self.argument)
964
+
965
+ def _eval_evalf(self, prec):
966
+ if self.order.is_Integer:
967
+ return self.rewrite(besselj)._eval_evalf(prec)
968
+
969
+
970
+ class yn(SphericalBesselBase):
971
+ r"""
972
+ Spherical Bessel function of the second kind.
973
+
974
+ Explanation
975
+ ===========
976
+
977
+ This function is another solution to the spherical Bessel equation, and
978
+ linearly independent from $j_n$. It can be defined as
979
+
980
+ .. math ::
981
+ y_\nu(z) = \sqrt{\frac{\pi}{2z}} Y_{\nu + \frac{1}{2}}(z),
982
+
983
+ where $Y_\nu(z)$ is the Bessel function of the second kind.
984
+
985
+ For integral orders $n$, $y_n$ is calculated using the formula:
986
+
987
+ .. math:: y_n(z) = (-1)^{n+1} j_{-n-1}(z)
988
+
989
+ Examples
990
+ ========
991
+
992
+ >>> from sympy import Symbol, yn, sin, cos, expand_func, besselj, bessely
993
+ >>> z = Symbol("z")
994
+ >>> nu = Symbol("nu", integer=True)
995
+ >>> print(expand_func(yn(0, z)))
996
+ -cos(z)/z
997
+ >>> expand_func(yn(1, z)) == -cos(z)/z**2-sin(z)/z
998
+ True
999
+ >>> yn(nu, z).rewrite(besselj)
1000
+ (-1)**(nu + 1)*sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(-nu - 1/2, z)/2
1001
+ >>> yn(nu, z).rewrite(bessely)
1002
+ sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(nu + 1/2, z)/2
1003
+ >>> yn(2, 5.2+0.3j).evalf(20)
1004
+ 0.18525034196069722536 + 0.014895573969924817587*I
1005
+
1006
+ See Also
1007
+ ========
1008
+
1009
+ besselj, bessely, besselk, jn
1010
+
1011
+ References
1012
+ ==========
1013
+
1014
+ .. [1] https://dlmf.nist.gov/10.47
1015
+
1016
+ """
1017
+ @assume_integer_order
1018
+ def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
1019
+ return S.NegativeOne**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z)
1020
+
1021
+ @assume_integer_order
1022
+ def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
1023
+ return sqrt(pi/(2*z)) * bessely(nu + S.Half, z)
1024
+
1025
+ def _eval_rewrite_as_jn(self, nu, z, **kwargs):
1026
+ return S.NegativeOne**(nu + 1) * jn(-nu - 1, z)
1027
+
1028
+ def _expand(self, **hints):
1029
+ return _yn(self.order, self.argument)
1030
+
1031
+ def _eval_evalf(self, prec):
1032
+ if self.order.is_Integer:
1033
+ return self.rewrite(bessely)._eval_evalf(prec)
1034
+
1035
+
1036
+ class SphericalHankelBase(SphericalBesselBase):
1037
+
1038
+ @assume_integer_order
1039
+ def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
1040
+ # jn +- I*yn
1041
+ # jn as beeselj: sqrt(pi/(2*z)) * besselj(nu + S.Half, z)
1042
+ # yn as besselj: (-1)**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z)
1043
+ hks = self._hankel_kind_sign
1044
+ return sqrt(pi/(2*z))*(besselj(nu + S.Half, z) +
1045
+ hks*I*S.NegativeOne**(nu+1)*besselj(-nu - S.Half, z))
1046
+
1047
+ @assume_integer_order
1048
+ def _eval_rewrite_as_bessely(self, nu, z, **kwargs):
1049
+ # jn +- I*yn
1050
+ # jn as bessely: (-1)**nu * sqrt(pi/(2*z)) * bessely(-nu - S.Half, z)
1051
+ # yn as bessely: sqrt(pi/(2*z)) * bessely(nu + S.Half, z)
1052
+ hks = self._hankel_kind_sign
1053
+ return sqrt(pi/(2*z))*(S.NegativeOne**nu*bessely(-nu - S.Half, z) +
1054
+ hks*I*bessely(nu + S.Half, z))
1055
+
1056
+ def _eval_rewrite_as_yn(self, nu, z, **kwargs):
1057
+ hks = self._hankel_kind_sign
1058
+ return jn(nu, z).rewrite(yn) + hks*I*yn(nu, z)
1059
+
1060
+ def _eval_rewrite_as_jn(self, nu, z, **kwargs):
1061
+ hks = self._hankel_kind_sign
1062
+ return jn(nu, z) + hks*I*yn(nu, z).rewrite(jn)
1063
+
1064
+ def _eval_expand_func(self, **hints):
1065
+ if self.order.is_Integer:
1066
+ return self._expand(**hints)
1067
+ else:
1068
+ nu = self.order
1069
+ z = self.argument
1070
+ hks = self._hankel_kind_sign
1071
+ return jn(nu, z) + hks*I*yn(nu, z)
1072
+
1073
+ def _expand(self, **hints):
1074
+ n = self.order
1075
+ z = self.argument
1076
+ hks = self._hankel_kind_sign
1077
+
1078
+ # fully expanded version
1079
+ # return ((fn(n, z) * sin(z) +
1080
+ # (-1)**(n + 1) * fn(-n - 1, z) * cos(z)) + # jn
1081
+ # (hks * I * (-1)**(n + 1) *
1082
+ # (fn(-n - 1, z) * hk * I * sin(z) +
1083
+ # (-1)**(-n) * fn(n, z) * I * cos(z))) # +-I*yn
1084
+ # )
1085
+
1086
+ return (_jn(n, z) + hks*I*_yn(n, z)).expand()
1087
+
1088
+ def _eval_evalf(self, prec):
1089
+ if self.order.is_Integer:
1090
+ return self.rewrite(besselj)._eval_evalf(prec)
1091
+
1092
+
1093
+ class hn1(SphericalHankelBase):
1094
+ r"""
1095
+ Spherical Hankel function of the first kind.
1096
+
1097
+ Explanation
1098
+ ===========
1099
+
1100
+ This function is defined as
1101
+
1102
+ .. math:: h_\nu^(1)(z) = j_\nu(z) + i y_\nu(z),
1103
+
1104
+ where $j_\nu(z)$ and $y_\nu(z)$ are the spherical
1105
+ Bessel function of the first and second kinds.
1106
+
1107
+ For integral orders $n$, $h_n^(1)$ is calculated using the formula:
1108
+
1109
+ .. math:: h_n^(1)(z) = j_{n}(z) + i (-1)^{n+1} j_{-n-1}(z)
1110
+
1111
+ Examples
1112
+ ========
1113
+
1114
+ >>> from sympy import Symbol, hn1, hankel1, expand_func, yn, jn
1115
+ >>> z = Symbol("z")
1116
+ >>> nu = Symbol("nu", integer=True)
1117
+ >>> print(expand_func(hn1(nu, z)))
1118
+ jn(nu, z) + I*yn(nu, z)
1119
+ >>> print(expand_func(hn1(0, z)))
1120
+ sin(z)/z - I*cos(z)/z
1121
+ >>> print(expand_func(hn1(1, z)))
1122
+ -I*sin(z)/z - cos(z)/z + sin(z)/z**2 - I*cos(z)/z**2
1123
+ >>> hn1(nu, z).rewrite(jn)
1124
+ (-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z)
1125
+ >>> hn1(nu, z).rewrite(yn)
1126
+ (-1)**nu*yn(-nu - 1, z) + I*yn(nu, z)
1127
+ >>> hn1(nu, z).rewrite(hankel1)
1128
+ sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel1(nu, z)/2
1129
+
1130
+ See Also
1131
+ ========
1132
+
1133
+ hn2, jn, yn, hankel1, hankel2
1134
+
1135
+ References
1136
+ ==========
1137
+
1138
+ .. [1] https://dlmf.nist.gov/10.47
1139
+
1140
+ """
1141
+
1142
+ _hankel_kind_sign = S.One
1143
+
1144
+ @assume_integer_order
1145
+ def _eval_rewrite_as_hankel1(self, nu, z, **kwargs):
1146
+ return sqrt(pi/(2*z))*hankel1(nu, z)
1147
+
1148
+
1149
+ class hn2(SphericalHankelBase):
1150
+ r"""
1151
+ Spherical Hankel function of the second kind.
1152
+
1153
+ Explanation
1154
+ ===========
1155
+
1156
+ This function is defined as
1157
+
1158
+ .. math:: h_\nu^(2)(z) = j_\nu(z) - i y_\nu(z),
1159
+
1160
+ where $j_\nu(z)$ and $y_\nu(z)$ are the spherical
1161
+ Bessel function of the first and second kinds.
1162
+
1163
+ For integral orders $n$, $h_n^(2)$ is calculated using the formula:
1164
+
1165
+ .. math:: h_n^(2)(z) = j_{n} - i (-1)^{n+1} j_{-n-1}(z)
1166
+
1167
+ Examples
1168
+ ========
1169
+
1170
+ >>> from sympy import Symbol, hn2, hankel2, expand_func, jn, yn
1171
+ >>> z = Symbol("z")
1172
+ >>> nu = Symbol("nu", integer=True)
1173
+ >>> print(expand_func(hn2(nu, z)))
1174
+ jn(nu, z) - I*yn(nu, z)
1175
+ >>> print(expand_func(hn2(0, z)))
1176
+ sin(z)/z + I*cos(z)/z
1177
+ >>> print(expand_func(hn2(1, z)))
1178
+ I*sin(z)/z - cos(z)/z + sin(z)/z**2 + I*cos(z)/z**2
1179
+ >>> hn2(nu, z).rewrite(hankel2)
1180
+ sqrt(2)*sqrt(pi)*sqrt(1/z)*hankel2(nu, z)/2
1181
+ >>> hn2(nu, z).rewrite(jn)
1182
+ -(-1)**(nu + 1)*I*jn(-nu - 1, z) + jn(nu, z)
1183
+ >>> hn2(nu, z).rewrite(yn)
1184
+ (-1)**nu*yn(-nu - 1, z) - I*yn(nu, z)
1185
+
1186
+ See Also
1187
+ ========
1188
+
1189
+ hn1, jn, yn, hankel1, hankel2
1190
+
1191
+ References
1192
+ ==========
1193
+
1194
+ .. [1] https://dlmf.nist.gov/10.47
1195
+
1196
+ """
1197
+
1198
+ _hankel_kind_sign = -S.One
1199
+
1200
+ @assume_integer_order
1201
+ def _eval_rewrite_as_hankel2(self, nu, z, **kwargs):
1202
+ return sqrt(pi/(2*z))*hankel2(nu, z)
1203
+
1204
+
1205
+ def jn_zeros(n, k, method="sympy", dps=15):
1206
+ """
1207
+ Zeros of the spherical Bessel function of the first kind.
1208
+
1209
+ Explanation
1210
+ ===========
1211
+
1212
+ This returns an array of zeros of $jn$ up to the $k$-th zero.
1213
+
1214
+ * method = "sympy": uses `mpmath.besseljzero
1215
+ <https://mpmath.org/doc/current/functions/bessel.html#mpmath.besseljzero>`_
1216
+ * method = "scipy": uses the
1217
+ `SciPy's sph_jn <https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.jn_zeros.html>`_
1218
+ and
1219
+ `newton <https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html>`_
1220
+ to find all
1221
+ roots, which is faster than computing the zeros using a general
1222
+ numerical solver, but it requires SciPy and only works with low
1223
+ precision floating point numbers. (The function used with
1224
+ method="sympy" is a recent addition to mpmath; before that a general
1225
+ solver was used.)
1226
+
1227
+ Examples
1228
+ ========
1229
+
1230
+ >>> from sympy import jn_zeros
1231
+ >>> jn_zeros(2, 4, dps=5)
1232
+ [5.7635, 9.095, 12.323, 15.515]
1233
+
1234
+ See Also
1235
+ ========
1236
+
1237
+ jn, yn, besselj, besselk, bessely
1238
+
1239
+ Parameters
1240
+ ==========
1241
+
1242
+ n : integer
1243
+ order of Bessel function
1244
+
1245
+ k : integer
1246
+ number of zeros to return
1247
+
1248
+
1249
+ """
1250
+ from math import pi as math_pi
1251
+
1252
+ if method == "sympy":
1253
+ from mpmath import besseljzero
1254
+ from mpmath.libmp.libmpf import dps_to_prec
1255
+ prec = dps_to_prec(dps)
1256
+ return [Expr._from_mpmath(besseljzero(S(n + 0.5)._to_mpmath(prec),
1257
+ int(l)), prec)
1258
+ for l in range(1, k + 1)]
1259
+ elif method == "scipy":
1260
+ from scipy.optimize import newton
1261
+ try:
1262
+ from scipy.special import spherical_jn
1263
+ f = lambda x: spherical_jn(n, x)
1264
+ except ImportError:
1265
+ from scipy.special import sph_jn
1266
+ f = lambda x: sph_jn(n, x)[0][-1]
1267
+ else:
1268
+ raise NotImplementedError("Unknown method.")
1269
+
1270
+ def solver(f, x):
1271
+ if method == "scipy":
1272
+ root = newton(f, x)
1273
+ else:
1274
+ raise NotImplementedError("Unknown method.")
1275
+ return root
1276
+
1277
+ # we need to approximate the position of the first root:
1278
+ root = n + math_pi
1279
+ # determine the first root exactly:
1280
+ root = solver(f, root)
1281
+ roots = [root]
1282
+ for i in range(k - 1):
1283
+ # estimate the position of the next root using the last root + pi:
1284
+ root = solver(f, root + math_pi)
1285
+ roots.append(root)
1286
+ return roots
1287
+
1288
+
1289
+ class AiryBase(Function):
1290
+ """
1291
+ Abstract base class for Airy functions.
1292
+
1293
+ This class is meant to reduce code duplication.
1294
+
1295
+ """
1296
+
1297
+ def _eval_conjugate(self):
1298
+ return self.func(self.args[0].conjugate())
1299
+
1300
+ def _eval_is_extended_real(self):
1301
+ return self.args[0].is_extended_real
1302
+
1303
+ def as_real_imag(self, deep=True, **hints):
1304
+ z = self.args[0]
1305
+ zc = z.conjugate()
1306
+ f = self.func
1307
+ u = (f(z)+f(zc))/2
1308
+ v = I*(f(zc)-f(z))/2
1309
+ return u, v
1310
+
1311
+ def _eval_expand_complex(self, deep=True, **hints):
1312
+ re_part, im_part = self.as_real_imag(deep=deep, **hints)
1313
+ return re_part + im_part*I
1314
+
1315
+
1316
+ class airyai(AiryBase):
1317
+ r"""
1318
+ The Airy function $\operatorname{Ai}$ of the first kind.
1319
+
1320
+ Explanation
1321
+ ===========
1322
+
1323
+ The Airy function $\operatorname{Ai}(z)$ is defined to be the function
1324
+ satisfying Airy's differential equation
1325
+
1326
+ .. math::
1327
+ \frac{\mathrm{d}^2 w(z)}{\mathrm{d}z^2} - z w(z) = 0.
1328
+
1329
+ Equivalently, for real $z$
1330
+
1331
+ .. math::
1332
+ \operatorname{Ai}(z) := \frac{1}{\pi}
1333
+ \int_0^\infty \cos\left(\frac{t^3}{3} + z t\right) \mathrm{d}t.
1334
+
1335
+ Examples
1336
+ ========
1337
+
1338
+ Create an Airy function object:
1339
+
1340
+ >>> from sympy import airyai
1341
+ >>> from sympy.abc import z
1342
+
1343
+ >>> airyai(z)
1344
+ airyai(z)
1345
+
1346
+ Several special values are known:
1347
+
1348
+ >>> airyai(0)
1349
+ 3**(1/3)/(3*gamma(2/3))
1350
+ >>> from sympy import oo
1351
+ >>> airyai(oo)
1352
+ 0
1353
+ >>> airyai(-oo)
1354
+ 0
1355
+
1356
+ The Airy function obeys the mirror symmetry:
1357
+
1358
+ >>> from sympy import conjugate
1359
+ >>> conjugate(airyai(z))
1360
+ airyai(conjugate(z))
1361
+
1362
+ Differentiation with respect to $z$ is supported:
1363
+
1364
+ >>> from sympy import diff
1365
+ >>> diff(airyai(z), z)
1366
+ airyaiprime(z)
1367
+ >>> diff(airyai(z), z, 2)
1368
+ z*airyai(z)
1369
+
1370
+ Series expansion is also supported:
1371
+
1372
+ >>> from sympy import series
1373
+ >>> series(airyai(z), z, 0, 3)
1374
+ 3**(5/6)*gamma(1/3)/(6*pi) - 3**(1/6)*z*gamma(2/3)/(2*pi) + O(z**3)
1375
+
1376
+ We can numerically evaluate the Airy function to arbitrary precision
1377
+ on the whole complex plane:
1378
+
1379
+ >>> airyai(-2).evalf(50)
1380
+ 0.22740742820168557599192443603787379946077222541710
1381
+
1382
+ Rewrite $\operatorname{Ai}(z)$ in terms of hypergeometric functions:
1383
+
1384
+ >>> from sympy import hyper
1385
+ >>> airyai(z).rewrite(hyper)
1386
+ -3**(2/3)*z*hyper((), (4/3,), z**3/9)/(3*gamma(1/3)) + 3**(1/3)*hyper((), (2/3,), z**3/9)/(3*gamma(2/3))
1387
+
1388
+ See Also
1389
+ ========
1390
+
1391
+ airybi: Airy function of the second kind.
1392
+ airyaiprime: Derivative of the Airy function of the first kind.
1393
+ airybiprime: Derivative of the Airy function of the second kind.
1394
+
1395
+ References
1396
+ ==========
1397
+
1398
+ .. [1] https://en.wikipedia.org/wiki/Airy_function
1399
+ .. [2] https://dlmf.nist.gov/9
1400
+ .. [3] https://encyclopediaofmath.org/wiki/Airy_functions
1401
+ .. [4] https://mathworld.wolfram.com/AiryFunctions.html
1402
+
1403
+ """
1404
+
1405
+ nargs = 1
1406
+ unbranched = True
1407
+
1408
+ @classmethod
1409
+ def eval(cls, arg):
1410
+ if arg.is_Number:
1411
+ if arg is S.NaN:
1412
+ return S.NaN
1413
+ elif arg is S.Infinity:
1414
+ return S.Zero
1415
+ elif arg is S.NegativeInfinity:
1416
+ return S.Zero
1417
+ elif arg.is_zero:
1418
+ return S.One / (3**Rational(2, 3) * gamma(Rational(2, 3)))
1419
+ if arg.is_zero:
1420
+ return S.One / (3**Rational(2, 3) * gamma(Rational(2, 3)))
1421
+
1422
+ def fdiff(self, argindex=1):
1423
+ if argindex == 1:
1424
+ return airyaiprime(self.args[0])
1425
+ else:
1426
+ raise ArgumentIndexError(self, argindex)
1427
+
1428
+ @staticmethod
1429
+ @cacheit
1430
+ def taylor_term(n, x, *previous_terms):
1431
+ if n < 0:
1432
+ return S.Zero
1433
+ else:
1434
+ x = sympify(x)
1435
+ if len(previous_terms) > 1:
1436
+ p = previous_terms[-1]
1437
+ return ((cbrt(3)*x)**(-n)*(cbrt(3)*x)**(n + 1)*sin(pi*(n*Rational(2, 3) + Rational(4, 3)))*factorial(n) *
1438
+ gamma(n/3 + Rational(2, 3))/(sin(pi*(n*Rational(2, 3) + Rational(2, 3)))*factorial(n + 1)*gamma(n/3 + Rational(1, 3))) * p)
1439
+ else:
1440
+ return (S.One/(3**Rational(2, 3)*pi) * gamma((n+S.One)/S(3)) * sin(Rational(2, 3)*pi*(n+S.One)) /
1441
+ factorial(n) * (cbrt(3)*x)**n)
1442
+
1443
+ def _eval_rewrite_as_besselj(self, z, **kwargs):
1444
+ ot = Rational(1, 3)
1445
+ tt = Rational(2, 3)
1446
+ a = Pow(-z, Rational(3, 2))
1447
+ if re(z).is_negative:
1448
+ return ot*sqrt(-z) * (besselj(-ot, tt*a) + besselj(ot, tt*a))
1449
+
1450
+ def _eval_rewrite_as_besseli(self, z, **kwargs):
1451
+ ot = Rational(1, 3)
1452
+ tt = Rational(2, 3)
1453
+ a = Pow(z, Rational(3, 2))
1454
+ if re(z).is_positive:
1455
+ return ot*sqrt(z) * (besseli(-ot, tt*a) - besseli(ot, tt*a))
1456
+ else:
1457
+ return ot*(Pow(a, ot)*besseli(-ot, tt*a) - z*Pow(a, -ot)*besseli(ot, tt*a))
1458
+
1459
+ def _eval_rewrite_as_hyper(self, z, **kwargs):
1460
+ pf1 = S.One / (3**Rational(2, 3)*gamma(Rational(2, 3)))
1461
+ pf2 = z / (root(3, 3)*gamma(Rational(1, 3)))
1462
+ return pf1 * hyper([], [Rational(2, 3)], z**3/9) - pf2 * hyper([], [Rational(4, 3)], z**3/9)
1463
+
1464
+ def _eval_expand_func(self, **hints):
1465
+ arg = self.args[0]
1466
+ symbs = arg.free_symbols
1467
+
1468
+ if len(symbs) == 1:
1469
+ z = symbs.pop()
1470
+ c = Wild("c", exclude=[z])
1471
+ d = Wild("d", exclude=[z])
1472
+ m = Wild("m", exclude=[z])
1473
+ n = Wild("n", exclude=[z])
1474
+ M = arg.match(c*(d*z**n)**m)
1475
+ if M is not None:
1476
+ m = M[m]
1477
+ # The transformation is given by 03.05.16.0001.01
1478
+ # https://functions.wolfram.com/Bessel-TypeFunctions/AiryAi/16/01/01/0001/
1479
+ if (3*m).is_integer:
1480
+ c = M[c]
1481
+ d = M[d]
1482
+ n = M[n]
1483
+ pf = (d * z**n)**m / (d**m * z**(m*n))
1484
+ newarg = c * d**m * z**(m*n)
1485
+ return S.Half * ((pf + S.One)*airyai(newarg) - (pf - S.One)/sqrt(3)*airybi(newarg))
1486
+
1487
+
1488
+ class airybi(AiryBase):
1489
+ r"""
1490
+ The Airy function $\operatorname{Bi}$ of the second kind.
1491
+
1492
+ Explanation
1493
+ ===========
1494
+
1495
+ The Airy function $\operatorname{Bi}(z)$ is defined to be the function
1496
+ satisfying Airy's differential equation
1497
+
1498
+ .. math::
1499
+ \frac{\mathrm{d}^2 w(z)}{\mathrm{d}z^2} - z w(z) = 0.
1500
+
1501
+ Equivalently, for real $z$
1502
+
1503
+ .. math::
1504
+ \operatorname{Bi}(z) := \frac{1}{\pi}
1505
+ \int_0^\infty
1506
+ \exp\left(-\frac{t^3}{3} + z t\right)
1507
+ + \sin\left(\frac{t^3}{3} + z t\right) \mathrm{d}t.
1508
+
1509
+ Examples
1510
+ ========
1511
+
1512
+ Create an Airy function object:
1513
+
1514
+ >>> from sympy import airybi
1515
+ >>> from sympy.abc import z
1516
+
1517
+ >>> airybi(z)
1518
+ airybi(z)
1519
+
1520
+ Several special values are known:
1521
+
1522
+ >>> airybi(0)
1523
+ 3**(5/6)/(3*gamma(2/3))
1524
+ >>> from sympy import oo
1525
+ >>> airybi(oo)
1526
+ oo
1527
+ >>> airybi(-oo)
1528
+ 0
1529
+
1530
+ The Airy function obeys the mirror symmetry:
1531
+
1532
+ >>> from sympy import conjugate
1533
+ >>> conjugate(airybi(z))
1534
+ airybi(conjugate(z))
1535
+
1536
+ Differentiation with respect to $z$ is supported:
1537
+
1538
+ >>> from sympy import diff
1539
+ >>> diff(airybi(z), z)
1540
+ airybiprime(z)
1541
+ >>> diff(airybi(z), z, 2)
1542
+ z*airybi(z)
1543
+
1544
+ Series expansion is also supported:
1545
+
1546
+ >>> from sympy import series
1547
+ >>> series(airybi(z), z, 0, 3)
1548
+ 3**(1/3)*gamma(1/3)/(2*pi) + 3**(2/3)*z*gamma(2/3)/(2*pi) + O(z**3)
1549
+
1550
+ We can numerically evaluate the Airy function to arbitrary precision
1551
+ on the whole complex plane:
1552
+
1553
+ >>> airybi(-2).evalf(50)
1554
+ -0.41230258795639848808323405461146104203453483447240
1555
+
1556
+ Rewrite $\operatorname{Bi}(z)$ in terms of hypergeometric functions:
1557
+
1558
+ >>> from sympy import hyper
1559
+ >>> airybi(z).rewrite(hyper)
1560
+ 3**(1/6)*z*hyper((), (4/3,), z**3/9)/gamma(1/3) + 3**(5/6)*hyper((), (2/3,), z**3/9)/(3*gamma(2/3))
1561
+
1562
+ See Also
1563
+ ========
1564
+
1565
+ airyai: Airy function of the first kind.
1566
+ airyaiprime: Derivative of the Airy function of the first kind.
1567
+ airybiprime: Derivative of the Airy function of the second kind.
1568
+
1569
+ References
1570
+ ==========
1571
+
1572
+ .. [1] https://en.wikipedia.org/wiki/Airy_function
1573
+ .. [2] https://dlmf.nist.gov/9
1574
+ .. [3] https://encyclopediaofmath.org/wiki/Airy_functions
1575
+ .. [4] https://mathworld.wolfram.com/AiryFunctions.html
1576
+
1577
+ """
1578
+
1579
+ nargs = 1
1580
+ unbranched = True
1581
+
1582
+ @classmethod
1583
+ def eval(cls, arg):
1584
+ if arg.is_Number:
1585
+ if arg is S.NaN:
1586
+ return S.NaN
1587
+ elif arg is S.Infinity:
1588
+ return S.Infinity
1589
+ elif arg is S.NegativeInfinity:
1590
+ return S.Zero
1591
+ elif arg.is_zero:
1592
+ return S.One / (3**Rational(1, 6) * gamma(Rational(2, 3)))
1593
+
1594
+ if arg.is_zero:
1595
+ return S.One / (3**Rational(1, 6) * gamma(Rational(2, 3)))
1596
+
1597
+ def fdiff(self, argindex=1):
1598
+ if argindex == 1:
1599
+ return airybiprime(self.args[0])
1600
+ else:
1601
+ raise ArgumentIndexError(self, argindex)
1602
+
1603
+ @staticmethod
1604
+ @cacheit
1605
+ def taylor_term(n, x, *previous_terms):
1606
+ if n < 0:
1607
+ return S.Zero
1608
+ else:
1609
+ x = sympify(x)
1610
+ if len(previous_terms) > 1:
1611
+ p = previous_terms[-1]
1612
+ return (cbrt(3)*x * Abs(sin(Rational(2, 3)*pi*(n + S.One))) * factorial((n - S.One)/S(3)) /
1613
+ ((n + S.One) * Abs(cos(Rational(2, 3)*pi*(n + S.Half))) * factorial((n - 2)/S(3))) * p)
1614
+ else:
1615
+ return (S.One/(root(3, 6)*pi) * gamma((n + S.One)/S(3)) * Abs(sin(Rational(2, 3)*pi*(n + S.One))) /
1616
+ factorial(n) * (cbrt(3)*x)**n)
1617
+
1618
+ def _eval_rewrite_as_besselj(self, z, **kwargs):
1619
+ ot = Rational(1, 3)
1620
+ tt = Rational(2, 3)
1621
+ a = Pow(-z, Rational(3, 2))
1622
+ if re(z).is_negative:
1623
+ return sqrt(-z/3) * (besselj(-ot, tt*a) - besselj(ot, tt*a))
1624
+
1625
+ def _eval_rewrite_as_besseli(self, z, **kwargs):
1626
+ ot = Rational(1, 3)
1627
+ tt = Rational(2, 3)
1628
+ a = Pow(z, Rational(3, 2))
1629
+ if re(z).is_positive:
1630
+ return sqrt(z)/sqrt(3) * (besseli(-ot, tt*a) + besseli(ot, tt*a))
1631
+ else:
1632
+ b = Pow(a, ot)
1633
+ c = Pow(a, -ot)
1634
+ return sqrt(ot)*(b*besseli(-ot, tt*a) + z*c*besseli(ot, tt*a))
1635
+
1636
+ def _eval_rewrite_as_hyper(self, z, **kwargs):
1637
+ pf1 = S.One / (root(3, 6)*gamma(Rational(2, 3)))
1638
+ pf2 = z*root(3, 6) / gamma(Rational(1, 3))
1639
+ return pf1 * hyper([], [Rational(2, 3)], z**3/9) + pf2 * hyper([], [Rational(4, 3)], z**3/9)
1640
+
1641
+ def _eval_expand_func(self, **hints):
1642
+ arg = self.args[0]
1643
+ symbs = arg.free_symbols
1644
+
1645
+ if len(symbs) == 1:
1646
+ z = symbs.pop()
1647
+ c = Wild("c", exclude=[z])
1648
+ d = Wild("d", exclude=[z])
1649
+ m = Wild("m", exclude=[z])
1650
+ n = Wild("n", exclude=[z])
1651
+ M = arg.match(c*(d*z**n)**m)
1652
+ if M is not None:
1653
+ m = M[m]
1654
+ # The transformation is given by 03.06.16.0001.01
1655
+ # https://functions.wolfram.com/Bessel-TypeFunctions/AiryBi/16/01/01/0001/
1656
+ if (3*m).is_integer:
1657
+ c = M[c]
1658
+ d = M[d]
1659
+ n = M[n]
1660
+ pf = (d * z**n)**m / (d**m * z**(m*n))
1661
+ newarg = c * d**m * z**(m*n)
1662
+ return S.Half * (sqrt(3)*(S.One - pf)*airyai(newarg) + (S.One + pf)*airybi(newarg))
1663
+
1664
+
1665
+ class airyaiprime(AiryBase):
1666
+ r"""
1667
+ The derivative $\operatorname{Ai}^\prime$ of the Airy function of the first
1668
+ kind.
1669
+
1670
+ Explanation
1671
+ ===========
1672
+
1673
+ The Airy function $\operatorname{Ai}^\prime(z)$ is defined to be the
1674
+ function
1675
+
1676
+ .. math::
1677
+ \operatorname{Ai}^\prime(z) := \frac{\mathrm{d} \operatorname{Ai}(z)}{\mathrm{d} z}.
1678
+
1679
+ Examples
1680
+ ========
1681
+
1682
+ Create an Airy function object:
1683
+
1684
+ >>> from sympy import airyaiprime
1685
+ >>> from sympy.abc import z
1686
+
1687
+ >>> airyaiprime(z)
1688
+ airyaiprime(z)
1689
+
1690
+ Several special values are known:
1691
+
1692
+ >>> airyaiprime(0)
1693
+ -3**(2/3)/(3*gamma(1/3))
1694
+ >>> from sympy import oo
1695
+ >>> airyaiprime(oo)
1696
+ 0
1697
+
1698
+ The Airy function obeys the mirror symmetry:
1699
+
1700
+ >>> from sympy import conjugate
1701
+ >>> conjugate(airyaiprime(z))
1702
+ airyaiprime(conjugate(z))
1703
+
1704
+ Differentiation with respect to $z$ is supported:
1705
+
1706
+ >>> from sympy import diff
1707
+ >>> diff(airyaiprime(z), z)
1708
+ z*airyai(z)
1709
+ >>> diff(airyaiprime(z), z, 2)
1710
+ z*airyaiprime(z) + airyai(z)
1711
+
1712
+ Series expansion is also supported:
1713
+
1714
+ >>> from sympy import series
1715
+ >>> series(airyaiprime(z), z, 0, 3)
1716
+ -3**(2/3)/(3*gamma(1/3)) + 3**(1/3)*z**2/(6*gamma(2/3)) + O(z**3)
1717
+
1718
+ We can numerically evaluate the Airy function to arbitrary precision
1719
+ on the whole complex plane:
1720
+
1721
+ >>> airyaiprime(-2).evalf(50)
1722
+ 0.61825902074169104140626429133247528291577794512415
1723
+
1724
+ Rewrite $\operatorname{Ai}^\prime(z)$ in terms of hypergeometric functions:
1725
+
1726
+ >>> from sympy import hyper
1727
+ >>> airyaiprime(z).rewrite(hyper)
1728
+ 3**(1/3)*z**2*hyper((), (5/3,), z**3/9)/(6*gamma(2/3)) - 3**(2/3)*hyper((), (1/3,), z**3/9)/(3*gamma(1/3))
1729
+
1730
+ See Also
1731
+ ========
1732
+
1733
+ airyai: Airy function of the first kind.
1734
+ airybi: Airy function of the second kind.
1735
+ airybiprime: Derivative of the Airy function of the second kind.
1736
+
1737
+ References
1738
+ ==========
1739
+
1740
+ .. [1] https://en.wikipedia.org/wiki/Airy_function
1741
+ .. [2] https://dlmf.nist.gov/9
1742
+ .. [3] https://encyclopediaofmath.org/wiki/Airy_functions
1743
+ .. [4] https://mathworld.wolfram.com/AiryFunctions.html
1744
+
1745
+ """
1746
+
1747
+ nargs = 1
1748
+ unbranched = True
1749
+
1750
+ @classmethod
1751
+ def eval(cls, arg):
1752
+ if arg.is_Number:
1753
+ if arg is S.NaN:
1754
+ return S.NaN
1755
+ elif arg is S.Infinity:
1756
+ return S.Zero
1757
+
1758
+ if arg.is_zero:
1759
+ return S.NegativeOne / (3**Rational(1, 3) * gamma(Rational(1, 3)))
1760
+
1761
+ def fdiff(self, argindex=1):
1762
+ if argindex == 1:
1763
+ return self.args[0]*airyai(self.args[0])
1764
+ else:
1765
+ raise ArgumentIndexError(self, argindex)
1766
+
1767
+ def _eval_evalf(self, prec):
1768
+ z = self.args[0]._to_mpmath(prec)
1769
+ with workprec(prec):
1770
+ res = mp.airyai(z, derivative=1)
1771
+ return Expr._from_mpmath(res, prec)
1772
+
1773
+ def _eval_rewrite_as_besselj(self, z, **kwargs):
1774
+ tt = Rational(2, 3)
1775
+ a = Pow(-z, Rational(3, 2))
1776
+ if re(z).is_negative:
1777
+ return z/3 * (besselj(-tt, tt*a) - besselj(tt, tt*a))
1778
+
1779
+ def _eval_rewrite_as_besseli(self, z, **kwargs):
1780
+ ot = Rational(1, 3)
1781
+ tt = Rational(2, 3)
1782
+ a = tt * Pow(z, Rational(3, 2))
1783
+ if re(z).is_positive:
1784
+ return z/3 * (besseli(tt, a) - besseli(-tt, a))
1785
+ else:
1786
+ a = Pow(z, Rational(3, 2))
1787
+ b = Pow(a, tt)
1788
+ c = Pow(a, -tt)
1789
+ return ot * (z**2*c*besseli(tt, tt*a) - b*besseli(-ot, tt*a))
1790
+
1791
+ def _eval_rewrite_as_hyper(self, z, **kwargs):
1792
+ pf1 = z**2 / (2*3**Rational(2, 3)*gamma(Rational(2, 3)))
1793
+ pf2 = 1 / (root(3, 3)*gamma(Rational(1, 3)))
1794
+ return pf1 * hyper([], [Rational(5, 3)], z**3/9) - pf2 * hyper([], [Rational(1, 3)], z**3/9)
1795
+
1796
+ def _eval_expand_func(self, **hints):
1797
+ arg = self.args[0]
1798
+ symbs = arg.free_symbols
1799
+
1800
+ if len(symbs) == 1:
1801
+ z = symbs.pop()
1802
+ c = Wild("c", exclude=[z])
1803
+ d = Wild("d", exclude=[z])
1804
+ m = Wild("m", exclude=[z])
1805
+ n = Wild("n", exclude=[z])
1806
+ M = arg.match(c*(d*z**n)**m)
1807
+ if M is not None:
1808
+ m = M[m]
1809
+ # The transformation is in principle
1810
+ # given by 03.07.16.0001.01 but note
1811
+ # that there is an error in this formula.
1812
+ # https://functions.wolfram.com/Bessel-TypeFunctions/AiryAiPrime/16/01/01/0001/
1813
+ if (3*m).is_integer:
1814
+ c = M[c]
1815
+ d = M[d]
1816
+ n = M[n]
1817
+ pf = (d**m * z**(n*m)) / (d * z**n)**m
1818
+ newarg = c * d**m * z**(n*m)
1819
+ return S.Half * ((pf + S.One)*airyaiprime(newarg) + (pf - S.One)/sqrt(3)*airybiprime(newarg))
1820
+
1821
+
1822
+ class airybiprime(AiryBase):
1823
+ r"""
1824
+ The derivative $\operatorname{Bi}^\prime$ of the Airy function of the first
1825
+ kind.
1826
+
1827
+ Explanation
1828
+ ===========
1829
+
1830
+ The Airy function $\operatorname{Bi}^\prime(z)$ is defined to be the
1831
+ function
1832
+
1833
+ .. math::
1834
+ \operatorname{Bi}^\prime(z) := \frac{\mathrm{d} \operatorname{Bi}(z)}{\mathrm{d} z}.
1835
+
1836
+ Examples
1837
+ ========
1838
+
1839
+ Create an Airy function object:
1840
+
1841
+ >>> from sympy import airybiprime
1842
+ >>> from sympy.abc import z
1843
+
1844
+ >>> airybiprime(z)
1845
+ airybiprime(z)
1846
+
1847
+ Several special values are known:
1848
+
1849
+ >>> airybiprime(0)
1850
+ 3**(1/6)/gamma(1/3)
1851
+ >>> from sympy import oo
1852
+ >>> airybiprime(oo)
1853
+ oo
1854
+ >>> airybiprime(-oo)
1855
+ 0
1856
+
1857
+ The Airy function obeys the mirror symmetry:
1858
+
1859
+ >>> from sympy import conjugate
1860
+ >>> conjugate(airybiprime(z))
1861
+ airybiprime(conjugate(z))
1862
+
1863
+ Differentiation with respect to $z$ is supported:
1864
+
1865
+ >>> from sympy import diff
1866
+ >>> diff(airybiprime(z), z)
1867
+ z*airybi(z)
1868
+ >>> diff(airybiprime(z), z, 2)
1869
+ z*airybiprime(z) + airybi(z)
1870
+
1871
+ Series expansion is also supported:
1872
+
1873
+ >>> from sympy import series
1874
+ >>> series(airybiprime(z), z, 0, 3)
1875
+ 3**(1/6)/gamma(1/3) + 3**(5/6)*z**2/(6*gamma(2/3)) + O(z**3)
1876
+
1877
+ We can numerically evaluate the Airy function to arbitrary precision
1878
+ on the whole complex plane:
1879
+
1880
+ >>> airybiprime(-2).evalf(50)
1881
+ 0.27879516692116952268509756941098324140300059345163
1882
+
1883
+ Rewrite $\operatorname{Bi}^\prime(z)$ in terms of hypergeometric functions:
1884
+
1885
+ >>> from sympy import hyper
1886
+ >>> airybiprime(z).rewrite(hyper)
1887
+ 3**(5/6)*z**2*hyper((), (5/3,), z**3/9)/(6*gamma(2/3)) + 3**(1/6)*hyper((), (1/3,), z**3/9)/gamma(1/3)
1888
+
1889
+ See Also
1890
+ ========
1891
+
1892
+ airyai: Airy function of the first kind.
1893
+ airybi: Airy function of the second kind.
1894
+ airyaiprime: Derivative of the Airy function of the first kind.
1895
+
1896
+ References
1897
+ ==========
1898
+
1899
+ .. [1] https://en.wikipedia.org/wiki/Airy_function
1900
+ .. [2] https://dlmf.nist.gov/9
1901
+ .. [3] https://encyclopediaofmath.org/wiki/Airy_functions
1902
+ .. [4] https://mathworld.wolfram.com/AiryFunctions.html
1903
+
1904
+ """
1905
+
1906
+ nargs = 1
1907
+ unbranched = True
1908
+
1909
+ @classmethod
1910
+ def eval(cls, arg):
1911
+ if arg.is_Number:
1912
+ if arg is S.NaN:
1913
+ return S.NaN
1914
+ elif arg is S.Infinity:
1915
+ return S.Infinity
1916
+ elif arg is S.NegativeInfinity:
1917
+ return S.Zero
1918
+ elif arg.is_zero:
1919
+ return 3**Rational(1, 6) / gamma(Rational(1, 3))
1920
+
1921
+ if arg.is_zero:
1922
+ return 3**Rational(1, 6) / gamma(Rational(1, 3))
1923
+
1924
+
1925
+ def fdiff(self, argindex=1):
1926
+ if argindex == 1:
1927
+ return self.args[0]*airybi(self.args[0])
1928
+ else:
1929
+ raise ArgumentIndexError(self, argindex)
1930
+
1931
+ def _eval_evalf(self, prec):
1932
+ z = self.args[0]._to_mpmath(prec)
1933
+ with workprec(prec):
1934
+ res = mp.airybi(z, derivative=1)
1935
+ return Expr._from_mpmath(res, prec)
1936
+
1937
+ def _eval_rewrite_as_besselj(self, z, **kwargs):
1938
+ tt = Rational(2, 3)
1939
+ a = tt * Pow(-z, Rational(3, 2))
1940
+ if re(z).is_negative:
1941
+ return -z/sqrt(3) * (besselj(-tt, a) + besselj(tt, a))
1942
+
1943
+ def _eval_rewrite_as_besseli(self, z, **kwargs):
1944
+ ot = Rational(1, 3)
1945
+ tt = Rational(2, 3)
1946
+ a = tt * Pow(z, Rational(3, 2))
1947
+ if re(z).is_positive:
1948
+ return z/sqrt(3) * (besseli(-tt, a) + besseli(tt, a))
1949
+ else:
1950
+ a = Pow(z, Rational(3, 2))
1951
+ b = Pow(a, tt)
1952
+ c = Pow(a, -tt)
1953
+ return sqrt(ot) * (b*besseli(-tt, tt*a) + z**2*c*besseli(tt, tt*a))
1954
+
1955
+ def _eval_rewrite_as_hyper(self, z, **kwargs):
1956
+ pf1 = z**2 / (2*root(3, 6)*gamma(Rational(2, 3)))
1957
+ pf2 = root(3, 6) / gamma(Rational(1, 3))
1958
+ return pf1 * hyper([], [Rational(5, 3)], z**3/9) + pf2 * hyper([], [Rational(1, 3)], z**3/9)
1959
+
1960
+ def _eval_expand_func(self, **hints):
1961
+ arg = self.args[0]
1962
+ symbs = arg.free_symbols
1963
+
1964
+ if len(symbs) == 1:
1965
+ z = symbs.pop()
1966
+ c = Wild("c", exclude=[z])
1967
+ d = Wild("d", exclude=[z])
1968
+ m = Wild("m", exclude=[z])
1969
+ n = Wild("n", exclude=[z])
1970
+ M = arg.match(c*(d*z**n)**m)
1971
+ if M is not None:
1972
+ m = M[m]
1973
+ # The transformation is in principle
1974
+ # given by 03.08.16.0001.01 but note
1975
+ # that there is an error in this formula.
1976
+ # https://functions.wolfram.com/Bessel-TypeFunctions/AiryBiPrime/16/01/01/0001/
1977
+ if (3*m).is_integer:
1978
+ c = M[c]
1979
+ d = M[d]
1980
+ n = M[n]
1981
+ pf = (d**m * z**(n*m)) / (d * z**n)**m
1982
+ newarg = c * d**m * z**(n*m)
1983
+ return S.Half * (sqrt(3)*(pf - S.One)*airyaiprime(newarg) + (pf + S.One)*airybiprime(newarg))
1984
+
1985
+
1986
+ class marcumq(Function):
1987
+ r"""
1988
+ The Marcum Q-function.
1989
+
1990
+ Explanation
1991
+ ===========
1992
+
1993
+ The Marcum Q-function is defined by the meromorphic continuation of
1994
+
1995
+ .. math::
1996
+ Q_m(a, b) = a^{- m + 1} \int_{b}^{\infty} x^{m} e^{- \frac{a^{2}}{2} - \frac{x^{2}}{2}} I_{m - 1}\left(a x\right)\, dx
1997
+
1998
+ Examples
1999
+ ========
2000
+
2001
+ >>> from sympy import marcumq
2002
+ >>> from sympy.abc import m, a, b
2003
+ >>> marcumq(m, a, b)
2004
+ marcumq(m, a, b)
2005
+
2006
+ Special values:
2007
+
2008
+ >>> marcumq(m, 0, b)
2009
+ uppergamma(m, b**2/2)/gamma(m)
2010
+ >>> marcumq(0, 0, 0)
2011
+ 0
2012
+ >>> marcumq(0, a, 0)
2013
+ 1 - exp(-a**2/2)
2014
+ >>> marcumq(1, a, a)
2015
+ 1/2 + exp(-a**2)*besseli(0, a**2)/2
2016
+ >>> marcumq(2, a, a)
2017
+ 1/2 + exp(-a**2)*besseli(0, a**2)/2 + exp(-a**2)*besseli(1, a**2)
2018
+
2019
+ Differentiation with respect to $a$ and $b$ is supported:
2020
+
2021
+ >>> from sympy import diff
2022
+ >>> diff(marcumq(m, a, b), a)
2023
+ a*(-marcumq(m, a, b) + marcumq(m + 1, a, b))
2024
+ >>> diff(marcumq(m, a, b), b)
2025
+ -a**(1 - m)*b**m*exp(-a**2/2 - b**2/2)*besseli(m - 1, a*b)
2026
+
2027
+ References
2028
+ ==========
2029
+
2030
+ .. [1] https://en.wikipedia.org/wiki/Marcum_Q-function
2031
+ .. [2] https://mathworld.wolfram.com/MarcumQ-Function.html
2032
+
2033
+ """
2034
+
2035
+ @classmethod
2036
+ def eval(cls, m, a, b):
2037
+ if a is S.Zero:
2038
+ if m is S.Zero and b is S.Zero:
2039
+ return S.Zero
2040
+ return uppergamma(m, b**2 * S.Half) / gamma(m)
2041
+
2042
+ if m is S.Zero and b is S.Zero:
2043
+ return 1 - 1 / exp(a**2 * S.Half)
2044
+
2045
+ if a == b:
2046
+ if m is S.One:
2047
+ return (1 + exp(-a**2) * besseli(0, a**2))*S.Half
2048
+ if m == 2:
2049
+ return S.Half + S.Half * exp(-a**2) * besseli(0, a**2) + exp(-a**2) * besseli(1, a**2)
2050
+
2051
+ if a.is_zero:
2052
+ if m.is_zero and b.is_zero:
2053
+ return S.Zero
2054
+ return uppergamma(m, b**2*S.Half) / gamma(m)
2055
+
2056
+ if m.is_zero and b.is_zero:
2057
+ return 1 - 1 / exp(a**2*S.Half)
2058
+
2059
+ def fdiff(self, argindex=2):
2060
+ m, a, b = self.args
2061
+ if argindex == 2:
2062
+ return a * (-marcumq(m, a, b) + marcumq(1+m, a, b))
2063
+ elif argindex == 3:
2064
+ return (-b**m / a**(m-1)) * exp(-(a**2 + b**2)/2) * besseli(m-1, a*b)
2065
+ else:
2066
+ raise ArgumentIndexError(self, argindex)
2067
+
2068
+ def _eval_rewrite_as_Integral(self, m, a, b, **kwargs):
2069
+ from sympy.integrals.integrals import Integral
2070
+ x = kwargs.get('x', Dummy('x'))
2071
+ return a ** (1 - m) * \
2072
+ Integral(x**m * exp(-(x**2 + a**2)/2) * besseli(m-1, a*x), [x, b, S.Infinity])
2073
+
2074
+ def _eval_rewrite_as_Sum(self, m, a, b, **kwargs):
2075
+ from sympy.concrete.summations import Sum
2076
+ k = kwargs.get('k', Dummy('k'))
2077
+ return exp(-(a**2 + b**2) / 2) * Sum((a/b)**k * besseli(k, a*b), [k, 1-m, S.Infinity])
2078
+
2079
+ def _eval_rewrite_as_besseli(self, m, a, b, **kwargs):
2080
+ if a == b:
2081
+ if m == 1:
2082
+ return (1 + exp(-a**2) * besseli(0, a**2)) / 2
2083
+ if m.is_Integer and m >= 2:
2084
+ s = sum([besseli(i, a**2) for i in range(1, m)])
2085
+ return S.Half + exp(-a**2) * besseli(0, a**2) / 2 + exp(-a**2) * s
2086
+
2087
+ def _eval_is_zero(self):
2088
+ if all(arg.is_zero for arg in self.args):
2089
+ return True
venv/lib/python3.10/site-packages/sympy/functions/special/beta_functions.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S
2
+ from sympy.core.function import Function, ArgumentIndexError
3
+ from sympy.core.symbol import Dummy
4
+ from sympy.functions.special.gamma_functions import gamma, digamma
5
+ from sympy.functions.combinatorial.numbers import catalan
6
+ from sympy.functions.elementary.complexes import conjugate
7
+
8
+ # See mpmath #569 and SymPy #20569
9
+ def betainc_mpmath_fix(a, b, x1, x2, reg=0):
10
+ from mpmath import betainc, mpf
11
+ if x1 == x2:
12
+ return mpf(0)
13
+ else:
14
+ return betainc(a, b, x1, x2, reg)
15
+
16
+ ###############################################################################
17
+ ############################ COMPLETE BETA FUNCTION ##########################
18
+ ###############################################################################
19
+
20
+ class beta(Function):
21
+ r"""
22
+ The beta integral is called the Eulerian integral of the first kind by
23
+ Legendre:
24
+
25
+ .. math::
26
+ \mathrm{B}(x,y) \int^{1}_{0} t^{x-1} (1-t)^{y-1} \mathrm{d}t.
27
+
28
+ Explanation
29
+ ===========
30
+
31
+ The Beta function or Euler's first integral is closely associated
32
+ with the gamma function. The Beta function is often used in probability
33
+ theory and mathematical statistics. It satisfies properties like:
34
+
35
+ .. math::
36
+ \mathrm{B}(a,1) = \frac{1}{a} \\
37
+ \mathrm{B}(a,b) = \mathrm{B}(b,a) \\
38
+ \mathrm{B}(a,b) = \frac{\Gamma(a) \Gamma(b)}{\Gamma(a+b)}
39
+
40
+ Therefore for integral values of $a$ and $b$:
41
+
42
+ .. math::
43
+ \mathrm{B} = \frac{(a-1)! (b-1)!}{(a+b-1)!}
44
+
45
+ A special case of the Beta function when `x = y` is the
46
+ Central Beta function. It satisfies properties like:
47
+
48
+ .. math::
49
+ \mathrm{B}(x) = 2^{1 - 2x}\mathrm{B}(x, \frac{1}{2})
50
+ \mathrm{B}(x) = 2^{1 - 2x} cos(\pi x) \mathrm{B}(\frac{1}{2} - x, x)
51
+ \mathrm{B}(x) = \int_{0}^{1} \frac{t^x}{(1 + t)^{2x}} dt
52
+ \mathrm{B}(x) = \frac{2}{x} \prod_{n = 1}^{\infty} \frac{n(n + 2x)}{(n + x)^2}
53
+
54
+ Examples
55
+ ========
56
+
57
+ >>> from sympy import I, pi
58
+ >>> from sympy.abc import x, y
59
+
60
+ The Beta function obeys the mirror symmetry:
61
+
62
+ >>> from sympy import beta, conjugate
63
+ >>> conjugate(beta(x, y))
64
+ beta(conjugate(x), conjugate(y))
65
+
66
+ Differentiation with respect to both $x$ and $y$ is supported:
67
+
68
+ >>> from sympy import beta, diff
69
+ >>> diff(beta(x, y), x)
70
+ (polygamma(0, x) - polygamma(0, x + y))*beta(x, y)
71
+
72
+ >>> diff(beta(x, y), y)
73
+ (polygamma(0, y) - polygamma(0, x + y))*beta(x, y)
74
+
75
+ >>> diff(beta(x), x)
76
+ 2*(polygamma(0, x) - polygamma(0, 2*x))*beta(x, x)
77
+
78
+ We can numerically evaluate the Beta function to
79
+ arbitrary precision for any complex numbers x and y:
80
+
81
+ >>> from sympy import beta
82
+ >>> beta(pi).evalf(40)
83
+ 0.02671848900111377452242355235388489324562
84
+
85
+ >>> beta(1 + I).evalf(20)
86
+ -0.2112723729365330143 - 0.7655283165378005676*I
87
+
88
+ See Also
89
+ ========
90
+
91
+ gamma: Gamma function.
92
+ uppergamma: Upper incomplete gamma function.
93
+ lowergamma: Lower incomplete gamma function.
94
+ polygamma: Polygamma function.
95
+ loggamma: Log Gamma function.
96
+ digamma: Digamma function.
97
+ trigamma: Trigamma function.
98
+
99
+ References
100
+ ==========
101
+
102
+ .. [1] https://en.wikipedia.org/wiki/Beta_function
103
+ .. [2] https://mathworld.wolfram.com/BetaFunction.html
104
+ .. [3] https://dlmf.nist.gov/5.12
105
+
106
+ """
107
+ unbranched = True
108
+
109
+ def fdiff(self, argindex):
110
+ x, y = self.args
111
+ if argindex == 1:
112
+ # Diff wrt x
113
+ return beta(x, y)*(digamma(x) - digamma(x + y))
114
+ elif argindex == 2:
115
+ # Diff wrt y
116
+ return beta(x, y)*(digamma(y) - digamma(x + y))
117
+ else:
118
+ raise ArgumentIndexError(self, argindex)
119
+
120
+ @classmethod
121
+ def eval(cls, x, y=None):
122
+ if y is None:
123
+ return beta(x, x)
124
+ if x.is_Number and y.is_Number:
125
+ return beta(x, y, evaluate=False).doit()
126
+
127
+ def doit(self, **hints):
128
+ x = xold = self.args[0]
129
+ # Deal with unevaluated single argument beta
130
+ single_argument = len(self.args) == 1
131
+ y = yold = self.args[0] if single_argument else self.args[1]
132
+ if hints.get('deep', True):
133
+ x = x.doit(**hints)
134
+ y = y.doit(**hints)
135
+ if y.is_zero or x.is_zero:
136
+ return S.ComplexInfinity
137
+ if y is S.One:
138
+ return 1/x
139
+ if x is S.One:
140
+ return 1/y
141
+ if y == x + 1:
142
+ return 1/(x*y*catalan(x))
143
+ s = x + y
144
+ if (s.is_integer and s.is_negative and x.is_integer is False and
145
+ y.is_integer is False):
146
+ return S.Zero
147
+ if x == xold and y == yold and not single_argument:
148
+ return self
149
+ return beta(x, y)
150
+
151
+ def _eval_expand_func(self, **hints):
152
+ x, y = self.args
153
+ return gamma(x)*gamma(y) / gamma(x + y)
154
+
155
+ def _eval_is_real(self):
156
+ return self.args[0].is_real and self.args[1].is_real
157
+
158
+ def _eval_conjugate(self):
159
+ return self.func(self.args[0].conjugate(), self.args[1].conjugate())
160
+
161
+ def _eval_rewrite_as_gamma(self, x, y, piecewise=True, **kwargs):
162
+ return self._eval_expand_func(**kwargs)
163
+
164
+ def _eval_rewrite_as_Integral(self, x, y, **kwargs):
165
+ from sympy.integrals.integrals import Integral
166
+ t = Dummy('t')
167
+ return Integral(t**(x - 1)*(1 - t)**(y - 1), (t, 0, 1))
168
+
169
+ ###############################################################################
170
+ ########################## INCOMPLETE BETA FUNCTION ###########################
171
+ ###############################################################################
172
+
173
+ class betainc(Function):
174
+ r"""
175
+ The Generalized Incomplete Beta function is defined as
176
+
177
+ .. math::
178
+ \mathrm{B}_{(x_1, x_2)}(a, b) = \int_{x_1}^{x_2} t^{a - 1} (1 - t)^{b - 1} dt
179
+
180
+ The Incomplete Beta function is a special case
181
+ of the Generalized Incomplete Beta function :
182
+
183
+ .. math:: \mathrm{B}_z (a, b) = \mathrm{B}_{(0, z)}(a, b)
184
+
185
+ The Incomplete Beta function satisfies :
186
+
187
+ .. math:: \mathrm{B}_z (a, b) = (-1)^a \mathrm{B}_{\frac{z}{z - 1}} (a, 1 - a - b)
188
+
189
+ The Beta function is a special case of the Incomplete Beta function :
190
+
191
+ .. math:: \mathrm{B}(a, b) = \mathrm{B}_{1}(a, b)
192
+
193
+ Examples
194
+ ========
195
+
196
+ >>> from sympy import betainc, symbols, conjugate
197
+ >>> a, b, x, x1, x2 = symbols('a b x x1 x2')
198
+
199
+ The Generalized Incomplete Beta function is given by:
200
+
201
+ >>> betainc(a, b, x1, x2)
202
+ betainc(a, b, x1, x2)
203
+
204
+ The Incomplete Beta function can be obtained as follows:
205
+
206
+ >>> betainc(a, b, 0, x)
207
+ betainc(a, b, 0, x)
208
+
209
+ The Incomplete Beta function obeys the mirror symmetry:
210
+
211
+ >>> conjugate(betainc(a, b, x1, x2))
212
+ betainc(conjugate(a), conjugate(b), conjugate(x1), conjugate(x2))
213
+
214
+ We can numerically evaluate the Incomplete Beta function to
215
+ arbitrary precision for any complex numbers a, b, x1 and x2:
216
+
217
+ >>> from sympy import betainc, I
218
+ >>> betainc(2, 3, 4, 5).evalf(10)
219
+ 56.08333333
220
+ >>> betainc(0.75, 1 - 4*I, 0, 2 + 3*I).evalf(25)
221
+ 0.2241657956955709603655887 + 0.3619619242700451992411724*I
222
+
223
+ The Generalized Incomplete Beta function can be expressed
224
+ in terms of the Generalized Hypergeometric function.
225
+
226
+ >>> from sympy import hyper
227
+ >>> betainc(a, b, x1, x2).rewrite(hyper)
228
+ (-x1**a*hyper((a, 1 - b), (a + 1,), x1) + x2**a*hyper((a, 1 - b), (a + 1,), x2))/a
229
+
230
+ See Also
231
+ ========
232
+
233
+ beta: Beta function
234
+ hyper: Generalized Hypergeometric function
235
+
236
+ References
237
+ ==========
238
+
239
+ .. [1] https://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function
240
+ .. [2] https://dlmf.nist.gov/8.17
241
+ .. [3] https://functions.wolfram.com/GammaBetaErf/Beta4/
242
+ .. [4] https://functions.wolfram.com/GammaBetaErf/BetaRegularized4/02/
243
+
244
+ """
245
+ nargs = 4
246
+ unbranched = True
247
+
248
+ def fdiff(self, argindex):
249
+ a, b, x1, x2 = self.args
250
+ if argindex == 3:
251
+ # Diff wrt x1
252
+ return -(1 - x1)**(b - 1)*x1**(a - 1)
253
+ elif argindex == 4:
254
+ # Diff wrt x2
255
+ return (1 - x2)**(b - 1)*x2**(a - 1)
256
+ else:
257
+ raise ArgumentIndexError(self, argindex)
258
+
259
+ def _eval_mpmath(self):
260
+ return betainc_mpmath_fix, self.args
261
+
262
+ def _eval_is_real(self):
263
+ if all(arg.is_real for arg in self.args):
264
+ return True
265
+
266
+ def _eval_conjugate(self):
267
+ return self.func(*map(conjugate, self.args))
268
+
269
+ def _eval_rewrite_as_Integral(self, a, b, x1, x2, **kwargs):
270
+ from sympy.integrals.integrals import Integral
271
+ t = Dummy('t')
272
+ return Integral(t**(a - 1)*(1 - t)**(b - 1), (t, x1, x2))
273
+
274
+ def _eval_rewrite_as_hyper(self, a, b, x1, x2, **kwargs):
275
+ from sympy.functions.special.hyper import hyper
276
+ return (x2**a * hyper((a, 1 - b), (a + 1,), x2) - x1**a * hyper((a, 1 - b), (a + 1,), x1)) / a
277
+
278
+ ###############################################################################
279
+ #################### REGULARIZED INCOMPLETE BETA FUNCTION #####################
280
+ ###############################################################################
281
+
282
+ class betainc_regularized(Function):
283
+ r"""
284
+ The Generalized Regularized Incomplete Beta function is given by
285
+
286
+ .. math::
287
+ \mathrm{I}_{(x_1, x_2)}(a, b) = \frac{\mathrm{B}_{(x_1, x_2)}(a, b)}{\mathrm{B}(a, b)}
288
+
289
+ The Regularized Incomplete Beta function is a special case
290
+ of the Generalized Regularized Incomplete Beta function :
291
+
292
+ .. math:: \mathrm{I}_z (a, b) = \mathrm{I}_{(0, z)}(a, b)
293
+
294
+ The Regularized Incomplete Beta function is the cumulative distribution
295
+ function of the beta distribution.
296
+
297
+ Examples
298
+ ========
299
+
300
+ >>> from sympy import betainc_regularized, symbols, conjugate
301
+ >>> a, b, x, x1, x2 = symbols('a b x x1 x2')
302
+
303
+ The Generalized Regularized Incomplete Beta
304
+ function is given by:
305
+
306
+ >>> betainc_regularized(a, b, x1, x2)
307
+ betainc_regularized(a, b, x1, x2)
308
+
309
+ The Regularized Incomplete Beta function
310
+ can be obtained as follows:
311
+
312
+ >>> betainc_regularized(a, b, 0, x)
313
+ betainc_regularized(a, b, 0, x)
314
+
315
+ The Regularized Incomplete Beta function
316
+ obeys the mirror symmetry:
317
+
318
+ >>> conjugate(betainc_regularized(a, b, x1, x2))
319
+ betainc_regularized(conjugate(a), conjugate(b), conjugate(x1), conjugate(x2))
320
+
321
+ We can numerically evaluate the Regularized Incomplete Beta function
322
+ to arbitrary precision for any complex numbers a, b, x1 and x2:
323
+
324
+ >>> from sympy import betainc_regularized, pi, E
325
+ >>> betainc_regularized(1, 2, 0, 0.25).evalf(10)
326
+ 0.4375000000
327
+ >>> betainc_regularized(pi, E, 0, 1).evalf(5)
328
+ 1.00000
329
+
330
+ The Generalized Regularized Incomplete Beta function can be
331
+ expressed in terms of the Generalized Hypergeometric function.
332
+
333
+ >>> from sympy import hyper
334
+ >>> betainc_regularized(a, b, x1, x2).rewrite(hyper)
335
+ (-x1**a*hyper((a, 1 - b), (a + 1,), x1) + x2**a*hyper((a, 1 - b), (a + 1,), x2))/(a*beta(a, b))
336
+
337
+ See Also
338
+ ========
339
+
340
+ beta: Beta function
341
+ hyper: Generalized Hypergeometric function
342
+
343
+ References
344
+ ==========
345
+
346
+ .. [1] https://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function
347
+ .. [2] https://dlmf.nist.gov/8.17
348
+ .. [3] https://functions.wolfram.com/GammaBetaErf/Beta4/
349
+ .. [4] https://functions.wolfram.com/GammaBetaErf/BetaRegularized4/02/
350
+
351
+ """
352
+ nargs = 4
353
+ unbranched = True
354
+
355
+ def __new__(cls, a, b, x1, x2):
356
+ return Function.__new__(cls, a, b, x1, x2)
357
+
358
+ def _eval_mpmath(self):
359
+ return betainc_mpmath_fix, (*self.args, S(1))
360
+
361
+ def fdiff(self, argindex):
362
+ a, b, x1, x2 = self.args
363
+ if argindex == 3:
364
+ # Diff wrt x1
365
+ return -(1 - x1)**(b - 1)*x1**(a - 1) / beta(a, b)
366
+ elif argindex == 4:
367
+ # Diff wrt x2
368
+ return (1 - x2)**(b - 1)*x2**(a - 1) / beta(a, b)
369
+ else:
370
+ raise ArgumentIndexError(self, argindex)
371
+
372
+ def _eval_is_real(self):
373
+ if all(arg.is_real for arg in self.args):
374
+ return True
375
+
376
+ def _eval_conjugate(self):
377
+ return self.func(*map(conjugate, self.args))
378
+
379
+ def _eval_rewrite_as_Integral(self, a, b, x1, x2, **kwargs):
380
+ from sympy.integrals.integrals import Integral
381
+ t = Dummy('t')
382
+ integrand = t**(a - 1)*(1 - t)**(b - 1)
383
+ expr = Integral(integrand, (t, x1, x2))
384
+ return expr / Integral(integrand, (t, 0, 1))
385
+
386
+ def _eval_rewrite_as_hyper(self, a, b, x1, x2, **kwargs):
387
+ from sympy.functions.special.hyper import hyper
388
+ expr = (x2**a * hyper((a, 1 - b), (a + 1,), x2) - x1**a * hyper((a, 1 - b), (a + 1,), x1)) / a
389
+ return expr / beta(a, b)
venv/lib/python3.10/site-packages/sympy/functions/special/bsplines.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, sympify
2
+ from sympy.core.symbol import (Dummy, symbols)
3
+ from sympy.functions import Piecewise, piecewise_fold
4
+ from sympy.logic.boolalg import And
5
+ from sympy.sets.sets import Interval
6
+
7
+ from functools import lru_cache
8
+
9
+
10
+ def _ivl(cond, x):
11
+ """return the interval corresponding to the condition
12
+
13
+ Conditions in spline's Piecewise give the range over
14
+ which an expression is valid like (lo <= x) & (x <= hi).
15
+ This function returns (lo, hi).
16
+ """
17
+ if isinstance(cond, And) and len(cond.args) == 2:
18
+ a, b = cond.args
19
+ if a.lts == x:
20
+ a, b = b, a
21
+ return a.lts, b.gts
22
+ raise TypeError('unexpected cond type: %s' % cond)
23
+
24
+
25
+ def _add_splines(c, b1, d, b2, x):
26
+ """Construct c*b1 + d*b2."""
27
+
28
+ if S.Zero in (b1, c):
29
+ rv = piecewise_fold(d * b2)
30
+ elif S.Zero in (b2, d):
31
+ rv = piecewise_fold(c * b1)
32
+ else:
33
+ new_args = []
34
+ # Just combining the Piecewise without any fancy optimization
35
+ p1 = piecewise_fold(c * b1)
36
+ p2 = piecewise_fold(d * b2)
37
+
38
+ # Search all Piecewise arguments except (0, True)
39
+ p2args = list(p2.args[:-1])
40
+
41
+ # This merging algorithm assumes the conditions in
42
+ # p1 and p2 are sorted
43
+ for arg in p1.args[:-1]:
44
+ expr = arg.expr
45
+ cond = arg.cond
46
+
47
+ lower = _ivl(cond, x)[0]
48
+
49
+ # Check p2 for matching conditions that can be merged
50
+ for i, arg2 in enumerate(p2args):
51
+ expr2 = arg2.expr
52
+ cond2 = arg2.cond
53
+
54
+ lower_2, upper_2 = _ivl(cond2, x)
55
+ if cond2 == cond:
56
+ # Conditions match, join expressions
57
+ expr += expr2
58
+ # Remove matching element
59
+ del p2args[i]
60
+ # No need to check the rest
61
+ break
62
+ elif lower_2 < lower and upper_2 <= lower:
63
+ # Check if arg2 condition smaller than arg1,
64
+ # add to new_args by itself (no match expected
65
+ # in p1)
66
+ new_args.append(arg2)
67
+ del p2args[i]
68
+ break
69
+
70
+ # Checked all, add expr and cond
71
+ new_args.append((expr, cond))
72
+
73
+ # Add remaining items from p2args
74
+ new_args.extend(p2args)
75
+
76
+ # Add final (0, True)
77
+ new_args.append((0, True))
78
+
79
+ rv = Piecewise(*new_args, evaluate=False)
80
+
81
+ return rv.expand()
82
+
83
+
84
+ @lru_cache(maxsize=128)
85
+ def bspline_basis(d, knots, n, x):
86
+ """
87
+ The $n$-th B-spline at $x$ of degree $d$ with knots.
88
+
89
+ Explanation
90
+ ===========
91
+
92
+ B-Splines are piecewise polynomials of degree $d$. They are defined on a
93
+ set of knots, which is a sequence of integers or floats.
94
+
95
+ Examples
96
+ ========
97
+
98
+ The 0th degree splines have a value of 1 on a single interval:
99
+
100
+ >>> from sympy import bspline_basis
101
+ >>> from sympy.abc import x
102
+ >>> d = 0
103
+ >>> knots = tuple(range(5))
104
+ >>> bspline_basis(d, knots, 0, x)
105
+ Piecewise((1, (x >= 0) & (x <= 1)), (0, True))
106
+
107
+ For a given ``(d, knots)`` there are ``len(knots)-d-1`` B-splines
108
+ defined, that are indexed by ``n`` (starting at 0).
109
+
110
+ Here is an example of a cubic B-spline:
111
+
112
+ >>> bspline_basis(3, tuple(range(5)), 0, x)
113
+ Piecewise((x**3/6, (x >= 0) & (x <= 1)),
114
+ (-x**3/2 + 2*x**2 - 2*x + 2/3,
115
+ (x >= 1) & (x <= 2)),
116
+ (x**3/2 - 4*x**2 + 10*x - 22/3,
117
+ (x >= 2) & (x <= 3)),
118
+ (-x**3/6 + 2*x**2 - 8*x + 32/3,
119
+ (x >= 3) & (x <= 4)),
120
+ (0, True))
121
+
122
+ By repeating knot points, you can introduce discontinuities in the
123
+ B-splines and their derivatives:
124
+
125
+ >>> d = 1
126
+ >>> knots = (0, 0, 2, 3, 4)
127
+ >>> bspline_basis(d, knots, 0, x)
128
+ Piecewise((1 - x/2, (x >= 0) & (x <= 2)), (0, True))
129
+
130
+ It is quite time consuming to construct and evaluate B-splines. If
131
+ you need to evaluate a B-spline many times, it is best to lambdify them
132
+ first:
133
+
134
+ >>> from sympy import lambdify
135
+ >>> d = 3
136
+ >>> knots = tuple(range(10))
137
+ >>> b0 = bspline_basis(d, knots, 0, x)
138
+ >>> f = lambdify(x, b0)
139
+ >>> y = f(0.5)
140
+
141
+ Parameters
142
+ ==========
143
+
144
+ d : integer
145
+ degree of bspline
146
+
147
+ knots : list of integer values
148
+ list of knots points of bspline
149
+
150
+ n : integer
151
+ $n$-th B-spline
152
+
153
+ x : symbol
154
+
155
+ See Also
156
+ ========
157
+
158
+ bspline_basis_set
159
+
160
+ References
161
+ ==========
162
+
163
+ .. [1] https://en.wikipedia.org/wiki/B-spline
164
+
165
+ """
166
+ # make sure x has no assumptions so conditions don't evaluate
167
+ xvar = x
168
+ x = Dummy()
169
+
170
+ knots = tuple(sympify(k) for k in knots)
171
+ d = int(d)
172
+ n = int(n)
173
+ n_knots = len(knots)
174
+ n_intervals = n_knots - 1
175
+ if n + d + 1 > n_intervals:
176
+ raise ValueError("n + d + 1 must not exceed len(knots) - 1")
177
+ if d == 0:
178
+ result = Piecewise(
179
+ (S.One, Interval(knots[n], knots[n + 1]).contains(x)), (0, True)
180
+ )
181
+ elif d > 0:
182
+ denom = knots[n + d + 1] - knots[n + 1]
183
+ if denom != S.Zero:
184
+ B = (knots[n + d + 1] - x) / denom
185
+ b2 = bspline_basis(d - 1, knots, n + 1, x)
186
+ else:
187
+ b2 = B = S.Zero
188
+
189
+ denom = knots[n + d] - knots[n]
190
+ if denom != S.Zero:
191
+ A = (x - knots[n]) / denom
192
+ b1 = bspline_basis(d - 1, knots, n, x)
193
+ else:
194
+ b1 = A = S.Zero
195
+
196
+ result = _add_splines(A, b1, B, b2, x)
197
+ else:
198
+ raise ValueError("degree must be non-negative: %r" % n)
199
+
200
+ # return result with user-given x
201
+ return result.xreplace({x: xvar})
202
+
203
+
204
+ def bspline_basis_set(d, knots, x):
205
+ """
206
+ Return the ``len(knots)-d-1`` B-splines at *x* of degree *d*
207
+ with *knots*.
208
+
209
+ Explanation
210
+ ===========
211
+
212
+ This function returns a list of piecewise polynomials that are the
213
+ ``len(knots)-d-1`` B-splines of degree *d* for the given knots.
214
+ This function calls ``bspline_basis(d, knots, n, x)`` for different
215
+ values of *n*.
216
+
217
+ Examples
218
+ ========
219
+
220
+ >>> from sympy import bspline_basis_set
221
+ >>> from sympy.abc import x
222
+ >>> d = 2
223
+ >>> knots = range(5)
224
+ >>> splines = bspline_basis_set(d, knots, x)
225
+ >>> splines
226
+ [Piecewise((x**2/2, (x >= 0) & (x <= 1)),
227
+ (-x**2 + 3*x - 3/2, (x >= 1) & (x <= 2)),
228
+ (x**2/2 - 3*x + 9/2, (x >= 2) & (x <= 3)),
229
+ (0, True)),
230
+ Piecewise((x**2/2 - x + 1/2, (x >= 1) & (x <= 2)),
231
+ (-x**2 + 5*x - 11/2, (x >= 2) & (x <= 3)),
232
+ (x**2/2 - 4*x + 8, (x >= 3) & (x <= 4)),
233
+ (0, True))]
234
+
235
+ Parameters
236
+ ==========
237
+
238
+ d : integer
239
+ degree of bspline
240
+
241
+ knots : list of integers
242
+ list of knots points of bspline
243
+
244
+ x : symbol
245
+
246
+ See Also
247
+ ========
248
+
249
+ bspline_basis
250
+
251
+ """
252
+ n_splines = len(knots) - d - 1
253
+ return [bspline_basis(d, tuple(knots), i, x) for i in range(n_splines)]
254
+
255
+
256
+ def interpolating_spline(d, x, X, Y):
257
+ """
258
+ Return spline of degree *d*, passing through the given *X*
259
+ and *Y* values.
260
+
261
+ Explanation
262
+ ===========
263
+
264
+ This function returns a piecewise function such that each part is
265
+ a polynomial of degree not greater than *d*. The value of *d*
266
+ must be 1 or greater and the values of *X* must be strictly
267
+ increasing.
268
+
269
+ Examples
270
+ ========
271
+
272
+ >>> from sympy import interpolating_spline
273
+ >>> from sympy.abc import x
274
+ >>> interpolating_spline(1, x, [1, 2, 4, 7], [3, 6, 5, 7])
275
+ Piecewise((3*x, (x >= 1) & (x <= 2)),
276
+ (7 - x/2, (x >= 2) & (x <= 4)),
277
+ (2*x/3 + 7/3, (x >= 4) & (x <= 7)))
278
+ >>> interpolating_spline(3, x, [-2, 0, 1, 3, 4], [4, 2, 1, 1, 3])
279
+ Piecewise((7*x**3/117 + 7*x**2/117 - 131*x/117 + 2, (x >= -2) & (x <= 1)),
280
+ (10*x**3/117 - 2*x**2/117 - 122*x/117 + 77/39, (x >= 1) & (x <= 4)))
281
+
282
+ Parameters
283
+ ==========
284
+
285
+ d : integer
286
+ Degree of Bspline strictly greater than equal to one
287
+
288
+ x : symbol
289
+
290
+ X : list of strictly increasing real values
291
+ list of X coordinates through which the spline passes
292
+
293
+ Y : list of real values
294
+ list of corresponding Y coordinates through which the spline passes
295
+
296
+ See Also
297
+ ========
298
+
299
+ bspline_basis_set, interpolating_poly
300
+
301
+ """
302
+ from sympy.solvers.solveset import linsolve
303
+ from sympy.matrices.dense import Matrix
304
+
305
+ # Input sanitization
306
+ d = sympify(d)
307
+ if not (d.is_Integer and d.is_positive):
308
+ raise ValueError("Spline degree must be a positive integer, not %s." % d)
309
+ if len(X) != len(Y):
310
+ raise ValueError("Number of X and Y coordinates must be the same.")
311
+ if len(X) < d + 1:
312
+ raise ValueError("Degree must be less than the number of control points.")
313
+ if not all(a < b for a, b in zip(X, X[1:])):
314
+ raise ValueError("The x-coordinates must be strictly increasing.")
315
+ X = [sympify(i) for i in X]
316
+
317
+ # Evaluating knots value
318
+ if d.is_odd:
319
+ j = (d + 1) // 2
320
+ interior_knots = X[j:-j]
321
+ else:
322
+ j = d // 2
323
+ interior_knots = [
324
+ (a + b)/2 for a, b in zip(X[j : -j - 1], X[j + 1 : -j])
325
+ ]
326
+
327
+ knots = [X[0]] * (d + 1) + list(interior_knots) + [X[-1]] * (d + 1)
328
+
329
+ basis = bspline_basis_set(d, knots, x)
330
+
331
+ A = [[b.subs(x, v) for b in basis] for v in X]
332
+
333
+ coeff = linsolve((Matrix(A), Matrix(Y)), symbols("c0:{}".format(len(X)), cls=Dummy))
334
+ coeff = list(coeff)[0]
335
+ intervals = {c for b in basis for (e, c) in b.args if c != True}
336
+
337
+ # Sorting the intervals
338
+ # ival contains the end-points of each interval
339
+ ival = [_ivl(c, x) for c in intervals]
340
+ com = zip(ival, intervals)
341
+ com = sorted(com, key=lambda x: x[0])
342
+ intervals = [y for x, y in com]
343
+
344
+ basis_dicts = [{c: e for (e, c) in b.args} for b in basis]
345
+ spline = []
346
+ for i in intervals:
347
+ piece = sum(
348
+ [c * d.get(i, S.Zero) for (c, d) in zip(coeff, basis_dicts)], S.Zero
349
+ )
350
+ spline.append((piece, i))
351
+ return Piecewise(*spline)
venv/lib/python3.10/site-packages/sympy/functions/special/delta_functions.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, diff
2
+ from sympy.core.function import Function, ArgumentIndexError
3
+ from sympy.core.logic import fuzzy_not
4
+ from sympy.core.relational import Eq, Ne
5
+ from sympy.functions.elementary.complexes import im, sign
6
+ from sympy.functions.elementary.piecewise import Piecewise
7
+ from sympy.polys.polyerrors import PolynomialError
8
+ from sympy.polys.polyroots import roots
9
+ from sympy.utilities.misc import filldedent
10
+
11
+
12
+ ###############################################################################
13
+ ################################ DELTA FUNCTION ###############################
14
+ ###############################################################################
15
+
16
+
17
+ class DiracDelta(Function):
18
+ r"""
19
+ The DiracDelta function and its derivatives.
20
+
21
+ Explanation
22
+ ===========
23
+
24
+ DiracDelta is not an ordinary function. It can be rigorously defined either
25
+ as a distribution or as a measure.
26
+
27
+ DiracDelta only makes sense in definite integrals, and in particular,
28
+ integrals of the form ``Integral(f(x)*DiracDelta(x - x0), (x, a, b))``,
29
+ where it equals ``f(x0)`` if ``a <= x0 <= b`` and ``0`` otherwise. Formally,
30
+ DiracDelta acts in some ways like a function that is ``0`` everywhere except
31
+ at ``0``, but in many ways it also does not. It can often be useful to treat
32
+ DiracDelta in formal ways, building up and manipulating expressions with
33
+ delta functions (which may eventually be integrated), but care must be taken
34
+ to not treat it as a real function. SymPy's ``oo`` is similar. It only
35
+ truly makes sense formally in certain contexts (such as integration limits),
36
+ but SymPy allows its use everywhere, and it tries to be consistent with
37
+ operations on it (like ``1/oo``), but it is easy to get into trouble and get
38
+ wrong results if ``oo`` is treated too much like a number. Similarly, if
39
+ DiracDelta is treated too much like a function, it is easy to get wrong or
40
+ nonsensical results.
41
+
42
+ DiracDelta function has the following properties:
43
+
44
+ 1) $\frac{d}{d x} \theta(x) = \delta(x)$
45
+ 2) $\int_{-\infty}^\infty \delta(x - a)f(x)\, dx = f(a)$ and $\int_{a-
46
+ \epsilon}^{a+\epsilon} \delta(x - a)f(x)\, dx = f(a)$
47
+ 3) $\delta(x) = 0$ for all $x \neq 0$
48
+ 4) $\delta(g(x)) = \sum_i \frac{\delta(x - x_i)}{\|g'(x_i)\|}$ where $x_i$
49
+ are the roots of $g$
50
+ 5) $\delta(-x) = \delta(x)$
51
+
52
+ Derivatives of ``k``-th order of DiracDelta have the following properties:
53
+
54
+ 6) $\delta(x, k) = 0$ for all $x \neq 0$
55
+ 7) $\delta(-x, k) = -\delta(x, k)$ for odd $k$
56
+ 8) $\delta(-x, k) = \delta(x, k)$ for even $k$
57
+
58
+ Examples
59
+ ========
60
+
61
+ >>> from sympy import DiracDelta, diff, pi
62
+ >>> from sympy.abc import x, y
63
+
64
+ >>> DiracDelta(x)
65
+ DiracDelta(x)
66
+ >>> DiracDelta(1)
67
+ 0
68
+ >>> DiracDelta(-1)
69
+ 0
70
+ >>> DiracDelta(pi)
71
+ 0
72
+ >>> DiracDelta(x - 4).subs(x, 4)
73
+ DiracDelta(0)
74
+ >>> diff(DiracDelta(x))
75
+ DiracDelta(x, 1)
76
+ >>> diff(DiracDelta(x - 1), x, 2)
77
+ DiracDelta(x - 1, 2)
78
+ >>> diff(DiracDelta(x**2 - 1), x, 2)
79
+ 2*(2*x**2*DiracDelta(x**2 - 1, 2) + DiracDelta(x**2 - 1, 1))
80
+ >>> DiracDelta(3*x).is_simple(x)
81
+ True
82
+ >>> DiracDelta(x**2).is_simple(x)
83
+ False
84
+ >>> DiracDelta((x**2 - 1)*y).expand(diracdelta=True, wrt=x)
85
+ DiracDelta(x - 1)/(2*Abs(y)) + DiracDelta(x + 1)/(2*Abs(y))
86
+
87
+ See Also
88
+ ========
89
+
90
+ Heaviside
91
+ sympy.simplify.simplify.simplify, is_simple
92
+ sympy.functions.special.tensor_functions.KroneckerDelta
93
+
94
+ References
95
+ ==========
96
+
97
+ .. [1] https://mathworld.wolfram.com/DeltaFunction.html
98
+
99
+ """
100
+
101
+ is_real = True
102
+
103
+ def fdiff(self, argindex=1):
104
+ """
105
+ Returns the first derivative of a DiracDelta Function.
106
+
107
+ Explanation
108
+ ===========
109
+
110
+ The difference between ``diff()`` and ``fdiff()`` is: ``diff()`` is the
111
+ user-level function and ``fdiff()`` is an object method. ``fdiff()`` is
112
+ a convenience method available in the ``Function`` class. It returns
113
+ the derivative of the function without considering the chain rule.
114
+ ``diff(function, x)`` calls ``Function._eval_derivative`` which in turn
115
+ calls ``fdiff()`` internally to compute the derivative of the function.
116
+
117
+ Examples
118
+ ========
119
+
120
+ >>> from sympy import DiracDelta, diff
121
+ >>> from sympy.abc import x
122
+
123
+ >>> DiracDelta(x).fdiff()
124
+ DiracDelta(x, 1)
125
+
126
+ >>> DiracDelta(x, 1).fdiff()
127
+ DiracDelta(x, 2)
128
+
129
+ >>> DiracDelta(x**2 - 1).fdiff()
130
+ DiracDelta(x**2 - 1, 1)
131
+
132
+ >>> diff(DiracDelta(x, 1)).fdiff()
133
+ DiracDelta(x, 3)
134
+
135
+ Parameters
136
+ ==========
137
+
138
+ argindex : integer
139
+ degree of derivative
140
+
141
+ """
142
+ if argindex == 1:
143
+ #I didn't know if there is a better way to handle default arguments
144
+ k = 0
145
+ if len(self.args) > 1:
146
+ k = self.args[1]
147
+ return self.func(self.args[0], k + 1)
148
+ else:
149
+ raise ArgumentIndexError(self, argindex)
150
+
151
+ @classmethod
152
+ def eval(cls, arg, k=S.Zero):
153
+ """
154
+ Returns a simplified form or a value of DiracDelta depending on the
155
+ argument passed by the DiracDelta object.
156
+
157
+ Explanation
158
+ ===========
159
+
160
+ The ``eval()`` method is automatically called when the ``DiracDelta``
161
+ class is about to be instantiated and it returns either some simplified
162
+ instance or the unevaluated instance depending on the argument passed.
163
+ In other words, ``eval()`` method is not needed to be called explicitly,
164
+ it is being called and evaluated once the object is called.
165
+
166
+ Examples
167
+ ========
168
+
169
+ >>> from sympy import DiracDelta, S
170
+ >>> from sympy.abc import x
171
+
172
+ >>> DiracDelta(x)
173
+ DiracDelta(x)
174
+
175
+ >>> DiracDelta(-x, 1)
176
+ -DiracDelta(x, 1)
177
+
178
+ >>> DiracDelta(1)
179
+ 0
180
+
181
+ >>> DiracDelta(5, 1)
182
+ 0
183
+
184
+ >>> DiracDelta(0)
185
+ DiracDelta(0)
186
+
187
+ >>> DiracDelta(-1)
188
+ 0
189
+
190
+ >>> DiracDelta(S.NaN)
191
+ nan
192
+
193
+ >>> DiracDelta(x - 100).subs(x, 5)
194
+ 0
195
+
196
+ >>> DiracDelta(x - 100).subs(x, 100)
197
+ DiracDelta(0)
198
+
199
+ Parameters
200
+ ==========
201
+
202
+ k : integer
203
+ order of derivative
204
+
205
+ arg : argument passed to DiracDelta
206
+
207
+ """
208
+ if not k.is_Integer or k.is_negative:
209
+ raise ValueError("Error: the second argument of DiracDelta must be \
210
+ a non-negative integer, %s given instead." % (k,))
211
+ if arg is S.NaN:
212
+ return S.NaN
213
+ if arg.is_nonzero:
214
+ return S.Zero
215
+ if fuzzy_not(im(arg).is_zero):
216
+ raise ValueError(filldedent('''
217
+ Function defined only for Real Values.
218
+ Complex part: %s found in %s .''' % (
219
+ repr(im(arg)), repr(arg))))
220
+ c, nc = arg.args_cnc()
221
+ if c and c[0] is S.NegativeOne:
222
+ # keep this fast and simple instead of using
223
+ # could_extract_minus_sign
224
+ if k.is_odd:
225
+ return -cls(-arg, k)
226
+ elif k.is_even:
227
+ return cls(-arg, k) if k else cls(-arg)
228
+ elif k.is_zero:
229
+ return cls(arg, evaluate=False)
230
+
231
+ def _eval_expand_diracdelta(self, **hints):
232
+ """
233
+ Compute a simplified representation of the function using
234
+ property number 4. Pass ``wrt`` as a hint to expand the expression
235
+ with respect to a particular variable.
236
+
237
+ Explanation
238
+ ===========
239
+
240
+ ``wrt`` is:
241
+
242
+ - a variable with respect to which a DiracDelta expression will
243
+ get expanded.
244
+
245
+ Examples
246
+ ========
247
+
248
+ >>> from sympy import DiracDelta
249
+ >>> from sympy.abc import x, y
250
+
251
+ >>> DiracDelta(x*y).expand(diracdelta=True, wrt=x)
252
+ DiracDelta(x)/Abs(y)
253
+ >>> DiracDelta(x*y).expand(diracdelta=True, wrt=y)
254
+ DiracDelta(y)/Abs(x)
255
+
256
+ >>> DiracDelta(x**2 + x - 2).expand(diracdelta=True, wrt=x)
257
+ DiracDelta(x - 1)/3 + DiracDelta(x + 2)/3
258
+
259
+ See Also
260
+ ========
261
+
262
+ is_simple, Diracdelta
263
+
264
+ """
265
+ wrt = hints.get('wrt', None)
266
+ if wrt is None:
267
+ free = self.free_symbols
268
+ if len(free) == 1:
269
+ wrt = free.pop()
270
+ else:
271
+ raise TypeError(filldedent('''
272
+ When there is more than 1 free symbol or variable in the expression,
273
+ the 'wrt' keyword is required as a hint to expand when using the
274
+ DiracDelta hint.'''))
275
+
276
+ if not self.args[0].has(wrt) or (len(self.args) > 1 and self.args[1] != 0 ):
277
+ return self
278
+ try:
279
+ argroots = roots(self.args[0], wrt)
280
+ result = 0
281
+ valid = True
282
+ darg = abs(diff(self.args[0], wrt))
283
+ for r, m in argroots.items():
284
+ if r.is_real is not False and m == 1:
285
+ result += self.func(wrt - r)/darg.subs(wrt, r)
286
+ else:
287
+ # don't handle non-real and if m != 1 then
288
+ # a polynomial will have a zero in the derivative (darg)
289
+ # at r
290
+ valid = False
291
+ break
292
+ if valid:
293
+ return result
294
+ except PolynomialError:
295
+ pass
296
+ return self
297
+
298
+ def is_simple(self, x):
299
+ """
300
+ Tells whether the argument(args[0]) of DiracDelta is a linear
301
+ expression in *x*.
302
+
303
+ Examples
304
+ ========
305
+
306
+ >>> from sympy import DiracDelta, cos
307
+ >>> from sympy.abc import x, y
308
+
309
+ >>> DiracDelta(x*y).is_simple(x)
310
+ True
311
+ >>> DiracDelta(x*y).is_simple(y)
312
+ True
313
+
314
+ >>> DiracDelta(x**2 + x - 2).is_simple(x)
315
+ False
316
+
317
+ >>> DiracDelta(cos(x)).is_simple(x)
318
+ False
319
+
320
+ Parameters
321
+ ==========
322
+
323
+ x : can be a symbol
324
+
325
+ See Also
326
+ ========
327
+
328
+ sympy.simplify.simplify.simplify, DiracDelta
329
+
330
+ """
331
+ p = self.args[0].as_poly(x)
332
+ if p:
333
+ return p.degree() == 1
334
+ return False
335
+
336
+ def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
337
+ """
338
+ Represents DiracDelta in a piecewise form.
339
+
340
+ Examples
341
+ ========
342
+
343
+ >>> from sympy import DiracDelta, Piecewise, Symbol
344
+ >>> x = Symbol('x')
345
+
346
+ >>> DiracDelta(x).rewrite(Piecewise)
347
+ Piecewise((DiracDelta(0), Eq(x, 0)), (0, True))
348
+
349
+ >>> DiracDelta(x - 5).rewrite(Piecewise)
350
+ Piecewise((DiracDelta(0), Eq(x, 5)), (0, True))
351
+
352
+ >>> DiracDelta(x**2 - 5).rewrite(Piecewise)
353
+ Piecewise((DiracDelta(0), Eq(x**2, 5)), (0, True))
354
+
355
+ >>> DiracDelta(x - 5, 4).rewrite(Piecewise)
356
+ DiracDelta(x - 5, 4)
357
+
358
+ """
359
+ if len(args) == 1:
360
+ return Piecewise((DiracDelta(0), Eq(args[0], 0)), (0, True))
361
+
362
+ def _eval_rewrite_as_SingularityFunction(self, *args, **kwargs):
363
+ """
364
+ Returns the DiracDelta expression written in the form of Singularity
365
+ Functions.
366
+
367
+ """
368
+ from sympy.solvers import solve
369
+ from sympy.functions.special.singularity_functions import SingularityFunction
370
+ if self == DiracDelta(0):
371
+ return SingularityFunction(0, 0, -1)
372
+ if self == DiracDelta(0, 1):
373
+ return SingularityFunction(0, 0, -2)
374
+ free = self.free_symbols
375
+ if len(free) == 1:
376
+ x = (free.pop())
377
+ if len(args) == 1:
378
+ return SingularityFunction(x, solve(args[0], x)[0], -1)
379
+ return SingularityFunction(x, solve(args[0], x)[0], -args[1] - 1)
380
+ else:
381
+ # I don't know how to handle the case for DiracDelta expressions
382
+ # having arguments with more than one variable.
383
+ raise TypeError(filldedent('''
384
+ rewrite(SingularityFunction) does not support
385
+ arguments with more that one variable.'''))
386
+
387
+
388
+ ###############################################################################
389
+ ############################## HEAVISIDE FUNCTION #############################
390
+ ###############################################################################
391
+
392
+
393
+ class Heaviside(Function):
394
+ r"""
395
+ Heaviside step function.
396
+
397
+ Explanation
398
+ ===========
399
+
400
+ The Heaviside step function has the following properties:
401
+
402
+ 1) $\frac{d}{d x} \theta(x) = \delta(x)$
403
+ 2) $\theta(x) = \begin{cases} 0 & \text{for}\: x < 0 \\ \frac{1}{2} &
404
+ \text{for}\: x = 0 \\1 & \text{for}\: x > 0 \end{cases}$
405
+ 3) $\frac{d}{d x} \max(x, 0) = \theta(x)$
406
+
407
+ Heaviside(x) is printed as $\theta(x)$ with the SymPy LaTeX printer.
408
+
409
+ The value at 0 is set differently in different fields. SymPy uses 1/2,
410
+ which is a convention from electronics and signal processing, and is
411
+ consistent with solving improper integrals by Fourier transform and
412
+ convolution.
413
+
414
+ To specify a different value of Heaviside at ``x=0``, a second argument
415
+ can be given. Using ``Heaviside(x, nan)`` gives an expression that will
416
+ evaluate to nan for x=0.
417
+
418
+ .. versionchanged:: 1.9 ``Heaviside(0)`` now returns 1/2 (before: undefined)
419
+
420
+ Examples
421
+ ========
422
+
423
+ >>> from sympy import Heaviside, nan
424
+ >>> from sympy.abc import x
425
+ >>> Heaviside(9)
426
+ 1
427
+ >>> Heaviside(-9)
428
+ 0
429
+ >>> Heaviside(0)
430
+ 1/2
431
+ >>> Heaviside(0, nan)
432
+ nan
433
+ >>> (Heaviside(x) + 1).replace(Heaviside(x), Heaviside(x, 1))
434
+ Heaviside(x, 1) + 1
435
+
436
+ See Also
437
+ ========
438
+
439
+ DiracDelta
440
+
441
+ References
442
+ ==========
443
+
444
+ .. [1] https://mathworld.wolfram.com/HeavisideStepFunction.html
445
+ .. [2] https://dlmf.nist.gov/1.16#iv
446
+
447
+ """
448
+
449
+ is_real = True
450
+
451
+ def fdiff(self, argindex=1):
452
+ """
453
+ Returns the first derivative of a Heaviside Function.
454
+
455
+ Examples
456
+ ========
457
+
458
+ >>> from sympy import Heaviside, diff
459
+ >>> from sympy.abc import x
460
+
461
+ >>> Heaviside(x).fdiff()
462
+ DiracDelta(x)
463
+
464
+ >>> Heaviside(x**2 - 1).fdiff()
465
+ DiracDelta(x**2 - 1)
466
+
467
+ >>> diff(Heaviside(x)).fdiff()
468
+ DiracDelta(x, 1)
469
+
470
+ Parameters
471
+ ==========
472
+
473
+ argindex : integer
474
+ order of derivative
475
+
476
+ """
477
+ if argindex == 1:
478
+ return DiracDelta(self.args[0])
479
+ else:
480
+ raise ArgumentIndexError(self, argindex)
481
+
482
+ def __new__(cls, arg, H0=S.Half, **options):
483
+ if isinstance(H0, Heaviside) and len(H0.args) == 1:
484
+ H0 = S.Half
485
+ return super(cls, cls).__new__(cls, arg, H0, **options)
486
+
487
+ @property
488
+ def pargs(self):
489
+ """Args without default S.Half"""
490
+ args = self.args
491
+ if args[1] is S.Half:
492
+ args = args[:1]
493
+ return args
494
+
495
+ @classmethod
496
+ def eval(cls, arg, H0=S.Half):
497
+ """
498
+ Returns a simplified form or a value of Heaviside depending on the
499
+ argument passed by the Heaviside object.
500
+
501
+ Explanation
502
+ ===========
503
+
504
+ The ``eval()`` method is automatically called when the ``Heaviside``
505
+ class is about to be instantiated and it returns either some simplified
506
+ instance or the unevaluated instance depending on the argument passed.
507
+ In other words, ``eval()`` method is not needed to be called explicitly,
508
+ it is being called and evaluated once the object is called.
509
+
510
+ Examples
511
+ ========
512
+
513
+ >>> from sympy import Heaviside, S
514
+ >>> from sympy.abc import x
515
+
516
+ >>> Heaviside(x)
517
+ Heaviside(x)
518
+
519
+ >>> Heaviside(19)
520
+ 1
521
+
522
+ >>> Heaviside(0)
523
+ 1/2
524
+
525
+ >>> Heaviside(0, 1)
526
+ 1
527
+
528
+ >>> Heaviside(-5)
529
+ 0
530
+
531
+ >>> Heaviside(S.NaN)
532
+ nan
533
+
534
+ >>> Heaviside(x - 100).subs(x, 5)
535
+ 0
536
+
537
+ >>> Heaviside(x - 100).subs(x, 105)
538
+ 1
539
+
540
+ Parameters
541
+ ==========
542
+
543
+ arg : argument passed by Heaviside object
544
+
545
+ H0 : value of Heaviside(0)
546
+
547
+ """
548
+ if arg.is_extended_negative:
549
+ return S.Zero
550
+ elif arg.is_extended_positive:
551
+ return S.One
552
+ elif arg.is_zero:
553
+ return H0
554
+ elif arg is S.NaN:
555
+ return S.NaN
556
+ elif fuzzy_not(im(arg).is_zero):
557
+ raise ValueError("Function defined only for Real Values. Complex part: %s found in %s ." % (repr(im(arg)), repr(arg)) )
558
+
559
+ def _eval_rewrite_as_Piecewise(self, arg, H0=None, **kwargs):
560
+ """
561
+ Represents Heaviside in a Piecewise form.
562
+
563
+ Examples
564
+ ========
565
+
566
+ >>> from sympy import Heaviside, Piecewise, Symbol, nan
567
+ >>> x = Symbol('x')
568
+
569
+ >>> Heaviside(x).rewrite(Piecewise)
570
+ Piecewise((0, x < 0), (1/2, Eq(x, 0)), (1, True))
571
+
572
+ >>> Heaviside(x,nan).rewrite(Piecewise)
573
+ Piecewise((0, x < 0), (nan, Eq(x, 0)), (1, True))
574
+
575
+ >>> Heaviside(x - 5).rewrite(Piecewise)
576
+ Piecewise((0, x < 5), (1/2, Eq(x, 5)), (1, True))
577
+
578
+ >>> Heaviside(x**2 - 1).rewrite(Piecewise)
579
+ Piecewise((0, x**2 < 1), (1/2, Eq(x**2, 1)), (1, True))
580
+
581
+ """
582
+ if H0 == 0:
583
+ return Piecewise((0, arg <= 0), (1, True))
584
+ if H0 == 1:
585
+ return Piecewise((0, arg < 0), (1, True))
586
+ return Piecewise((0, arg < 0), (H0, Eq(arg, 0)), (1, True))
587
+
588
+ def _eval_rewrite_as_sign(self, arg, H0=S.Half, **kwargs):
589
+ """
590
+ Represents the Heaviside function in the form of sign function.
591
+
592
+ Explanation
593
+ ===========
594
+
595
+ The value of Heaviside(0) must be 1/2 for rewriting as sign to be
596
+ strictly equivalent. For easier usage, we also allow this rewriting
597
+ when Heaviside(0) is undefined.
598
+
599
+ Examples
600
+ ========
601
+
602
+ >>> from sympy import Heaviside, Symbol, sign, nan
603
+ >>> x = Symbol('x', real=True)
604
+ >>> y = Symbol('y')
605
+
606
+ >>> Heaviside(x).rewrite(sign)
607
+ sign(x)/2 + 1/2
608
+
609
+ >>> Heaviside(x, 0).rewrite(sign)
610
+ Piecewise((sign(x)/2 + 1/2, Ne(x, 0)), (0, True))
611
+
612
+ >>> Heaviside(x, nan).rewrite(sign)
613
+ Piecewise((sign(x)/2 + 1/2, Ne(x, 0)), (nan, True))
614
+
615
+ >>> Heaviside(x - 2).rewrite(sign)
616
+ sign(x - 2)/2 + 1/2
617
+
618
+ >>> Heaviside(x**2 - 2*x + 1).rewrite(sign)
619
+ sign(x**2 - 2*x + 1)/2 + 1/2
620
+
621
+ >>> Heaviside(y).rewrite(sign)
622
+ Heaviside(y)
623
+
624
+ >>> Heaviside(y**2 - 2*y + 1).rewrite(sign)
625
+ Heaviside(y**2 - 2*y + 1)
626
+
627
+ See Also
628
+ ========
629
+
630
+ sign
631
+
632
+ """
633
+ if arg.is_extended_real:
634
+ pw1 = Piecewise(
635
+ ((sign(arg) + 1)/2, Ne(arg, 0)),
636
+ (Heaviside(0, H0=H0), True))
637
+ pw2 = Piecewise(
638
+ ((sign(arg) + 1)/2, Eq(Heaviside(0, H0=H0), S.Half)),
639
+ (pw1, True))
640
+ return pw2
641
+
642
+ def _eval_rewrite_as_SingularityFunction(self, args, H0=S.Half, **kwargs):
643
+ """
644
+ Returns the Heaviside expression written in the form of Singularity
645
+ Functions.
646
+
647
+ """
648
+ from sympy.solvers import solve
649
+ from sympy.functions.special.singularity_functions import SingularityFunction
650
+ if self == Heaviside(0):
651
+ return SingularityFunction(0, 0, 0)
652
+ free = self.free_symbols
653
+ if len(free) == 1:
654
+ x = (free.pop())
655
+ return SingularityFunction(x, solve(args, x)[0], 0)
656
+ # TODO
657
+ # ((x - 5)**3*Heaviside(x - 5)).rewrite(SingularityFunction) should output
658
+ # SingularityFunction(x, 5, 0) instead of (x - 5)**3*SingularityFunction(x, 5, 0)
659
+ else:
660
+ # I don't know how to handle the case for Heaviside expressions
661
+ # having arguments with more than one variable.
662
+ raise TypeError(filldedent('''
663
+ rewrite(SingularityFunction) does not
664
+ support arguments with more that one variable.'''))
venv/lib/python3.10/site-packages/sympy/functions/special/elliptic_integrals.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Elliptic Integrals. """
2
+
3
+ from sympy.core import S, pi, I, Rational
4
+ from sympy.core.function import Function, ArgumentIndexError
5
+ from sympy.core.symbol import Dummy
6
+ from sympy.functions.elementary.complexes import sign
7
+ from sympy.functions.elementary.hyperbolic import atanh
8
+ from sympy.functions.elementary.miscellaneous import sqrt
9
+ from sympy.functions.elementary.trigonometric import sin, tan
10
+ from sympy.functions.special.gamma_functions import gamma
11
+ from sympy.functions.special.hyper import hyper, meijerg
12
+
13
+ class elliptic_k(Function):
14
+ r"""
15
+ The complete elliptic integral of the first kind, defined by
16
+
17
+ .. math:: K(m) = F\left(\tfrac{\pi}{2}\middle| m\right)
18
+
19
+ where $F\left(z\middle| m\right)$ is the Legendre incomplete
20
+ elliptic integral of the first kind.
21
+
22
+ Explanation
23
+ ===========
24
+
25
+ The function $K(m)$ is a single-valued function on the complex
26
+ plane with branch cut along the interval $(1, \infty)$.
27
+
28
+ Note that our notation defines the incomplete elliptic integral
29
+ in terms of the parameter $m$ instead of the elliptic modulus
30
+ (eccentricity) $k$.
31
+ In this case, the parameter $m$ is defined as $m=k^2$.
32
+
33
+ Examples
34
+ ========
35
+
36
+ >>> from sympy import elliptic_k, I
37
+ >>> from sympy.abc import m
38
+ >>> elliptic_k(0)
39
+ pi/2
40
+ >>> elliptic_k(1.0 + I)
41
+ 1.50923695405127 + 0.625146415202697*I
42
+ >>> elliptic_k(m).series(n=3)
43
+ pi/2 + pi*m/8 + 9*pi*m**2/128 + O(m**3)
44
+
45
+ See Also
46
+ ========
47
+
48
+ elliptic_f
49
+
50
+ References
51
+ ==========
52
+
53
+ .. [1] https://en.wikipedia.org/wiki/Elliptic_integrals
54
+ .. [2] https://functions.wolfram.com/EllipticIntegrals/EllipticK
55
+
56
+ """
57
+
58
+ @classmethod
59
+ def eval(cls, m):
60
+ if m.is_zero:
61
+ return pi*S.Half
62
+ elif m is S.Half:
63
+ return 8*pi**Rational(3, 2)/gamma(Rational(-1, 4))**2
64
+ elif m is S.One:
65
+ return S.ComplexInfinity
66
+ elif m is S.NegativeOne:
67
+ return gamma(Rational(1, 4))**2/(4*sqrt(2*pi))
68
+ elif m in (S.Infinity, S.NegativeInfinity, I*S.Infinity,
69
+ I*S.NegativeInfinity, S.ComplexInfinity):
70
+ return S.Zero
71
+
72
+ def fdiff(self, argindex=1):
73
+ m = self.args[0]
74
+ return (elliptic_e(m) - (1 - m)*elliptic_k(m))/(2*m*(1 - m))
75
+
76
+ def _eval_conjugate(self):
77
+ m = self.args[0]
78
+ if (m.is_real and (m - 1).is_positive) is False:
79
+ return self.func(m.conjugate())
80
+
81
+ def _eval_nseries(self, x, n, logx, cdir=0):
82
+ from sympy.simplify import hyperexpand
83
+ return hyperexpand(self.rewrite(hyper)._eval_nseries(x, n=n, logx=logx))
84
+
85
+ def _eval_rewrite_as_hyper(self, m, **kwargs):
86
+ return pi*S.Half*hyper((S.Half, S.Half), (S.One,), m)
87
+
88
+ def _eval_rewrite_as_meijerg(self, m, **kwargs):
89
+ return meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -m)/2
90
+
91
+ def _eval_is_zero(self):
92
+ m = self.args[0]
93
+ if m.is_infinite:
94
+ return True
95
+
96
+ def _eval_rewrite_as_Integral(self, *args):
97
+ from sympy.integrals.integrals import Integral
98
+ t = Dummy('t')
99
+ m = self.args[0]
100
+ return Integral(1/sqrt(1 - m*sin(t)**2), (t, 0, pi/2))
101
+
102
+
103
+ class elliptic_f(Function):
104
+ r"""
105
+ The Legendre incomplete elliptic integral of the first
106
+ kind, defined by
107
+
108
+ .. math:: F\left(z\middle| m\right) =
109
+ \int_0^z \frac{dt}{\sqrt{1 - m \sin^2 t}}
110
+
111
+ Explanation
112
+ ===========
113
+
114
+ This function reduces to a complete elliptic integral of
115
+ the first kind, $K(m)$, when $z = \pi/2$.
116
+
117
+ Note that our notation defines the incomplete elliptic integral
118
+ in terms of the parameter $m$ instead of the elliptic modulus
119
+ (eccentricity) $k$.
120
+ In this case, the parameter $m$ is defined as $m=k^2$.
121
+
122
+ Examples
123
+ ========
124
+
125
+ >>> from sympy import elliptic_f, I
126
+ >>> from sympy.abc import z, m
127
+ >>> elliptic_f(z, m).series(z)
128
+ z + z**5*(3*m**2/40 - m/30) + m*z**3/6 + O(z**6)
129
+ >>> elliptic_f(3.0 + I/2, 1.0 + I)
130
+ 2.909449841483 + 1.74720545502474*I
131
+
132
+ See Also
133
+ ========
134
+
135
+ elliptic_k
136
+
137
+ References
138
+ ==========
139
+
140
+ .. [1] https://en.wikipedia.org/wiki/Elliptic_integrals
141
+ .. [2] https://functions.wolfram.com/EllipticIntegrals/EllipticF
142
+
143
+ """
144
+
145
+ @classmethod
146
+ def eval(cls, z, m):
147
+ if z.is_zero:
148
+ return S.Zero
149
+ if m.is_zero:
150
+ return z
151
+ k = 2*z/pi
152
+ if k.is_integer:
153
+ return k*elliptic_k(m)
154
+ elif m in (S.Infinity, S.NegativeInfinity):
155
+ return S.Zero
156
+ elif z.could_extract_minus_sign():
157
+ return -elliptic_f(-z, m)
158
+
159
+ def fdiff(self, argindex=1):
160
+ z, m = self.args
161
+ fm = sqrt(1 - m*sin(z)**2)
162
+ if argindex == 1:
163
+ return 1/fm
164
+ elif argindex == 2:
165
+ return (elliptic_e(z, m)/(2*m*(1 - m)) - elliptic_f(z, m)/(2*m) -
166
+ sin(2*z)/(4*(1 - m)*fm))
167
+ raise ArgumentIndexError(self, argindex)
168
+
169
+ def _eval_conjugate(self):
170
+ z, m = self.args
171
+ if (m.is_real and (m - 1).is_positive) is False:
172
+ return self.func(z.conjugate(), m.conjugate())
173
+
174
+ def _eval_rewrite_as_Integral(self, *args):
175
+ from sympy.integrals.integrals import Integral
176
+ t = Dummy('t')
177
+ z, m = self.args[0], self.args[1]
178
+ return Integral(1/(sqrt(1 - m*sin(t)**2)), (t, 0, z))
179
+
180
+ def _eval_is_zero(self):
181
+ z, m = self.args
182
+ if z.is_zero:
183
+ return True
184
+ if m.is_extended_real and m.is_infinite:
185
+ return True
186
+
187
+
188
+ class elliptic_e(Function):
189
+ r"""
190
+ Called with two arguments $z$ and $m$, evaluates the
191
+ incomplete elliptic integral of the second kind, defined by
192
+
193
+ .. math:: E\left(z\middle| m\right) = \int_0^z \sqrt{1 - m \sin^2 t} dt
194
+
195
+ Called with a single argument $m$, evaluates the Legendre complete
196
+ elliptic integral of the second kind
197
+
198
+ .. math:: E(m) = E\left(\tfrac{\pi}{2}\middle| m\right)
199
+
200
+ Explanation
201
+ ===========
202
+
203
+ The function $E(m)$ is a single-valued function on the complex
204
+ plane with branch cut along the interval $(1, \infty)$.
205
+
206
+ Note that our notation defines the incomplete elliptic integral
207
+ in terms of the parameter $m$ instead of the elliptic modulus
208
+ (eccentricity) $k$.
209
+ In this case, the parameter $m$ is defined as $m=k^2$.
210
+
211
+ Examples
212
+ ========
213
+
214
+ >>> from sympy import elliptic_e, I
215
+ >>> from sympy.abc import z, m
216
+ >>> elliptic_e(z, m).series(z)
217
+ z + z**5*(-m**2/40 + m/30) - m*z**3/6 + O(z**6)
218
+ >>> elliptic_e(m).series(n=4)
219
+ pi/2 - pi*m/8 - 3*pi*m**2/128 - 5*pi*m**3/512 + O(m**4)
220
+ >>> elliptic_e(1 + I, 2 - I/2).n()
221
+ 1.55203744279187 + 0.290764986058437*I
222
+ >>> elliptic_e(0)
223
+ pi/2
224
+ >>> elliptic_e(2.0 - I)
225
+ 0.991052601328069 + 0.81879421395609*I
226
+
227
+ References
228
+ ==========
229
+
230
+ .. [1] https://en.wikipedia.org/wiki/Elliptic_integrals
231
+ .. [2] https://functions.wolfram.com/EllipticIntegrals/EllipticE2
232
+ .. [3] https://functions.wolfram.com/EllipticIntegrals/EllipticE
233
+
234
+ """
235
+
236
+ @classmethod
237
+ def eval(cls, m, z=None):
238
+ if z is not None:
239
+ z, m = m, z
240
+ k = 2*z/pi
241
+ if m.is_zero:
242
+ return z
243
+ if z.is_zero:
244
+ return S.Zero
245
+ elif k.is_integer:
246
+ return k*elliptic_e(m)
247
+ elif m in (S.Infinity, S.NegativeInfinity):
248
+ return S.ComplexInfinity
249
+ elif z.could_extract_minus_sign():
250
+ return -elliptic_e(-z, m)
251
+ else:
252
+ if m.is_zero:
253
+ return pi/2
254
+ elif m is S.One:
255
+ return S.One
256
+ elif m is S.Infinity:
257
+ return I*S.Infinity
258
+ elif m is S.NegativeInfinity:
259
+ return S.Infinity
260
+ elif m is S.ComplexInfinity:
261
+ return S.ComplexInfinity
262
+
263
+ def fdiff(self, argindex=1):
264
+ if len(self.args) == 2:
265
+ z, m = self.args
266
+ if argindex == 1:
267
+ return sqrt(1 - m*sin(z)**2)
268
+ elif argindex == 2:
269
+ return (elliptic_e(z, m) - elliptic_f(z, m))/(2*m)
270
+ else:
271
+ m = self.args[0]
272
+ if argindex == 1:
273
+ return (elliptic_e(m) - elliptic_k(m))/(2*m)
274
+ raise ArgumentIndexError(self, argindex)
275
+
276
+ def _eval_conjugate(self):
277
+ if len(self.args) == 2:
278
+ z, m = self.args
279
+ if (m.is_real and (m - 1).is_positive) is False:
280
+ return self.func(z.conjugate(), m.conjugate())
281
+ else:
282
+ m = self.args[0]
283
+ if (m.is_real and (m - 1).is_positive) is False:
284
+ return self.func(m.conjugate())
285
+
286
+ def _eval_nseries(self, x, n, logx, cdir=0):
287
+ from sympy.simplify import hyperexpand
288
+ if len(self.args) == 1:
289
+ return hyperexpand(self.rewrite(hyper)._eval_nseries(x, n=n, logx=logx))
290
+ return super()._eval_nseries(x, n=n, logx=logx)
291
+
292
+ def _eval_rewrite_as_hyper(self, *args, **kwargs):
293
+ if len(args) == 1:
294
+ m = args[0]
295
+ return (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), m)
296
+
297
+ def _eval_rewrite_as_meijerg(self, *args, **kwargs):
298
+ if len(args) == 1:
299
+ m = args[0]
300
+ return -meijerg(((S.Half, Rational(3, 2)), []), \
301
+ ((S.Zero,), (S.Zero,)), -m)/4
302
+
303
+ def _eval_rewrite_as_Integral(self, *args):
304
+ from sympy.integrals.integrals import Integral
305
+ z, m = (pi/2, self.args[0]) if len(self.args) == 1 else self.args
306
+ t = Dummy('t')
307
+ return Integral(sqrt(1 - m*sin(t)**2), (t, 0, z))
308
+
309
+
310
+ class elliptic_pi(Function):
311
+ r"""
312
+ Called with three arguments $n$, $z$ and $m$, evaluates the
313
+ Legendre incomplete elliptic integral of the third kind, defined by
314
+
315
+ .. math:: \Pi\left(n; z\middle| m\right) = \int_0^z \frac{dt}
316
+ {\left(1 - n \sin^2 t\right) \sqrt{1 - m \sin^2 t}}
317
+
318
+ Called with two arguments $n$ and $m$, evaluates the complete
319
+ elliptic integral of the third kind:
320
+
321
+ .. math:: \Pi\left(n\middle| m\right) =
322
+ \Pi\left(n; \tfrac{\pi}{2}\middle| m\right)
323
+
324
+ Explanation
325
+ ===========
326
+
327
+ Note that our notation defines the incomplete elliptic integral
328
+ in terms of the parameter $m$ instead of the elliptic modulus
329
+ (eccentricity) $k$.
330
+ In this case, the parameter $m$ is defined as $m=k^2$.
331
+
332
+ Examples
333
+ ========
334
+
335
+ >>> from sympy import elliptic_pi, I
336
+ >>> from sympy.abc import z, n, m
337
+ >>> elliptic_pi(n, z, m).series(z, n=4)
338
+ z + z**3*(m/6 + n/3) + O(z**4)
339
+ >>> elliptic_pi(0.5 + I, 1.0 - I, 1.2)
340
+ 2.50232379629182 - 0.760939574180767*I
341
+ >>> elliptic_pi(0, 0)
342
+ pi/2
343
+ >>> elliptic_pi(1.0 - I/3, 2.0 + I)
344
+ 3.29136443417283 + 0.32555634906645*I
345
+
346
+ References
347
+ ==========
348
+
349
+ .. [1] https://en.wikipedia.org/wiki/Elliptic_integrals
350
+ .. [2] https://functions.wolfram.com/EllipticIntegrals/EllipticPi3
351
+ .. [3] https://functions.wolfram.com/EllipticIntegrals/EllipticPi
352
+
353
+ """
354
+
355
+ @classmethod
356
+ def eval(cls, n, m, z=None):
357
+ if z is not None:
358
+ n, z, m = n, m, z
359
+ if n.is_zero:
360
+ return elliptic_f(z, m)
361
+ elif n is S.One:
362
+ return (elliptic_f(z, m) +
363
+ (sqrt(1 - m*sin(z)**2)*tan(z) -
364
+ elliptic_e(z, m))/(1 - m))
365
+ k = 2*z/pi
366
+ if k.is_integer:
367
+ return k*elliptic_pi(n, m)
368
+ elif m.is_zero:
369
+ return atanh(sqrt(n - 1)*tan(z))/sqrt(n - 1)
370
+ elif n == m:
371
+ return (elliptic_f(z, n) - elliptic_pi(1, z, n) +
372
+ tan(z)/sqrt(1 - n*sin(z)**2))
373
+ elif n in (S.Infinity, S.NegativeInfinity):
374
+ return S.Zero
375
+ elif m in (S.Infinity, S.NegativeInfinity):
376
+ return S.Zero
377
+ elif z.could_extract_minus_sign():
378
+ return -elliptic_pi(n, -z, m)
379
+ if n.is_zero:
380
+ return elliptic_f(z, m)
381
+ if m.is_extended_real and m.is_infinite or \
382
+ n.is_extended_real and n.is_infinite:
383
+ return S.Zero
384
+ else:
385
+ if n.is_zero:
386
+ return elliptic_k(m)
387
+ elif n is S.One:
388
+ return S.ComplexInfinity
389
+ elif m.is_zero:
390
+ return pi/(2*sqrt(1 - n))
391
+ elif m == S.One:
392
+ return S.NegativeInfinity/sign(n - 1)
393
+ elif n == m:
394
+ return elliptic_e(n)/(1 - n)
395
+ elif n in (S.Infinity, S.NegativeInfinity):
396
+ return S.Zero
397
+ elif m in (S.Infinity, S.NegativeInfinity):
398
+ return S.Zero
399
+ if n.is_zero:
400
+ return elliptic_k(m)
401
+ if m.is_extended_real and m.is_infinite or \
402
+ n.is_extended_real and n.is_infinite:
403
+ return S.Zero
404
+
405
+ def _eval_conjugate(self):
406
+ if len(self.args) == 3:
407
+ n, z, m = self.args
408
+ if (n.is_real and (n - 1).is_positive) is False and \
409
+ (m.is_real and (m - 1).is_positive) is False:
410
+ return self.func(n.conjugate(), z.conjugate(), m.conjugate())
411
+ else:
412
+ n, m = self.args
413
+ return self.func(n.conjugate(), m.conjugate())
414
+
415
+ def fdiff(self, argindex=1):
416
+ if len(self.args) == 3:
417
+ n, z, m = self.args
418
+ fm, fn = sqrt(1 - m*sin(z)**2), 1 - n*sin(z)**2
419
+ if argindex == 1:
420
+ return (elliptic_e(z, m) + (m - n)*elliptic_f(z, m)/n +
421
+ (n**2 - m)*elliptic_pi(n, z, m)/n -
422
+ n*fm*sin(2*z)/(2*fn))/(2*(m - n)*(n - 1))
423
+ elif argindex == 2:
424
+ return 1/(fm*fn)
425
+ elif argindex == 3:
426
+ return (elliptic_e(z, m)/(m - 1) +
427
+ elliptic_pi(n, z, m) -
428
+ m*sin(2*z)/(2*(m - 1)*fm))/(2*(n - m))
429
+ else:
430
+ n, m = self.args
431
+ if argindex == 1:
432
+ return (elliptic_e(m) + (m - n)*elliptic_k(m)/n +
433
+ (n**2 - m)*elliptic_pi(n, m)/n)/(2*(m - n)*(n - 1))
434
+ elif argindex == 2:
435
+ return (elliptic_e(m)/(m - 1) + elliptic_pi(n, m))/(2*(n - m))
436
+ raise ArgumentIndexError(self, argindex)
437
+
438
+ def _eval_rewrite_as_Integral(self, *args):
439
+ from sympy.integrals.integrals import Integral
440
+ if len(self.args) == 2:
441
+ n, m, z = self.args[0], self.args[1], pi/2
442
+ else:
443
+ n, z, m = self.args
444
+ t = Dummy('t')
445
+ return Integral(1/((1 - n*sin(t)**2)*sqrt(1 - m*sin(t)**2)), (t, 0, z))
venv/lib/python3.10/site-packages/sympy/functions/special/error_functions.py ADDED
@@ -0,0 +1,2741 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ This module contains various functions that are special cases
2
+ of incomplete gamma functions. It should probably be renamed. """
3
+
4
+ from sympy.core import EulerGamma # Must be imported from core, not core.numbers
5
+ from sympy.core.add import Add
6
+ from sympy.core.cache import cacheit
7
+ from sympy.core.function import Function, ArgumentIndexError, expand_mul
8
+ from sympy.core.numbers import I, pi, Rational
9
+ from sympy.core.relational import is_eq
10
+ from sympy.core.power import Pow
11
+ from sympy.core.singleton import S
12
+ from sympy.core.symbol import Symbol
13
+ from sympy.core.sympify import sympify
14
+ from sympy.functions.combinatorial.factorials import factorial, factorial2, RisingFactorial
15
+ from sympy.functions.elementary.complexes import polar_lift, re, unpolarify
16
+ from sympy.functions.elementary.integers import ceiling, floor
17
+ from sympy.functions.elementary.miscellaneous import sqrt, root
18
+ from sympy.functions.elementary.exponential import exp, log, exp_polar
19
+ from sympy.functions.elementary.hyperbolic import cosh, sinh
20
+ from sympy.functions.elementary.trigonometric import cos, sin, sinc
21
+ from sympy.functions.special.hyper import hyper, meijerg
22
+
23
+ # TODO series expansions
24
+ # TODO see the "Note:" in Ei
25
+
26
+ # Helper function
27
+ def real_to_real_as_real_imag(self, deep=True, **hints):
28
+ if self.args[0].is_extended_real:
29
+ if deep:
30
+ hints['complex'] = False
31
+ return (self.expand(deep, **hints), S.Zero)
32
+ else:
33
+ return (self, S.Zero)
34
+ if deep:
35
+ x, y = self.args[0].expand(deep, **hints).as_real_imag()
36
+ else:
37
+ x, y = self.args[0].as_real_imag()
38
+ re = (self.func(x + I*y) + self.func(x - I*y))/2
39
+ im = (self.func(x + I*y) - self.func(x - I*y))/(2*I)
40
+ return (re, im)
41
+
42
+
43
+ ###############################################################################
44
+ ################################ ERROR FUNCTION ###############################
45
+ ###############################################################################
46
+
47
+
48
+ class erf(Function):
49
+ r"""
50
+ The Gauss error function.
51
+
52
+ Explanation
53
+ ===========
54
+
55
+ This function is defined as:
56
+
57
+ .. math ::
58
+ \mathrm{erf}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{-t^2} \mathrm{d}t.
59
+
60
+ Examples
61
+ ========
62
+
63
+ >>> from sympy import I, oo, erf
64
+ >>> from sympy.abc import z
65
+
66
+ Several special values are known:
67
+
68
+ >>> erf(0)
69
+ 0
70
+ >>> erf(oo)
71
+ 1
72
+ >>> erf(-oo)
73
+ -1
74
+ >>> erf(I*oo)
75
+ oo*I
76
+ >>> erf(-I*oo)
77
+ -oo*I
78
+
79
+ In general one can pull out factors of -1 and $I$ from the argument:
80
+
81
+ >>> erf(-z)
82
+ -erf(z)
83
+
84
+ The error function obeys the mirror symmetry:
85
+
86
+ >>> from sympy import conjugate
87
+ >>> conjugate(erf(z))
88
+ erf(conjugate(z))
89
+
90
+ Differentiation with respect to $z$ is supported:
91
+
92
+ >>> from sympy import diff
93
+ >>> diff(erf(z), z)
94
+ 2*exp(-z**2)/sqrt(pi)
95
+
96
+ We can numerically evaluate the error function to arbitrary precision
97
+ on the whole complex plane:
98
+
99
+ >>> erf(4).evalf(30)
100
+ 0.999999984582742099719981147840
101
+
102
+ >>> erf(-4*I).evalf(30)
103
+ -1296959.73071763923152794095062*I
104
+
105
+ See Also
106
+ ========
107
+
108
+ erfc: Complementary error function.
109
+ erfi: Imaginary error function.
110
+ erf2: Two-argument error function.
111
+ erfinv: Inverse error function.
112
+ erfcinv: Inverse Complementary error function.
113
+ erf2inv: Inverse two-argument error function.
114
+
115
+ References
116
+ ==========
117
+
118
+ .. [1] https://en.wikipedia.org/wiki/Error_function
119
+ .. [2] https://dlmf.nist.gov/7
120
+ .. [3] https://mathworld.wolfram.com/Erf.html
121
+ .. [4] https://functions.wolfram.com/GammaBetaErf/Erf
122
+
123
+ """
124
+
125
+ unbranched = True
126
+
127
+ def fdiff(self, argindex=1):
128
+ if argindex == 1:
129
+ return 2*exp(-self.args[0]**2)/sqrt(pi)
130
+ else:
131
+ raise ArgumentIndexError(self, argindex)
132
+
133
+
134
+ def inverse(self, argindex=1):
135
+ """
136
+ Returns the inverse of this function.
137
+
138
+ """
139
+ return erfinv
140
+
141
+ @classmethod
142
+ def eval(cls, arg):
143
+ if arg.is_Number:
144
+ if arg is S.NaN:
145
+ return S.NaN
146
+ elif arg is S.Infinity:
147
+ return S.One
148
+ elif arg is S.NegativeInfinity:
149
+ return S.NegativeOne
150
+ elif arg.is_zero:
151
+ return S.Zero
152
+
153
+ if isinstance(arg, erfinv):
154
+ return arg.args[0]
155
+
156
+ if isinstance(arg, erfcinv):
157
+ return S.One - arg.args[0]
158
+
159
+ if arg.is_zero:
160
+ return S.Zero
161
+
162
+ # Only happens with unevaluated erf2inv
163
+ if isinstance(arg, erf2inv) and arg.args[0].is_zero:
164
+ return arg.args[1]
165
+
166
+ # Try to pull out factors of I
167
+ t = arg.extract_multiplicatively(I)
168
+ if t in (S.Infinity, S.NegativeInfinity):
169
+ return arg
170
+
171
+ # Try to pull out factors of -1
172
+ if arg.could_extract_minus_sign():
173
+ return -cls(-arg)
174
+
175
+ @staticmethod
176
+ @cacheit
177
+ def taylor_term(n, x, *previous_terms):
178
+ if n < 0 or n % 2 == 0:
179
+ return S.Zero
180
+ else:
181
+ x = sympify(x)
182
+ k = floor((n - 1)/S(2))
183
+ if len(previous_terms) > 2:
184
+ return -previous_terms[-2] * x**2 * (n - 2)/(n*k)
185
+ else:
186
+ return 2*S.NegativeOne**k * x**n/(n*factorial(k)*sqrt(pi))
187
+
188
+ def _eval_conjugate(self):
189
+ return self.func(self.args[0].conjugate())
190
+
191
+ def _eval_is_real(self):
192
+ return self.args[0].is_extended_real
193
+
194
+ def _eval_is_finite(self):
195
+ if self.args[0].is_finite:
196
+ return True
197
+ else:
198
+ return self.args[0].is_extended_real
199
+
200
+ def _eval_is_zero(self):
201
+ return self.args[0].is_zero
202
+
203
+ def _eval_rewrite_as_uppergamma(self, z, **kwargs):
204
+ from sympy.functions.special.gamma_functions import uppergamma
205
+ return sqrt(z**2)/z*(S.One - uppergamma(S.Half, z**2)/sqrt(pi))
206
+
207
+ def _eval_rewrite_as_fresnels(self, z, **kwargs):
208
+ arg = (S.One - I)*z/sqrt(pi)
209
+ return (S.One + I)*(fresnelc(arg) - I*fresnels(arg))
210
+
211
+ def _eval_rewrite_as_fresnelc(self, z, **kwargs):
212
+ arg = (S.One - I)*z/sqrt(pi)
213
+ return (S.One + I)*(fresnelc(arg) - I*fresnels(arg))
214
+
215
+ def _eval_rewrite_as_meijerg(self, z, **kwargs):
216
+ return z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)
217
+
218
+ def _eval_rewrite_as_hyper(self, z, **kwargs):
219
+ return 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], -z**2)
220
+
221
+ def _eval_rewrite_as_expint(self, z, **kwargs):
222
+ return sqrt(z**2)/z - z*expint(S.Half, z**2)/sqrt(pi)
223
+
224
+ def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
225
+ from sympy.series.limits import limit
226
+ if limitvar:
227
+ lim = limit(z, limitvar, S.Infinity)
228
+ if lim is S.NegativeInfinity:
229
+ return S.NegativeOne + _erfs(-z)*exp(-z**2)
230
+ return S.One - _erfs(z)*exp(-z**2)
231
+
232
+ def _eval_rewrite_as_erfc(self, z, **kwargs):
233
+ return S.One - erfc(z)
234
+
235
+ def _eval_rewrite_as_erfi(self, z, **kwargs):
236
+ return -I*erfi(I*z)
237
+
238
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
239
+ arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
240
+ arg0 = arg.subs(x, 0)
241
+
242
+ if arg0 is S.ComplexInfinity:
243
+ arg0 = arg.limit(x, 0, dir='-' if cdir == -1 else '+')
244
+ if x in arg.free_symbols and arg0.is_zero:
245
+ return 2*arg/sqrt(pi)
246
+ else:
247
+ return self.func(arg0)
248
+
249
+ def _eval_aseries(self, n, args0, x, logx):
250
+ from sympy.series.order import Order
251
+ point = args0[0]
252
+
253
+ if point in [S.Infinity, S.NegativeInfinity]:
254
+ z = self.args[0]
255
+
256
+ try:
257
+ _, ex = z.leadterm(x)
258
+ except (ValueError, NotImplementedError):
259
+ return self
260
+
261
+ ex = -ex # as x->1/x for aseries
262
+ if ex.is_positive:
263
+ newn = ceiling(n/ex)
264
+ s = [S.NegativeOne**k * factorial2(2*k - 1) / (z**(2*k + 1) * 2**k)
265
+ for k in range(newn)] + [Order(1/z**newn, x)]
266
+ return S.One - (exp(-z**2)/sqrt(pi)) * Add(*s)
267
+
268
+ return super(erf, self)._eval_aseries(n, args0, x, logx)
269
+
270
+ as_real_imag = real_to_real_as_real_imag
271
+
272
+
273
+ class erfc(Function):
274
+ r"""
275
+ Complementary Error Function.
276
+
277
+ Explanation
278
+ ===========
279
+
280
+ The function is defined as:
281
+
282
+ .. math ::
283
+ \mathrm{erfc}(x) = \frac{2}{\sqrt{\pi}} \int_x^\infty e^{-t^2} \mathrm{d}t
284
+
285
+ Examples
286
+ ========
287
+
288
+ >>> from sympy import I, oo, erfc
289
+ >>> from sympy.abc import z
290
+
291
+ Several special values are known:
292
+
293
+ >>> erfc(0)
294
+ 1
295
+ >>> erfc(oo)
296
+ 0
297
+ >>> erfc(-oo)
298
+ 2
299
+ >>> erfc(I*oo)
300
+ -oo*I
301
+ >>> erfc(-I*oo)
302
+ oo*I
303
+
304
+ The error function obeys the mirror symmetry:
305
+
306
+ >>> from sympy import conjugate
307
+ >>> conjugate(erfc(z))
308
+ erfc(conjugate(z))
309
+
310
+ Differentiation with respect to $z$ is supported:
311
+
312
+ >>> from sympy import diff
313
+ >>> diff(erfc(z), z)
314
+ -2*exp(-z**2)/sqrt(pi)
315
+
316
+ It also follows
317
+
318
+ >>> erfc(-z)
319
+ 2 - erfc(z)
320
+
321
+ We can numerically evaluate the complementary error function to arbitrary
322
+ precision on the whole complex plane:
323
+
324
+ >>> erfc(4).evalf(30)
325
+ 0.0000000154172579002800188521596734869
326
+
327
+ >>> erfc(4*I).evalf(30)
328
+ 1.0 - 1296959.73071763923152794095062*I
329
+
330
+ See Also
331
+ ========
332
+
333
+ erf: Gaussian error function.
334
+ erfi: Imaginary error function.
335
+ erf2: Two-argument error function.
336
+ erfinv: Inverse error function.
337
+ erfcinv: Inverse Complementary error function.
338
+ erf2inv: Inverse two-argument error function.
339
+
340
+ References
341
+ ==========
342
+
343
+ .. [1] https://en.wikipedia.org/wiki/Error_function
344
+ .. [2] https://dlmf.nist.gov/7
345
+ .. [3] https://mathworld.wolfram.com/Erfc.html
346
+ .. [4] https://functions.wolfram.com/GammaBetaErf/Erfc
347
+
348
+ """
349
+
350
+ unbranched = True
351
+
352
+ def fdiff(self, argindex=1):
353
+ if argindex == 1:
354
+ return -2*exp(-self.args[0]**2)/sqrt(pi)
355
+ else:
356
+ raise ArgumentIndexError(self, argindex)
357
+
358
+ def inverse(self, argindex=1):
359
+ """
360
+ Returns the inverse of this function.
361
+
362
+ """
363
+ return erfcinv
364
+
365
+ @classmethod
366
+ def eval(cls, arg):
367
+ if arg.is_Number:
368
+ if arg is S.NaN:
369
+ return S.NaN
370
+ elif arg is S.Infinity:
371
+ return S.Zero
372
+ elif arg.is_zero:
373
+ return S.One
374
+
375
+ if isinstance(arg, erfinv):
376
+ return S.One - arg.args[0]
377
+
378
+ if isinstance(arg, erfcinv):
379
+ return arg.args[0]
380
+
381
+ if arg.is_zero:
382
+ return S.One
383
+
384
+ # Try to pull out factors of I
385
+ t = arg.extract_multiplicatively(I)
386
+ if t in (S.Infinity, S.NegativeInfinity):
387
+ return -arg
388
+
389
+ # Try to pull out factors of -1
390
+ if arg.could_extract_minus_sign():
391
+ return 2 - cls(-arg)
392
+
393
+ @staticmethod
394
+ @cacheit
395
+ def taylor_term(n, x, *previous_terms):
396
+ if n == 0:
397
+ return S.One
398
+ elif n < 0 or n % 2 == 0:
399
+ return S.Zero
400
+ else:
401
+ x = sympify(x)
402
+ k = floor((n - 1)/S(2))
403
+ if len(previous_terms) > 2:
404
+ return -previous_terms[-2] * x**2 * (n - 2)/(n*k)
405
+ else:
406
+ return -2*S.NegativeOne**k * x**n/(n*factorial(k)*sqrt(pi))
407
+
408
+ def _eval_conjugate(self):
409
+ return self.func(self.args[0].conjugate())
410
+
411
+ def _eval_is_real(self):
412
+ return self.args[0].is_extended_real
413
+
414
+ def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
415
+ return self.rewrite(erf).rewrite("tractable", deep=True, limitvar=limitvar)
416
+
417
+ def _eval_rewrite_as_erf(self, z, **kwargs):
418
+ return S.One - erf(z)
419
+
420
+ def _eval_rewrite_as_erfi(self, z, **kwargs):
421
+ return S.One + I*erfi(I*z)
422
+
423
+ def _eval_rewrite_as_fresnels(self, z, **kwargs):
424
+ arg = (S.One - I)*z/sqrt(pi)
425
+ return S.One - (S.One + I)*(fresnelc(arg) - I*fresnels(arg))
426
+
427
+ def _eval_rewrite_as_fresnelc(self, z, **kwargs):
428
+ arg = (S.One-I)*z/sqrt(pi)
429
+ return S.One - (S.One + I)*(fresnelc(arg) - I*fresnels(arg))
430
+
431
+ def _eval_rewrite_as_meijerg(self, z, **kwargs):
432
+ return S.One - z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)
433
+
434
+ def _eval_rewrite_as_hyper(self, z, **kwargs):
435
+ return S.One - 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], -z**2)
436
+
437
+ def _eval_rewrite_as_uppergamma(self, z, **kwargs):
438
+ from sympy.functions.special.gamma_functions import uppergamma
439
+ return S.One - sqrt(z**2)/z*(S.One - uppergamma(S.Half, z**2)/sqrt(pi))
440
+
441
+ def _eval_rewrite_as_expint(self, z, **kwargs):
442
+ return S.One - sqrt(z**2)/z + z*expint(S.Half, z**2)/sqrt(pi)
443
+
444
+ def _eval_expand_func(self, **hints):
445
+ return self.rewrite(erf)
446
+
447
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
448
+ arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
449
+ arg0 = arg.subs(x, 0)
450
+
451
+ if arg0 is S.ComplexInfinity:
452
+ arg0 = arg.limit(x, 0, dir='-' if cdir == -1 else '+')
453
+ if arg0.is_zero:
454
+ return S.One
455
+ else:
456
+ return self.func(arg0)
457
+
458
+ as_real_imag = real_to_real_as_real_imag
459
+
460
+ def _eval_aseries(self, n, args0, x, logx):
461
+ return S.One - erf(*self.args)._eval_aseries(n, args0, x, logx)
462
+
463
+
464
+ class erfi(Function):
465
+ r"""
466
+ Imaginary error function.
467
+
468
+ Explanation
469
+ ===========
470
+
471
+ The function erfi is defined as:
472
+
473
+ .. math ::
474
+ \mathrm{erfi}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{t^2} \mathrm{d}t
475
+
476
+ Examples
477
+ ========
478
+
479
+ >>> from sympy import I, oo, erfi
480
+ >>> from sympy.abc import z
481
+
482
+ Several special values are known:
483
+
484
+ >>> erfi(0)
485
+ 0
486
+ >>> erfi(oo)
487
+ oo
488
+ >>> erfi(-oo)
489
+ -oo
490
+ >>> erfi(I*oo)
491
+ I
492
+ >>> erfi(-I*oo)
493
+ -I
494
+
495
+ In general one can pull out factors of -1 and $I$ from the argument:
496
+
497
+ >>> erfi(-z)
498
+ -erfi(z)
499
+
500
+ >>> from sympy import conjugate
501
+ >>> conjugate(erfi(z))
502
+ erfi(conjugate(z))
503
+
504
+ Differentiation with respect to $z$ is supported:
505
+
506
+ >>> from sympy import diff
507
+ >>> diff(erfi(z), z)
508
+ 2*exp(z**2)/sqrt(pi)
509
+
510
+ We can numerically evaluate the imaginary error function to arbitrary
511
+ precision on the whole complex plane:
512
+
513
+ >>> erfi(2).evalf(30)
514
+ 18.5648024145755525987042919132
515
+
516
+ >>> erfi(-2*I).evalf(30)
517
+ -0.995322265018952734162069256367*I
518
+
519
+ See Also
520
+ ========
521
+
522
+ erf: Gaussian error function.
523
+ erfc: Complementary error function.
524
+ erf2: Two-argument error function.
525
+ erfinv: Inverse error function.
526
+ erfcinv: Inverse Complementary error function.
527
+ erf2inv: Inverse two-argument error function.
528
+
529
+ References
530
+ ==========
531
+
532
+ .. [1] https://en.wikipedia.org/wiki/Error_function
533
+ .. [2] https://mathworld.wolfram.com/Erfi.html
534
+ .. [3] https://functions.wolfram.com/GammaBetaErf/Erfi
535
+
536
+ """
537
+
538
+ unbranched = True
539
+
540
+ def fdiff(self, argindex=1):
541
+ if argindex == 1:
542
+ return 2*exp(self.args[0]**2)/sqrt(pi)
543
+ else:
544
+ raise ArgumentIndexError(self, argindex)
545
+
546
+ @classmethod
547
+ def eval(cls, z):
548
+ if z.is_Number:
549
+ if z is S.NaN:
550
+ return S.NaN
551
+ elif z.is_zero:
552
+ return S.Zero
553
+ elif z is S.Infinity:
554
+ return S.Infinity
555
+
556
+ if z.is_zero:
557
+ return S.Zero
558
+
559
+ # Try to pull out factors of -1
560
+ if z.could_extract_minus_sign():
561
+ return -cls(-z)
562
+
563
+ # Try to pull out factors of I
564
+ nz = z.extract_multiplicatively(I)
565
+ if nz is not None:
566
+ if nz is S.Infinity:
567
+ return I
568
+ if isinstance(nz, erfinv):
569
+ return I*nz.args[0]
570
+ if isinstance(nz, erfcinv):
571
+ return I*(S.One - nz.args[0])
572
+ # Only happens with unevaluated erf2inv
573
+ if isinstance(nz, erf2inv) and nz.args[0].is_zero:
574
+ return I*nz.args[1]
575
+
576
+ @staticmethod
577
+ @cacheit
578
+ def taylor_term(n, x, *previous_terms):
579
+ if n < 0 or n % 2 == 0:
580
+ return S.Zero
581
+ else:
582
+ x = sympify(x)
583
+ k = floor((n - 1)/S(2))
584
+ if len(previous_terms) > 2:
585
+ return previous_terms[-2] * x**2 * (n - 2)/(n*k)
586
+ else:
587
+ return 2 * x**n/(n*factorial(k)*sqrt(pi))
588
+
589
+ def _eval_conjugate(self):
590
+ return self.func(self.args[0].conjugate())
591
+
592
+ def _eval_is_extended_real(self):
593
+ return self.args[0].is_extended_real
594
+
595
+ def _eval_is_zero(self):
596
+ return self.args[0].is_zero
597
+
598
+ def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
599
+ return self.rewrite(erf).rewrite("tractable", deep=True, limitvar=limitvar)
600
+
601
+ def _eval_rewrite_as_erf(self, z, **kwargs):
602
+ return -I*erf(I*z)
603
+
604
+ def _eval_rewrite_as_erfc(self, z, **kwargs):
605
+ return I*erfc(I*z) - I
606
+
607
+ def _eval_rewrite_as_fresnels(self, z, **kwargs):
608
+ arg = (S.One + I)*z/sqrt(pi)
609
+ return (S.One - I)*(fresnelc(arg) - I*fresnels(arg))
610
+
611
+ def _eval_rewrite_as_fresnelc(self, z, **kwargs):
612
+ arg = (S.One + I)*z/sqrt(pi)
613
+ return (S.One - I)*(fresnelc(arg) - I*fresnels(arg))
614
+
615
+ def _eval_rewrite_as_meijerg(self, z, **kwargs):
616
+ return z/sqrt(pi)*meijerg([S.Half], [], [0], [Rational(-1, 2)], -z**2)
617
+
618
+ def _eval_rewrite_as_hyper(self, z, **kwargs):
619
+ return 2*z/sqrt(pi)*hyper([S.Half], [3*S.Half], z**2)
620
+
621
+ def _eval_rewrite_as_uppergamma(self, z, **kwargs):
622
+ from sympy.functions.special.gamma_functions import uppergamma
623
+ return sqrt(-z**2)/z*(uppergamma(S.Half, -z**2)/sqrt(pi) - S.One)
624
+
625
+ def _eval_rewrite_as_expint(self, z, **kwargs):
626
+ return sqrt(-z**2)/z - z*expint(S.Half, -z**2)/sqrt(pi)
627
+
628
+ def _eval_expand_func(self, **hints):
629
+ return self.rewrite(erf)
630
+
631
+ as_real_imag = real_to_real_as_real_imag
632
+
633
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
634
+ arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
635
+ arg0 = arg.subs(x, 0)
636
+
637
+ if x in arg.free_symbols and arg0.is_zero:
638
+ return 2*arg/sqrt(pi)
639
+ elif arg0.is_finite:
640
+ return self.func(arg0)
641
+ return self.func(arg)
642
+
643
+ def _eval_aseries(self, n, args0, x, logx):
644
+ from sympy.series.order import Order
645
+ point = args0[0]
646
+
647
+ if point is S.Infinity:
648
+ z = self.args[0]
649
+ s = [factorial2(2*k - 1) / (2**k * z**(2*k + 1))
650
+ for k in range(n)] + [Order(1/z**n, x)]
651
+ return -I + (exp(z**2)/sqrt(pi)) * Add(*s)
652
+
653
+ return super(erfi, self)._eval_aseries(n, args0, x, logx)
654
+
655
+
656
+ class erf2(Function):
657
+ r"""
658
+ Two-argument error function.
659
+
660
+ Explanation
661
+ ===========
662
+
663
+ This function is defined as:
664
+
665
+ .. math ::
666
+ \mathrm{erf2}(x, y) = \frac{2}{\sqrt{\pi}} \int_x^y e^{-t^2} \mathrm{d}t
667
+
668
+ Examples
669
+ ========
670
+
671
+ >>> from sympy import oo, erf2
672
+ >>> from sympy.abc import x, y
673
+
674
+ Several special values are known:
675
+
676
+ >>> erf2(0, 0)
677
+ 0
678
+ >>> erf2(x, x)
679
+ 0
680
+ >>> erf2(x, oo)
681
+ 1 - erf(x)
682
+ >>> erf2(x, -oo)
683
+ -erf(x) - 1
684
+ >>> erf2(oo, y)
685
+ erf(y) - 1
686
+ >>> erf2(-oo, y)
687
+ erf(y) + 1
688
+
689
+ In general one can pull out factors of -1:
690
+
691
+ >>> erf2(-x, -y)
692
+ -erf2(x, y)
693
+
694
+ The error function obeys the mirror symmetry:
695
+
696
+ >>> from sympy import conjugate
697
+ >>> conjugate(erf2(x, y))
698
+ erf2(conjugate(x), conjugate(y))
699
+
700
+ Differentiation with respect to $x$, $y$ is supported:
701
+
702
+ >>> from sympy import diff
703
+ >>> diff(erf2(x, y), x)
704
+ -2*exp(-x**2)/sqrt(pi)
705
+ >>> diff(erf2(x, y), y)
706
+ 2*exp(-y**2)/sqrt(pi)
707
+
708
+ See Also
709
+ ========
710
+
711
+ erf: Gaussian error function.
712
+ erfc: Complementary error function.
713
+ erfi: Imaginary error function.
714
+ erfinv: Inverse error function.
715
+ erfcinv: Inverse Complementary error function.
716
+ erf2inv: Inverse two-argument error function.
717
+
718
+ References
719
+ ==========
720
+
721
+ .. [1] https://functions.wolfram.com/GammaBetaErf/Erf2/
722
+
723
+ """
724
+
725
+
726
+ def fdiff(self, argindex):
727
+ x, y = self.args
728
+ if argindex == 1:
729
+ return -2*exp(-x**2)/sqrt(pi)
730
+ elif argindex == 2:
731
+ return 2*exp(-y**2)/sqrt(pi)
732
+ else:
733
+ raise ArgumentIndexError(self, argindex)
734
+
735
+ @classmethod
736
+ def eval(cls, x, y):
737
+ chk = (S.Infinity, S.NegativeInfinity, S.Zero)
738
+ if x is S.NaN or y is S.NaN:
739
+ return S.NaN
740
+ elif x == y:
741
+ return S.Zero
742
+ elif x in chk or y in chk:
743
+ return erf(y) - erf(x)
744
+
745
+ if isinstance(y, erf2inv) and y.args[0] == x:
746
+ return y.args[1]
747
+
748
+ if x.is_zero or y.is_zero or x.is_extended_real and x.is_infinite or \
749
+ y.is_extended_real and y.is_infinite:
750
+ return erf(y) - erf(x)
751
+
752
+ #Try to pull out -1 factor
753
+ sign_x = x.could_extract_minus_sign()
754
+ sign_y = y.could_extract_minus_sign()
755
+ if (sign_x and sign_y):
756
+ return -cls(-x, -y)
757
+ elif (sign_x or sign_y):
758
+ return erf(y)-erf(x)
759
+
760
+ def _eval_conjugate(self):
761
+ return self.func(self.args[0].conjugate(), self.args[1].conjugate())
762
+
763
+ def _eval_is_extended_real(self):
764
+ return self.args[0].is_extended_real and self.args[1].is_extended_real
765
+
766
+ def _eval_rewrite_as_erf(self, x, y, **kwargs):
767
+ return erf(y) - erf(x)
768
+
769
+ def _eval_rewrite_as_erfc(self, x, y, **kwargs):
770
+ return erfc(x) - erfc(y)
771
+
772
+ def _eval_rewrite_as_erfi(self, x, y, **kwargs):
773
+ return I*(erfi(I*x)-erfi(I*y))
774
+
775
+ def _eval_rewrite_as_fresnels(self, x, y, **kwargs):
776
+ return erf(y).rewrite(fresnels) - erf(x).rewrite(fresnels)
777
+
778
+ def _eval_rewrite_as_fresnelc(self, x, y, **kwargs):
779
+ return erf(y).rewrite(fresnelc) - erf(x).rewrite(fresnelc)
780
+
781
+ def _eval_rewrite_as_meijerg(self, x, y, **kwargs):
782
+ return erf(y).rewrite(meijerg) - erf(x).rewrite(meijerg)
783
+
784
+ def _eval_rewrite_as_hyper(self, x, y, **kwargs):
785
+ return erf(y).rewrite(hyper) - erf(x).rewrite(hyper)
786
+
787
+ def _eval_rewrite_as_uppergamma(self, x, y, **kwargs):
788
+ from sympy.functions.special.gamma_functions import uppergamma
789
+ return (sqrt(y**2)/y*(S.One - uppergamma(S.Half, y**2)/sqrt(pi)) -
790
+ sqrt(x**2)/x*(S.One - uppergamma(S.Half, x**2)/sqrt(pi)))
791
+
792
+ def _eval_rewrite_as_expint(self, x, y, **kwargs):
793
+ return erf(y).rewrite(expint) - erf(x).rewrite(expint)
794
+
795
+ def _eval_expand_func(self, **hints):
796
+ return self.rewrite(erf)
797
+
798
+ def _eval_is_zero(self):
799
+ return is_eq(*self.args)
800
+
801
+ class erfinv(Function):
802
+ r"""
803
+ Inverse Error Function. The erfinv function is defined as:
804
+
805
+ .. math ::
806
+ \mathrm{erf}(x) = y \quad \Rightarrow \quad \mathrm{erfinv}(y) = x
807
+
808
+ Examples
809
+ ========
810
+
811
+ >>> from sympy import erfinv
812
+ >>> from sympy.abc import x
813
+
814
+ Several special values are known:
815
+
816
+ >>> erfinv(0)
817
+ 0
818
+ >>> erfinv(1)
819
+ oo
820
+
821
+ Differentiation with respect to $x$ is supported:
822
+
823
+ >>> from sympy import diff
824
+ >>> diff(erfinv(x), x)
825
+ sqrt(pi)*exp(erfinv(x)**2)/2
826
+
827
+ We can numerically evaluate the inverse error function to arbitrary
828
+ precision on [-1, 1]:
829
+
830
+ >>> erfinv(0.2).evalf(30)
831
+ 0.179143454621291692285822705344
832
+
833
+ See Also
834
+ ========
835
+
836
+ erf: Gaussian error function.
837
+ erfc: Complementary error function.
838
+ erfi: Imaginary error function.
839
+ erf2: Two-argument error function.
840
+ erfcinv: Inverse Complementary error function.
841
+ erf2inv: Inverse two-argument error function.
842
+
843
+ References
844
+ ==========
845
+
846
+ .. [1] https://en.wikipedia.org/wiki/Error_function#Inverse_functions
847
+ .. [2] https://functions.wolfram.com/GammaBetaErf/InverseErf/
848
+
849
+ """
850
+
851
+
852
+ def fdiff(self, argindex =1):
853
+ if argindex == 1:
854
+ return sqrt(pi)*exp(self.func(self.args[0])**2)*S.Half
855
+ else :
856
+ raise ArgumentIndexError(self, argindex)
857
+
858
+ def inverse(self, argindex=1):
859
+ """
860
+ Returns the inverse of this function.
861
+
862
+ """
863
+ return erf
864
+
865
+ @classmethod
866
+ def eval(cls, z):
867
+ if z is S.NaN:
868
+ return S.NaN
869
+ elif z is S.NegativeOne:
870
+ return S.NegativeInfinity
871
+ elif z.is_zero:
872
+ return S.Zero
873
+ elif z is S.One:
874
+ return S.Infinity
875
+
876
+ if isinstance(z, erf) and z.args[0].is_extended_real:
877
+ return z.args[0]
878
+
879
+ if z.is_zero:
880
+ return S.Zero
881
+
882
+ # Try to pull out factors of -1
883
+ nz = z.extract_multiplicatively(-1)
884
+ if nz is not None and (isinstance(nz, erf) and (nz.args[0]).is_extended_real):
885
+ return -nz.args[0]
886
+
887
+ def _eval_rewrite_as_erfcinv(self, z, **kwargs):
888
+ return erfcinv(1-z)
889
+
890
+ def _eval_is_zero(self):
891
+ return self.args[0].is_zero
892
+
893
+
894
+ class erfcinv (Function):
895
+ r"""
896
+ Inverse Complementary Error Function. The erfcinv function is defined as:
897
+
898
+ .. math ::
899
+ \mathrm{erfc}(x) = y \quad \Rightarrow \quad \mathrm{erfcinv}(y) = x
900
+
901
+ Examples
902
+ ========
903
+
904
+ >>> from sympy import erfcinv
905
+ >>> from sympy.abc import x
906
+
907
+ Several special values are known:
908
+
909
+ >>> erfcinv(1)
910
+ 0
911
+ >>> erfcinv(0)
912
+ oo
913
+
914
+ Differentiation with respect to $x$ is supported:
915
+
916
+ >>> from sympy import diff
917
+ >>> diff(erfcinv(x), x)
918
+ -sqrt(pi)*exp(erfcinv(x)**2)/2
919
+
920
+ See Also
921
+ ========
922
+
923
+ erf: Gaussian error function.
924
+ erfc: Complementary error function.
925
+ erfi: Imaginary error function.
926
+ erf2: Two-argument error function.
927
+ erfinv: Inverse error function.
928
+ erf2inv: Inverse two-argument error function.
929
+
930
+ References
931
+ ==========
932
+
933
+ .. [1] https://en.wikipedia.org/wiki/Error_function#Inverse_functions
934
+ .. [2] https://functions.wolfram.com/GammaBetaErf/InverseErfc/
935
+
936
+ """
937
+
938
+
939
+ def fdiff(self, argindex =1):
940
+ if argindex == 1:
941
+ return -sqrt(pi)*exp(self.func(self.args[0])**2)*S.Half
942
+ else:
943
+ raise ArgumentIndexError(self, argindex)
944
+
945
+ def inverse(self, argindex=1):
946
+ """
947
+ Returns the inverse of this function.
948
+
949
+ """
950
+ return erfc
951
+
952
+ @classmethod
953
+ def eval(cls, z):
954
+ if z is S.NaN:
955
+ return S.NaN
956
+ elif z.is_zero:
957
+ return S.Infinity
958
+ elif z is S.One:
959
+ return S.Zero
960
+ elif z == 2:
961
+ return S.NegativeInfinity
962
+
963
+ if z.is_zero:
964
+ return S.Infinity
965
+
966
+ def _eval_rewrite_as_erfinv(self, z, **kwargs):
967
+ return erfinv(1-z)
968
+
969
+ def _eval_is_zero(self):
970
+ return (self.args[0] - 1).is_zero
971
+
972
+ def _eval_is_infinite(self):
973
+ return self.args[0].is_zero
974
+
975
+
976
+ class erf2inv(Function):
977
+ r"""
978
+ Two-argument Inverse error function. The erf2inv function is defined as:
979
+
980
+ .. math ::
981
+ \mathrm{erf2}(x, w) = y \quad \Rightarrow \quad \mathrm{erf2inv}(x, y) = w
982
+
983
+ Examples
984
+ ========
985
+
986
+ >>> from sympy import erf2inv, oo
987
+ >>> from sympy.abc import x, y
988
+
989
+ Several special values are known:
990
+
991
+ >>> erf2inv(0, 0)
992
+ 0
993
+ >>> erf2inv(1, 0)
994
+ 1
995
+ >>> erf2inv(0, 1)
996
+ oo
997
+ >>> erf2inv(0, y)
998
+ erfinv(y)
999
+ >>> erf2inv(oo, y)
1000
+ erfcinv(-y)
1001
+
1002
+ Differentiation with respect to $x$ and $y$ is supported:
1003
+
1004
+ >>> from sympy import diff
1005
+ >>> diff(erf2inv(x, y), x)
1006
+ exp(-x**2 + erf2inv(x, y)**2)
1007
+ >>> diff(erf2inv(x, y), y)
1008
+ sqrt(pi)*exp(erf2inv(x, y)**2)/2
1009
+
1010
+ See Also
1011
+ ========
1012
+
1013
+ erf: Gaussian error function.
1014
+ erfc: Complementary error function.
1015
+ erfi: Imaginary error function.
1016
+ erf2: Two-argument error function.
1017
+ erfinv: Inverse error function.
1018
+ erfcinv: Inverse complementary error function.
1019
+
1020
+ References
1021
+ ==========
1022
+
1023
+ .. [1] https://functions.wolfram.com/GammaBetaErf/InverseErf2/
1024
+
1025
+ """
1026
+
1027
+
1028
+ def fdiff(self, argindex):
1029
+ x, y = self.args
1030
+ if argindex == 1:
1031
+ return exp(self.func(x,y)**2-x**2)
1032
+ elif argindex == 2:
1033
+ return sqrt(pi)*S.Half*exp(self.func(x,y)**2)
1034
+ else:
1035
+ raise ArgumentIndexError(self, argindex)
1036
+
1037
+ @classmethod
1038
+ def eval(cls, x, y):
1039
+ if x is S.NaN or y is S.NaN:
1040
+ return S.NaN
1041
+ elif x.is_zero and y.is_zero:
1042
+ return S.Zero
1043
+ elif x.is_zero and y is S.One:
1044
+ return S.Infinity
1045
+ elif x is S.One and y.is_zero:
1046
+ return S.One
1047
+ elif x.is_zero:
1048
+ return erfinv(y)
1049
+ elif x is S.Infinity:
1050
+ return erfcinv(-y)
1051
+ elif y.is_zero:
1052
+ return x
1053
+ elif y is S.Infinity:
1054
+ return erfinv(x)
1055
+
1056
+ if x.is_zero:
1057
+ if y.is_zero:
1058
+ return S.Zero
1059
+ else:
1060
+ return erfinv(y)
1061
+ if y.is_zero:
1062
+ return x
1063
+
1064
+ def _eval_is_zero(self):
1065
+ x, y = self.args
1066
+ if x.is_zero and y.is_zero:
1067
+ return True
1068
+
1069
+ ###############################################################################
1070
+ #################### EXPONENTIAL INTEGRALS ####################################
1071
+ ###############################################################################
1072
+
1073
+ class Ei(Function):
1074
+ r"""
1075
+ The classical exponential integral.
1076
+
1077
+ Explanation
1078
+ ===========
1079
+
1080
+ For use in SymPy, this function is defined as
1081
+
1082
+ .. math:: \operatorname{Ei}(x) = \sum_{n=1}^\infty \frac{x^n}{n\, n!}
1083
+ + \log(x) + \gamma,
1084
+
1085
+ where $\gamma$ is the Euler-Mascheroni constant.
1086
+
1087
+ If $x$ is a polar number, this defines an analytic function on the
1088
+ Riemann surface of the logarithm. Otherwise this defines an analytic
1089
+ function in the cut plane $\mathbb{C} \setminus (-\infty, 0]$.
1090
+
1091
+ **Background**
1092
+
1093
+ The name exponential integral comes from the following statement:
1094
+
1095
+ .. math:: \operatorname{Ei}(x) = \int_{-\infty}^x \frac{e^t}{t} \mathrm{d}t
1096
+
1097
+ If the integral is interpreted as a Cauchy principal value, this statement
1098
+ holds for $x > 0$ and $\operatorname{Ei}(x)$ as defined above.
1099
+
1100
+ Examples
1101
+ ========
1102
+
1103
+ >>> from sympy import Ei, polar_lift, exp_polar, I, pi
1104
+ >>> from sympy.abc import x
1105
+
1106
+ >>> Ei(-1)
1107
+ Ei(-1)
1108
+
1109
+ This yields a real value:
1110
+
1111
+ >>> Ei(-1).n(chop=True)
1112
+ -0.219383934395520
1113
+
1114
+ On the other hand the analytic continuation is not real:
1115
+
1116
+ >>> Ei(polar_lift(-1)).n(chop=True)
1117
+ -0.21938393439552 + 3.14159265358979*I
1118
+
1119
+ The exponential integral has a logarithmic branch point at the origin:
1120
+
1121
+ >>> Ei(x*exp_polar(2*I*pi))
1122
+ Ei(x) + 2*I*pi
1123
+
1124
+ Differentiation is supported:
1125
+
1126
+ >>> Ei(x).diff(x)
1127
+ exp(x)/x
1128
+
1129
+ The exponential integral is related to many other special functions.
1130
+ For example:
1131
+
1132
+ >>> from sympy import expint, Shi
1133
+ >>> Ei(x).rewrite(expint)
1134
+ -expint(1, x*exp_polar(I*pi)) - I*pi
1135
+ >>> Ei(x).rewrite(Shi)
1136
+ Chi(x) + Shi(x)
1137
+
1138
+ See Also
1139
+ ========
1140
+
1141
+ expint: Generalised exponential integral.
1142
+ E1: Special case of the generalised exponential integral.
1143
+ li: Logarithmic integral.
1144
+ Li: Offset logarithmic integral.
1145
+ Si: Sine integral.
1146
+ Ci: Cosine integral.
1147
+ Shi: Hyperbolic sine integral.
1148
+ Chi: Hyperbolic cosine integral.
1149
+ uppergamma: Upper incomplete gamma function.
1150
+
1151
+ References
1152
+ ==========
1153
+
1154
+ .. [1] https://dlmf.nist.gov/6.6
1155
+ .. [2] https://en.wikipedia.org/wiki/Exponential_integral
1156
+ .. [3] Abramowitz & Stegun, section 5: https://web.archive.org/web/20201128173312/http://people.math.sfu.ca/~cbm/aands/page_228.htm
1157
+
1158
+ """
1159
+
1160
+
1161
+ @classmethod
1162
+ def eval(cls, z):
1163
+ if z.is_zero:
1164
+ return S.NegativeInfinity
1165
+ elif z is S.Infinity:
1166
+ return S.Infinity
1167
+ elif z is S.NegativeInfinity:
1168
+ return S.Zero
1169
+
1170
+ if z.is_zero:
1171
+ return S.NegativeInfinity
1172
+
1173
+ nz, n = z.extract_branch_factor()
1174
+ if n:
1175
+ return Ei(nz) + 2*I*pi*n
1176
+
1177
+ def fdiff(self, argindex=1):
1178
+ arg = unpolarify(self.args[0])
1179
+ if argindex == 1:
1180
+ return exp(arg)/arg
1181
+ else:
1182
+ raise ArgumentIndexError(self, argindex)
1183
+
1184
+ def _eval_evalf(self, prec):
1185
+ if (self.args[0]/polar_lift(-1)).is_positive:
1186
+ return Function._eval_evalf(self, prec) + (I*pi)._eval_evalf(prec)
1187
+ return Function._eval_evalf(self, prec)
1188
+
1189
+ def _eval_rewrite_as_uppergamma(self, z, **kwargs):
1190
+ from sympy.functions.special.gamma_functions import uppergamma
1191
+ # XXX this does not currently work usefully because uppergamma
1192
+ # immediately turns into expint
1193
+ return -uppergamma(0, polar_lift(-1)*z) - I*pi
1194
+
1195
+ def _eval_rewrite_as_expint(self, z, **kwargs):
1196
+ return -expint(1, polar_lift(-1)*z) - I*pi
1197
+
1198
+ def _eval_rewrite_as_li(self, z, **kwargs):
1199
+ if isinstance(z, log):
1200
+ return li(z.args[0])
1201
+ # TODO:
1202
+ # Actually it only holds that:
1203
+ # Ei(z) = li(exp(z))
1204
+ # for -pi < imag(z) <= pi
1205
+ return li(exp(z))
1206
+
1207
+ def _eval_rewrite_as_Si(self, z, **kwargs):
1208
+ if z.is_negative:
1209
+ return Shi(z) + Chi(z) - I*pi
1210
+ else:
1211
+ return Shi(z) + Chi(z)
1212
+ _eval_rewrite_as_Ci = _eval_rewrite_as_Si
1213
+ _eval_rewrite_as_Chi = _eval_rewrite_as_Si
1214
+ _eval_rewrite_as_Shi = _eval_rewrite_as_Si
1215
+
1216
+ def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
1217
+ return exp(z) * _eis(z)
1218
+
1219
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
1220
+ from sympy import re
1221
+ x0 = self.args[0].limit(x, 0)
1222
+ arg = self.args[0].as_leading_term(x, cdir=cdir)
1223
+ cdir = arg.dir(x, cdir)
1224
+ if x0.is_zero:
1225
+ c, e = arg.as_coeff_exponent(x)
1226
+ logx = log(x) if logx is None else logx
1227
+ return log(c) + e*logx + EulerGamma - (
1228
+ I*pi if re(cdir).is_negative else S.Zero)
1229
+ return super()._eval_as_leading_term(x, logx=logx, cdir=cdir)
1230
+
1231
+ def _eval_nseries(self, x, n, logx, cdir=0):
1232
+ x0 = self.args[0].limit(x, 0)
1233
+ if x0.is_zero:
1234
+ f = self._eval_rewrite_as_Si(*self.args)
1235
+ return f._eval_nseries(x, n, logx)
1236
+ return super()._eval_nseries(x, n, logx)
1237
+
1238
+ def _eval_aseries(self, n, args0, x, logx):
1239
+ from sympy.series.order import Order
1240
+ point = args0[0]
1241
+
1242
+ if point is S.Infinity:
1243
+ z = self.args[0]
1244
+ s = [factorial(k) / (z)**k for k in range(n)] + \
1245
+ [Order(1/z**n, x)]
1246
+ return (exp(z)/z) * Add(*s)
1247
+
1248
+ return super(Ei, self)._eval_aseries(n, args0, x, logx)
1249
+
1250
+
1251
+ class expint(Function):
1252
+ r"""
1253
+ Generalized exponential integral.
1254
+
1255
+ Explanation
1256
+ ===========
1257
+
1258
+ This function is defined as
1259
+
1260
+ .. math:: \operatorname{E}_\nu(z) = z^{\nu - 1} \Gamma(1 - \nu, z),
1261
+
1262
+ where $\Gamma(1 - \nu, z)$ is the upper incomplete gamma function
1263
+ (``uppergamma``).
1264
+
1265
+ Hence for $z$ with positive real part we have
1266
+
1267
+ .. math:: \operatorname{E}_\nu(z)
1268
+ = \int_1^\infty \frac{e^{-zt}}{t^\nu} \mathrm{d}t,
1269
+
1270
+ which explains the name.
1271
+
1272
+ The representation as an incomplete gamma function provides an analytic
1273
+ continuation for $\operatorname{E}_\nu(z)$. If $\nu$ is a
1274
+ non-positive integer, the exponential integral is thus an unbranched
1275
+ function of $z$, otherwise there is a branch point at the origin.
1276
+ Refer to the incomplete gamma function documentation for details of the
1277
+ branching behavior.
1278
+
1279
+ Examples
1280
+ ========
1281
+
1282
+ >>> from sympy import expint, S
1283
+ >>> from sympy.abc import nu, z
1284
+
1285
+ Differentiation is supported. Differentiation with respect to $z$ further
1286
+ explains the name: for integral orders, the exponential integral is an
1287
+ iterated integral of the exponential function.
1288
+
1289
+ >>> expint(nu, z).diff(z)
1290
+ -expint(nu - 1, z)
1291
+
1292
+ Differentiation with respect to $\nu$ has no classical expression:
1293
+
1294
+ >>> expint(nu, z).diff(nu)
1295
+ -z**(nu - 1)*meijerg(((), (1, 1)), ((0, 0, 1 - nu), ()), z)
1296
+
1297
+ At non-postive integer orders, the exponential integral reduces to the
1298
+ exponential function:
1299
+
1300
+ >>> expint(0, z)
1301
+ exp(-z)/z
1302
+ >>> expint(-1, z)
1303
+ exp(-z)/z + exp(-z)/z**2
1304
+
1305
+ At half-integers it reduces to error functions:
1306
+
1307
+ >>> expint(S(1)/2, z)
1308
+ sqrt(pi)*erfc(sqrt(z))/sqrt(z)
1309
+
1310
+ At positive integer orders it can be rewritten in terms of exponentials
1311
+ and ``expint(1, z)``. Use ``expand_func()`` to do this:
1312
+
1313
+ >>> from sympy import expand_func
1314
+ >>> expand_func(expint(5, z))
1315
+ z**4*expint(1, z)/24 + (-z**3 + z**2 - 2*z + 6)*exp(-z)/24
1316
+
1317
+ The generalised exponential integral is essentially equivalent to the
1318
+ incomplete gamma function:
1319
+
1320
+ >>> from sympy import uppergamma
1321
+ >>> expint(nu, z).rewrite(uppergamma)
1322
+ z**(nu - 1)*uppergamma(1 - nu, z)
1323
+
1324
+ As such it is branched at the origin:
1325
+
1326
+ >>> from sympy import exp_polar, pi, I
1327
+ >>> expint(4, z*exp_polar(2*pi*I))
1328
+ I*pi*z**3/3 + expint(4, z)
1329
+ >>> expint(nu, z*exp_polar(2*pi*I))
1330
+ z**(nu - 1)*(exp(2*I*pi*nu) - 1)*gamma(1 - nu) + expint(nu, z)
1331
+
1332
+ See Also
1333
+ ========
1334
+
1335
+ Ei: Another related function called exponential integral.
1336
+ E1: The classical case, returns expint(1, z).
1337
+ li: Logarithmic integral.
1338
+ Li: Offset logarithmic integral.
1339
+ Si: Sine integral.
1340
+ Ci: Cosine integral.
1341
+ Shi: Hyperbolic sine integral.
1342
+ Chi: Hyperbolic cosine integral.
1343
+ uppergamma
1344
+
1345
+ References
1346
+ ==========
1347
+
1348
+ .. [1] https://dlmf.nist.gov/8.19
1349
+ .. [2] https://functions.wolfram.com/GammaBetaErf/ExpIntegralE/
1350
+ .. [3] https://en.wikipedia.org/wiki/Exponential_integral
1351
+
1352
+ """
1353
+
1354
+
1355
+ @classmethod
1356
+ def eval(cls, nu, z):
1357
+ from sympy.functions.special.gamma_functions import (gamma, uppergamma)
1358
+ nu2 = unpolarify(nu)
1359
+ if nu != nu2:
1360
+ return expint(nu2, z)
1361
+ if nu.is_Integer and nu <= 0 or (not nu.is_Integer and (2*nu).is_Integer):
1362
+ return unpolarify(expand_mul(z**(nu - 1)*uppergamma(1 - nu, z)))
1363
+
1364
+ # Extract branching information. This can be deduced from what is
1365
+ # explained in lowergamma.eval().
1366
+ z, n = z.extract_branch_factor()
1367
+ if n is S.Zero:
1368
+ return
1369
+ if nu.is_integer:
1370
+ if not nu > 0:
1371
+ return
1372
+ return expint(nu, z) \
1373
+ - 2*pi*I*n*S.NegativeOne**(nu - 1)/factorial(nu - 1)*unpolarify(z)**(nu - 1)
1374
+ else:
1375
+ return (exp(2*I*pi*nu*n) - 1)*z**(nu - 1)*gamma(1 - nu) + expint(nu, z)
1376
+
1377
+ def fdiff(self, argindex):
1378
+ nu, z = self.args
1379
+ if argindex == 1:
1380
+ return -z**(nu - 1)*meijerg([], [1, 1], [0, 0, 1 - nu], [], z)
1381
+ elif argindex == 2:
1382
+ return -expint(nu - 1, z)
1383
+ else:
1384
+ raise ArgumentIndexError(self, argindex)
1385
+
1386
+ def _eval_rewrite_as_uppergamma(self, nu, z, **kwargs):
1387
+ from sympy.functions.special.gamma_functions import uppergamma
1388
+ return z**(nu - 1)*uppergamma(1 - nu, z)
1389
+
1390
+ def _eval_rewrite_as_Ei(self, nu, z, **kwargs):
1391
+ if nu == 1:
1392
+ return -Ei(z*exp_polar(-I*pi)) - I*pi
1393
+ elif nu.is_Integer and nu > 1:
1394
+ # DLMF, 8.19.7
1395
+ x = -unpolarify(z)
1396
+ return x**(nu - 1)/factorial(nu - 1)*E1(z).rewrite(Ei) + \
1397
+ exp(x)/factorial(nu - 1) * \
1398
+ Add(*[factorial(nu - k - 2)*x**k for k in range(nu - 1)])
1399
+ else:
1400
+ return self
1401
+
1402
+ def _eval_expand_func(self, **hints):
1403
+ return self.rewrite(Ei).rewrite(expint, **hints)
1404
+
1405
+ def _eval_rewrite_as_Si(self, nu, z, **kwargs):
1406
+ if nu != 1:
1407
+ return self
1408
+ return Shi(z) - Chi(z)
1409
+ _eval_rewrite_as_Ci = _eval_rewrite_as_Si
1410
+ _eval_rewrite_as_Chi = _eval_rewrite_as_Si
1411
+ _eval_rewrite_as_Shi = _eval_rewrite_as_Si
1412
+
1413
+ def _eval_nseries(self, x, n, logx, cdir=0):
1414
+ if not self.args[0].has(x):
1415
+ nu = self.args[0]
1416
+ if nu == 1:
1417
+ f = self._eval_rewrite_as_Si(*self.args)
1418
+ return f._eval_nseries(x, n, logx)
1419
+ elif nu.is_Integer and nu > 1:
1420
+ f = self._eval_rewrite_as_Ei(*self.args)
1421
+ return f._eval_nseries(x, n, logx)
1422
+ return super()._eval_nseries(x, n, logx)
1423
+
1424
+ def _eval_aseries(self, n, args0, x, logx):
1425
+ from sympy.series.order import Order
1426
+ point = args0[1]
1427
+ nu = self.args[0]
1428
+
1429
+ if point is S.Infinity:
1430
+ z = self.args[1]
1431
+ s = [S.NegativeOne**k * RisingFactorial(nu, k) / z**k for k in range(n)] + [Order(1/z**n, x)]
1432
+ return (exp(-z)/z) * Add(*s)
1433
+
1434
+ return super(expint, self)._eval_aseries(n, args0, x, logx)
1435
+
1436
+
1437
+ def E1(z):
1438
+ """
1439
+ Classical case of the generalized exponential integral.
1440
+
1441
+ Explanation
1442
+ ===========
1443
+
1444
+ This is equivalent to ``expint(1, z)``.
1445
+
1446
+ Examples
1447
+ ========
1448
+
1449
+ >>> from sympy import E1
1450
+ >>> E1(0)
1451
+ expint(1, 0)
1452
+
1453
+ >>> E1(5)
1454
+ expint(1, 5)
1455
+
1456
+ See Also
1457
+ ========
1458
+
1459
+ Ei: Exponential integral.
1460
+ expint: Generalised exponential integral.
1461
+ li: Logarithmic integral.
1462
+ Li: Offset logarithmic integral.
1463
+ Si: Sine integral.
1464
+ Ci: Cosine integral.
1465
+ Shi: Hyperbolic sine integral.
1466
+ Chi: Hyperbolic cosine integral.
1467
+
1468
+ """
1469
+ return expint(1, z)
1470
+
1471
+
1472
+ class li(Function):
1473
+ r"""
1474
+ The classical logarithmic integral.
1475
+
1476
+ Explanation
1477
+ ===========
1478
+
1479
+ For use in SymPy, this function is defined as
1480
+
1481
+ .. math:: \operatorname{li}(x) = \int_0^x \frac{1}{\log(t)} \mathrm{d}t \,.
1482
+
1483
+ Examples
1484
+ ========
1485
+
1486
+ >>> from sympy import I, oo, li
1487
+ >>> from sympy.abc import z
1488
+
1489
+ Several special values are known:
1490
+
1491
+ >>> li(0)
1492
+ 0
1493
+ >>> li(1)
1494
+ -oo
1495
+ >>> li(oo)
1496
+ oo
1497
+
1498
+ Differentiation with respect to $z$ is supported:
1499
+
1500
+ >>> from sympy import diff
1501
+ >>> diff(li(z), z)
1502
+ 1/log(z)
1503
+
1504
+ Defining the ``li`` function via an integral:
1505
+ >>> from sympy import integrate
1506
+ >>> integrate(li(z))
1507
+ z*li(z) - Ei(2*log(z))
1508
+
1509
+ >>> integrate(li(z),z)
1510
+ z*li(z) - Ei(2*log(z))
1511
+
1512
+
1513
+ The logarithmic integral can also be defined in terms of ``Ei``:
1514
+
1515
+ >>> from sympy import Ei
1516
+ >>> li(z).rewrite(Ei)
1517
+ Ei(log(z))
1518
+ >>> diff(li(z).rewrite(Ei), z)
1519
+ 1/log(z)
1520
+
1521
+ We can numerically evaluate the logarithmic integral to arbitrary precision
1522
+ on the whole complex plane (except the singular points):
1523
+
1524
+ >>> li(2).evalf(30)
1525
+ 1.04516378011749278484458888919
1526
+
1527
+ >>> li(2*I).evalf(30)
1528
+ 1.0652795784357498247001125598 + 3.08346052231061726610939702133*I
1529
+
1530
+ We can even compute Soldner's constant by the help of mpmath:
1531
+
1532
+ >>> from mpmath import findroot
1533
+ >>> findroot(li, 2)
1534
+ 1.45136923488338
1535
+
1536
+ Further transformations include rewriting ``li`` in terms of
1537
+ the trigonometric integrals ``Si``, ``Ci``, ``Shi`` and ``Chi``:
1538
+
1539
+ >>> from sympy import Si, Ci, Shi, Chi
1540
+ >>> li(z).rewrite(Si)
1541
+ -log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z))
1542
+ >>> li(z).rewrite(Ci)
1543
+ -log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z))
1544
+ >>> li(z).rewrite(Shi)
1545
+ -log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z))
1546
+ >>> li(z).rewrite(Chi)
1547
+ -log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z))
1548
+
1549
+ See Also
1550
+ ========
1551
+
1552
+ Li: Offset logarithmic integral.
1553
+ Ei: Exponential integral.
1554
+ expint: Generalised exponential integral.
1555
+ E1: Special case of the generalised exponential integral.
1556
+ Si: Sine integral.
1557
+ Ci: Cosine integral.
1558
+ Shi: Hyperbolic sine integral.
1559
+ Chi: Hyperbolic cosine integral.
1560
+
1561
+ References
1562
+ ==========
1563
+
1564
+ .. [1] https://en.wikipedia.org/wiki/Logarithmic_integral
1565
+ .. [2] https://mathworld.wolfram.com/LogarithmicIntegral.html
1566
+ .. [3] https://dlmf.nist.gov/6
1567
+ .. [4] https://mathworld.wolfram.com/SoldnersConstant.html
1568
+
1569
+ """
1570
+
1571
+
1572
+ @classmethod
1573
+ def eval(cls, z):
1574
+ if z.is_zero:
1575
+ return S.Zero
1576
+ elif z is S.One:
1577
+ return S.NegativeInfinity
1578
+ elif z is S.Infinity:
1579
+ return S.Infinity
1580
+ if z.is_zero:
1581
+ return S.Zero
1582
+
1583
+ def fdiff(self, argindex=1):
1584
+ arg = self.args[0]
1585
+ if argindex == 1:
1586
+ return S.One / log(arg)
1587
+ else:
1588
+ raise ArgumentIndexError(self, argindex)
1589
+
1590
+ def _eval_conjugate(self):
1591
+ z = self.args[0]
1592
+ # Exclude values on the branch cut (-oo, 0)
1593
+ if not z.is_extended_negative:
1594
+ return self.func(z.conjugate())
1595
+
1596
+ def _eval_rewrite_as_Li(self, z, **kwargs):
1597
+ return Li(z) + li(2)
1598
+
1599
+ def _eval_rewrite_as_Ei(self, z, **kwargs):
1600
+ return Ei(log(z))
1601
+
1602
+ def _eval_rewrite_as_uppergamma(self, z, **kwargs):
1603
+ from sympy.functions.special.gamma_functions import uppergamma
1604
+ return (-uppergamma(0, -log(z)) +
1605
+ S.Half*(log(log(z)) - log(S.One/log(z))) - log(-log(z)))
1606
+
1607
+ def _eval_rewrite_as_Si(self, z, **kwargs):
1608
+ return (Ci(I*log(z)) - I*Si(I*log(z)) -
1609
+ S.Half*(log(S.One/log(z)) - log(log(z))) - log(I*log(z)))
1610
+
1611
+ _eval_rewrite_as_Ci = _eval_rewrite_as_Si
1612
+
1613
+ def _eval_rewrite_as_Shi(self, z, **kwargs):
1614
+ return (Chi(log(z)) - Shi(log(z)) - S.Half*(log(S.One/log(z)) - log(log(z))))
1615
+
1616
+ _eval_rewrite_as_Chi = _eval_rewrite_as_Shi
1617
+
1618
+ def _eval_rewrite_as_hyper(self, z, **kwargs):
1619
+ return (log(z)*hyper((1, 1), (2, 2), log(z)) +
1620
+ S.Half*(log(log(z)) - log(S.One/log(z))) + EulerGamma)
1621
+
1622
+ def _eval_rewrite_as_meijerg(self, z, **kwargs):
1623
+ return (-log(-log(z)) - S.Half*(log(S.One/log(z)) - log(log(z)))
1624
+ - meijerg(((), (1,)), ((0, 0), ()), -log(z)))
1625
+
1626
+ def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
1627
+ return z * _eis(log(z))
1628
+
1629
+ def _eval_nseries(self, x, n, logx, cdir=0):
1630
+ z = self.args[0]
1631
+ s = [(log(z))**k / (factorial(k) * k) for k in range(1, n)]
1632
+ return EulerGamma + log(log(z)) + Add(*s)
1633
+
1634
+ def _eval_is_zero(self):
1635
+ z = self.args[0]
1636
+ if z.is_zero:
1637
+ return True
1638
+
1639
+ class Li(Function):
1640
+ r"""
1641
+ The offset logarithmic integral.
1642
+
1643
+ Explanation
1644
+ ===========
1645
+
1646
+ For use in SymPy, this function is defined as
1647
+
1648
+ .. math:: \operatorname{Li}(x) = \operatorname{li}(x) - \operatorname{li}(2)
1649
+
1650
+ Examples
1651
+ ========
1652
+
1653
+ >>> from sympy import Li
1654
+ >>> from sympy.abc import z
1655
+
1656
+ The following special value is known:
1657
+
1658
+ >>> Li(2)
1659
+ 0
1660
+
1661
+ Differentiation with respect to $z$ is supported:
1662
+
1663
+ >>> from sympy import diff
1664
+ >>> diff(Li(z), z)
1665
+ 1/log(z)
1666
+
1667
+ The shifted logarithmic integral can be written in terms of $li(z)$:
1668
+
1669
+ >>> from sympy import li
1670
+ >>> Li(z).rewrite(li)
1671
+ li(z) - li(2)
1672
+
1673
+ We can numerically evaluate the logarithmic integral to arbitrary precision
1674
+ on the whole complex plane (except the singular points):
1675
+
1676
+ >>> Li(2).evalf(30)
1677
+ 0
1678
+
1679
+ >>> Li(4).evalf(30)
1680
+ 1.92242131492155809316615998938
1681
+
1682
+ See Also
1683
+ ========
1684
+
1685
+ li: Logarithmic integral.
1686
+ Ei: Exponential integral.
1687
+ expint: Generalised exponential integral.
1688
+ E1: Special case of the generalised exponential integral.
1689
+ Si: Sine integral.
1690
+ Ci: Cosine integral.
1691
+ Shi: Hyperbolic sine integral.
1692
+ Chi: Hyperbolic cosine integral.
1693
+
1694
+ References
1695
+ ==========
1696
+
1697
+ .. [1] https://en.wikipedia.org/wiki/Logarithmic_integral
1698
+ .. [2] https://mathworld.wolfram.com/LogarithmicIntegral.html
1699
+ .. [3] https://dlmf.nist.gov/6
1700
+
1701
+ """
1702
+
1703
+
1704
+ @classmethod
1705
+ def eval(cls, z):
1706
+ if z is S.Infinity:
1707
+ return S.Infinity
1708
+ elif z == S(2):
1709
+ return S.Zero
1710
+
1711
+ def fdiff(self, argindex=1):
1712
+ arg = self.args[0]
1713
+ if argindex == 1:
1714
+ return S.One / log(arg)
1715
+ else:
1716
+ raise ArgumentIndexError(self, argindex)
1717
+
1718
+ def _eval_evalf(self, prec):
1719
+ return self.rewrite(li).evalf(prec)
1720
+
1721
+ def _eval_rewrite_as_li(self, z, **kwargs):
1722
+ return li(z) - li(2)
1723
+
1724
+ def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
1725
+ return self.rewrite(li).rewrite("tractable", deep=True)
1726
+
1727
+ def _eval_nseries(self, x, n, logx, cdir=0):
1728
+ f = self._eval_rewrite_as_li(*self.args)
1729
+ return f._eval_nseries(x, n, logx)
1730
+
1731
+ ###############################################################################
1732
+ #################### TRIGONOMETRIC INTEGRALS ##################################
1733
+ ###############################################################################
1734
+
1735
+ class TrigonometricIntegral(Function):
1736
+ """ Base class for trigonometric integrals. """
1737
+
1738
+
1739
+ @classmethod
1740
+ def eval(cls, z):
1741
+ if z is S.Zero:
1742
+ return cls._atzero
1743
+ elif z is S.Infinity:
1744
+ return cls._atinf()
1745
+ elif z is S.NegativeInfinity:
1746
+ return cls._atneginf()
1747
+
1748
+ if z.is_zero:
1749
+ return cls._atzero
1750
+
1751
+ nz = z.extract_multiplicatively(polar_lift(I))
1752
+ if nz is None and cls._trigfunc(0) == 0:
1753
+ nz = z.extract_multiplicatively(I)
1754
+ if nz is not None:
1755
+ return cls._Ifactor(nz, 1)
1756
+ nz = z.extract_multiplicatively(polar_lift(-I))
1757
+ if nz is not None:
1758
+ return cls._Ifactor(nz, -1)
1759
+
1760
+ nz = z.extract_multiplicatively(polar_lift(-1))
1761
+ if nz is None and cls._trigfunc(0) == 0:
1762
+ nz = z.extract_multiplicatively(-1)
1763
+ if nz is not None:
1764
+ return cls._minusfactor(nz)
1765
+
1766
+ nz, n = z.extract_branch_factor()
1767
+ if n == 0 and nz == z:
1768
+ return
1769
+ return 2*pi*I*n*cls._trigfunc(0) + cls(nz)
1770
+
1771
+ def fdiff(self, argindex=1):
1772
+ arg = unpolarify(self.args[0])
1773
+ if argindex == 1:
1774
+ return self._trigfunc(arg)/arg
1775
+ else:
1776
+ raise ArgumentIndexError(self, argindex)
1777
+
1778
+ def _eval_rewrite_as_Ei(self, z, **kwargs):
1779
+ return self._eval_rewrite_as_expint(z).rewrite(Ei)
1780
+
1781
+ def _eval_rewrite_as_uppergamma(self, z, **kwargs):
1782
+ from sympy.functions.special.gamma_functions import uppergamma
1783
+ return self._eval_rewrite_as_expint(z).rewrite(uppergamma)
1784
+
1785
+ def _eval_nseries(self, x, n, logx, cdir=0):
1786
+ # NOTE this is fairly inefficient
1787
+ n += 1
1788
+ if self.args[0].subs(x, 0) != 0:
1789
+ return super()._eval_nseries(x, n, logx)
1790
+ baseseries = self._trigfunc(x)._eval_nseries(x, n, logx)
1791
+ if self._trigfunc(0) != 0:
1792
+ baseseries -= 1
1793
+ baseseries = baseseries.replace(Pow, lambda t, n: t**n/n, simultaneous=False)
1794
+ if self._trigfunc(0) != 0:
1795
+ baseseries += EulerGamma + log(x)
1796
+ return baseseries.subs(x, self.args[0])._eval_nseries(x, n, logx)
1797
+
1798
+
1799
+ class Si(TrigonometricIntegral):
1800
+ r"""
1801
+ Sine integral.
1802
+
1803
+ Explanation
1804
+ ===========
1805
+
1806
+ This function is defined by
1807
+
1808
+ .. math:: \operatorname{Si}(z) = \int_0^z \frac{\sin{t}}{t} \mathrm{d}t.
1809
+
1810
+ It is an entire function.
1811
+
1812
+ Examples
1813
+ ========
1814
+
1815
+ >>> from sympy import Si
1816
+ >>> from sympy.abc import z
1817
+
1818
+ The sine integral is an antiderivative of $sin(z)/z$:
1819
+
1820
+ >>> Si(z).diff(z)
1821
+ sin(z)/z
1822
+
1823
+ It is unbranched:
1824
+
1825
+ >>> from sympy import exp_polar, I, pi
1826
+ >>> Si(z*exp_polar(2*I*pi))
1827
+ Si(z)
1828
+
1829
+ Sine integral behaves much like ordinary sine under multiplication by ``I``:
1830
+
1831
+ >>> Si(I*z)
1832
+ I*Shi(z)
1833
+ >>> Si(-z)
1834
+ -Si(z)
1835
+
1836
+ It can also be expressed in terms of exponential integrals, but beware
1837
+ that the latter is branched:
1838
+
1839
+ >>> from sympy import expint
1840
+ >>> Si(z).rewrite(expint)
1841
+ -I*(-expint(1, z*exp_polar(-I*pi/2))/2 +
1842
+ expint(1, z*exp_polar(I*pi/2))/2) + pi/2
1843
+
1844
+ It can be rewritten in the form of sinc function (by definition):
1845
+
1846
+ >>> from sympy import sinc
1847
+ >>> Si(z).rewrite(sinc)
1848
+ Integral(sinc(t), (t, 0, z))
1849
+
1850
+ See Also
1851
+ ========
1852
+
1853
+ Ci: Cosine integral.
1854
+ Shi: Hyperbolic sine integral.
1855
+ Chi: Hyperbolic cosine integral.
1856
+ Ei: Exponential integral.
1857
+ expint: Generalised exponential integral.
1858
+ sinc: unnormalized sinc function
1859
+ E1: Special case of the generalised exponential integral.
1860
+ li: Logarithmic integral.
1861
+ Li: Offset logarithmic integral.
1862
+
1863
+ References
1864
+ ==========
1865
+
1866
+ .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral
1867
+
1868
+ """
1869
+
1870
+ _trigfunc = sin
1871
+ _atzero = S.Zero
1872
+
1873
+ @classmethod
1874
+ def _atinf(cls):
1875
+ return pi*S.Half
1876
+
1877
+ @classmethod
1878
+ def _atneginf(cls):
1879
+ return -pi*S.Half
1880
+
1881
+ @classmethod
1882
+ def _minusfactor(cls, z):
1883
+ return -Si(z)
1884
+
1885
+ @classmethod
1886
+ def _Ifactor(cls, z, sign):
1887
+ return I*Shi(z)*sign
1888
+
1889
+ def _eval_rewrite_as_expint(self, z, **kwargs):
1890
+ # XXX should we polarify z?
1891
+ return pi/2 + (E1(polar_lift(I)*z) - E1(polar_lift(-I)*z))/2/I
1892
+
1893
+ def _eval_rewrite_as_sinc(self, z, **kwargs):
1894
+ from sympy.integrals.integrals import Integral
1895
+ t = Symbol('t', Dummy=True)
1896
+ return Integral(sinc(t), (t, 0, z))
1897
+
1898
+ def _eval_aseries(self, n, args0, x, logx):
1899
+ from sympy.series.order import Order
1900
+ point = args0[0]
1901
+
1902
+ # Expansion at oo
1903
+ if point is S.Infinity:
1904
+ z = self.args[0]
1905
+ p = [S.NegativeOne**k * factorial(2*k) / z**(2*k)
1906
+ for k in range(int((n - 1)/2))] + [Order(1/z**n, x)]
1907
+ q = [S.NegativeOne**k * factorial(2*k + 1) / z**(2*k + 1)
1908
+ for k in range(int(n/2) - 1)] + [Order(1/z**n, x)]
1909
+ return pi/2 - (cos(z)/z)*Add(*p) - (sin(z)/z)*Add(*q)
1910
+
1911
+ # All other points are not handled
1912
+ return super(Si, self)._eval_aseries(n, args0, x, logx)
1913
+
1914
+ def _eval_is_zero(self):
1915
+ z = self.args[0]
1916
+ if z.is_zero:
1917
+ return True
1918
+
1919
+
1920
+ class Ci(TrigonometricIntegral):
1921
+ r"""
1922
+ Cosine integral.
1923
+
1924
+ Explanation
1925
+ ===========
1926
+
1927
+ This function is defined for positive $x$ by
1928
+
1929
+ .. math:: \operatorname{Ci}(x) = \gamma + \log{x}
1930
+ + \int_0^x \frac{\cos{t} - 1}{t} \mathrm{d}t
1931
+ = -\int_x^\infty \frac{\cos{t}}{t} \mathrm{d}t,
1932
+
1933
+ where $\gamma$ is the Euler-Mascheroni constant.
1934
+
1935
+ We have
1936
+
1937
+ .. math:: \operatorname{Ci}(z) =
1938
+ -\frac{\operatorname{E}_1\left(e^{i\pi/2} z\right)
1939
+ + \operatorname{E}_1\left(e^{-i \pi/2} z\right)}{2}
1940
+
1941
+ which holds for all polar $z$ and thus provides an analytic
1942
+ continuation to the Riemann surface of the logarithm.
1943
+
1944
+ The formula also holds as stated
1945
+ for $z \in \mathbb{C}$ with $\Re(z) > 0$.
1946
+ By lifting to the principal branch, we obtain an analytic function on the
1947
+ cut complex plane.
1948
+
1949
+ Examples
1950
+ ========
1951
+
1952
+ >>> from sympy import Ci
1953
+ >>> from sympy.abc import z
1954
+
1955
+ The cosine integral is a primitive of $\cos(z)/z$:
1956
+
1957
+ >>> Ci(z).diff(z)
1958
+ cos(z)/z
1959
+
1960
+ It has a logarithmic branch point at the origin:
1961
+
1962
+ >>> from sympy import exp_polar, I, pi
1963
+ >>> Ci(z*exp_polar(2*I*pi))
1964
+ Ci(z) + 2*I*pi
1965
+
1966
+ The cosine integral behaves somewhat like ordinary $\cos$ under
1967
+ multiplication by $i$:
1968
+
1969
+ >>> from sympy import polar_lift
1970
+ >>> Ci(polar_lift(I)*z)
1971
+ Chi(z) + I*pi/2
1972
+ >>> Ci(polar_lift(-1)*z)
1973
+ Ci(z) + I*pi
1974
+
1975
+ It can also be expressed in terms of exponential integrals:
1976
+
1977
+ >>> from sympy import expint
1978
+ >>> Ci(z).rewrite(expint)
1979
+ -expint(1, z*exp_polar(-I*pi/2))/2 - expint(1, z*exp_polar(I*pi/2))/2
1980
+
1981
+ See Also
1982
+ ========
1983
+
1984
+ Si: Sine integral.
1985
+ Shi: Hyperbolic sine integral.
1986
+ Chi: Hyperbolic cosine integral.
1987
+ Ei: Exponential integral.
1988
+ expint: Generalised exponential integral.
1989
+ E1: Special case of the generalised exponential integral.
1990
+ li: Logarithmic integral.
1991
+ Li: Offset logarithmic integral.
1992
+
1993
+ References
1994
+ ==========
1995
+
1996
+ .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral
1997
+
1998
+ """
1999
+
2000
+ _trigfunc = cos
2001
+ _atzero = S.ComplexInfinity
2002
+
2003
+ @classmethod
2004
+ def _atinf(cls):
2005
+ return S.Zero
2006
+
2007
+ @classmethod
2008
+ def _atneginf(cls):
2009
+ return I*pi
2010
+
2011
+ @classmethod
2012
+ def _minusfactor(cls, z):
2013
+ return Ci(z) + I*pi
2014
+
2015
+ @classmethod
2016
+ def _Ifactor(cls, z, sign):
2017
+ return Chi(z) + I*pi/2*sign
2018
+
2019
+ def _eval_rewrite_as_expint(self, z, **kwargs):
2020
+ return -(E1(polar_lift(I)*z) + E1(polar_lift(-I)*z))/2
2021
+
2022
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
2023
+ arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
2024
+ arg0 = arg.subs(x, 0)
2025
+
2026
+ if arg0 is S.NaN:
2027
+ arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
2028
+ if arg0.is_zero:
2029
+ c, e = arg.as_coeff_exponent(x)
2030
+ logx = log(x) if logx is None else logx
2031
+ return log(c) + e*logx + EulerGamma
2032
+ elif arg0.is_finite:
2033
+ return self.func(arg0)
2034
+ else:
2035
+ return self
2036
+
2037
+ def _eval_aseries(self, n, args0, x, logx):
2038
+ from sympy.series.order import Order
2039
+ point = args0[0]
2040
+
2041
+ # Expansion at oo
2042
+ if point is S.Infinity:
2043
+ z = self.args[0]
2044
+ p = [S.NegativeOne**k * factorial(2*k) / z**(2*k)
2045
+ for k in range(int((n - 1)/2))] + [Order(1/z**n, x)]
2046
+ q = [S.NegativeOne**k * factorial(2*k + 1) / z**(2*k + 1)
2047
+ for k in range(int(n/2) - 1)] + [Order(1/z**n, x)]
2048
+ return (sin(z)/z)*Add(*p) - (cos(z)/z)*Add(*q)
2049
+
2050
+ # All other points are not handled
2051
+ return super(Ci, self)._eval_aseries(n, args0, x, logx)
2052
+
2053
+
2054
+ class Shi(TrigonometricIntegral):
2055
+ r"""
2056
+ Sinh integral.
2057
+
2058
+ Explanation
2059
+ ===========
2060
+
2061
+ This function is defined by
2062
+
2063
+ .. math:: \operatorname{Shi}(z) = \int_0^z \frac{\sinh{t}}{t} \mathrm{d}t.
2064
+
2065
+ It is an entire function.
2066
+
2067
+ Examples
2068
+ ========
2069
+
2070
+ >>> from sympy import Shi
2071
+ >>> from sympy.abc import z
2072
+
2073
+ The Sinh integral is a primitive of $\sinh(z)/z$:
2074
+
2075
+ >>> Shi(z).diff(z)
2076
+ sinh(z)/z
2077
+
2078
+ It is unbranched:
2079
+
2080
+ >>> from sympy import exp_polar, I, pi
2081
+ >>> Shi(z*exp_polar(2*I*pi))
2082
+ Shi(z)
2083
+
2084
+ The $\sinh$ integral behaves much like ordinary $\sinh$ under
2085
+ multiplication by $i$:
2086
+
2087
+ >>> Shi(I*z)
2088
+ I*Si(z)
2089
+ >>> Shi(-z)
2090
+ -Shi(z)
2091
+
2092
+ It can also be expressed in terms of exponential integrals, but beware
2093
+ that the latter is branched:
2094
+
2095
+ >>> from sympy import expint
2096
+ >>> Shi(z).rewrite(expint)
2097
+ expint(1, z)/2 - expint(1, z*exp_polar(I*pi))/2 - I*pi/2
2098
+
2099
+ See Also
2100
+ ========
2101
+
2102
+ Si: Sine integral.
2103
+ Ci: Cosine integral.
2104
+ Chi: Hyperbolic cosine integral.
2105
+ Ei: Exponential integral.
2106
+ expint: Generalised exponential integral.
2107
+ E1: Special case of the generalised exponential integral.
2108
+ li: Logarithmic integral.
2109
+ Li: Offset logarithmic integral.
2110
+
2111
+ References
2112
+ ==========
2113
+
2114
+ .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral
2115
+
2116
+ """
2117
+
2118
+ _trigfunc = sinh
2119
+ _atzero = S.Zero
2120
+
2121
+ @classmethod
2122
+ def _atinf(cls):
2123
+ return S.Infinity
2124
+
2125
+ @classmethod
2126
+ def _atneginf(cls):
2127
+ return S.NegativeInfinity
2128
+
2129
+ @classmethod
2130
+ def _minusfactor(cls, z):
2131
+ return -Shi(z)
2132
+
2133
+ @classmethod
2134
+ def _Ifactor(cls, z, sign):
2135
+ return I*Si(z)*sign
2136
+
2137
+ def _eval_rewrite_as_expint(self, z, **kwargs):
2138
+ # XXX should we polarify z?
2139
+ return (E1(z) - E1(exp_polar(I*pi)*z))/2 - I*pi/2
2140
+
2141
+ def _eval_is_zero(self):
2142
+ z = self.args[0]
2143
+ if z.is_zero:
2144
+ return True
2145
+
2146
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
2147
+ arg = self.args[0].as_leading_term(x)
2148
+ arg0 = arg.subs(x, 0)
2149
+
2150
+ if arg0 is S.NaN:
2151
+ arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
2152
+ if arg0.is_zero:
2153
+ return arg
2154
+ elif not arg0.is_infinite:
2155
+ return self.func(arg0)
2156
+ else:
2157
+ return self
2158
+
2159
+
2160
+ class Chi(TrigonometricIntegral):
2161
+ r"""
2162
+ Cosh integral.
2163
+
2164
+ Explanation
2165
+ ===========
2166
+
2167
+ This function is defined for positive $x$ by
2168
+
2169
+ .. math:: \operatorname{Chi}(x) = \gamma + \log{x}
2170
+ + \int_0^x \frac{\cosh{t} - 1}{t} \mathrm{d}t,
2171
+
2172
+ where $\gamma$ is the Euler-Mascheroni constant.
2173
+
2174
+ We have
2175
+
2176
+ .. math:: \operatorname{Chi}(z) = \operatorname{Ci}\left(e^{i \pi/2}z\right)
2177
+ - i\frac{\pi}{2},
2178
+
2179
+ which holds for all polar $z$ and thus provides an analytic
2180
+ continuation to the Riemann surface of the logarithm.
2181
+ By lifting to the principal branch we obtain an analytic function on the
2182
+ cut complex plane.
2183
+
2184
+ Examples
2185
+ ========
2186
+
2187
+ >>> from sympy import Chi
2188
+ >>> from sympy.abc import z
2189
+
2190
+ The $\cosh$ integral is a primitive of $\cosh(z)/z$:
2191
+
2192
+ >>> Chi(z).diff(z)
2193
+ cosh(z)/z
2194
+
2195
+ It has a logarithmic branch point at the origin:
2196
+
2197
+ >>> from sympy import exp_polar, I, pi
2198
+ >>> Chi(z*exp_polar(2*I*pi))
2199
+ Chi(z) + 2*I*pi
2200
+
2201
+ The $\cosh$ integral behaves somewhat like ordinary $\cosh$ under
2202
+ multiplication by $i$:
2203
+
2204
+ >>> from sympy import polar_lift
2205
+ >>> Chi(polar_lift(I)*z)
2206
+ Ci(z) + I*pi/2
2207
+ >>> Chi(polar_lift(-1)*z)
2208
+ Chi(z) + I*pi
2209
+
2210
+ It can also be expressed in terms of exponential integrals:
2211
+
2212
+ >>> from sympy import expint
2213
+ >>> Chi(z).rewrite(expint)
2214
+ -expint(1, z)/2 - expint(1, z*exp_polar(I*pi))/2 - I*pi/2
2215
+
2216
+ See Also
2217
+ ========
2218
+
2219
+ Si: Sine integral.
2220
+ Ci: Cosine integral.
2221
+ Shi: Hyperbolic sine integral.
2222
+ Ei: Exponential integral.
2223
+ expint: Generalised exponential integral.
2224
+ E1: Special case of the generalised exponential integral.
2225
+ li: Logarithmic integral.
2226
+ Li: Offset logarithmic integral.
2227
+
2228
+ References
2229
+ ==========
2230
+
2231
+ .. [1] https://en.wikipedia.org/wiki/Trigonometric_integral
2232
+
2233
+ """
2234
+
2235
+ _trigfunc = cosh
2236
+ _atzero = S.ComplexInfinity
2237
+
2238
+ @classmethod
2239
+ def _atinf(cls):
2240
+ return S.Infinity
2241
+
2242
+ @classmethod
2243
+ def _atneginf(cls):
2244
+ return S.Infinity
2245
+
2246
+ @classmethod
2247
+ def _minusfactor(cls, z):
2248
+ return Chi(z) + I*pi
2249
+
2250
+ @classmethod
2251
+ def _Ifactor(cls, z, sign):
2252
+ return Ci(z) + I*pi/2*sign
2253
+
2254
+ def _eval_rewrite_as_expint(self, z, **kwargs):
2255
+ return -I*pi/2 - (E1(z) + E1(exp_polar(I*pi)*z))/2
2256
+
2257
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
2258
+ arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
2259
+ arg0 = arg.subs(x, 0)
2260
+
2261
+ if arg0 is S.NaN:
2262
+ arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
2263
+ if arg0.is_zero:
2264
+ c, e = arg.as_coeff_exponent(x)
2265
+ logx = log(x) if logx is None else logx
2266
+ return log(c) + e*logx + EulerGamma
2267
+ elif arg0.is_finite:
2268
+ return self.func(arg0)
2269
+ else:
2270
+ return self
2271
+
2272
+
2273
+ ###############################################################################
2274
+ #################### FRESNEL INTEGRALS ########################################
2275
+ ###############################################################################
2276
+
2277
+ class FresnelIntegral(Function):
2278
+ """ Base class for the Fresnel integrals."""
2279
+
2280
+ unbranched = True
2281
+
2282
+ @classmethod
2283
+ def eval(cls, z):
2284
+ # Values at positive infinities signs
2285
+ # if any were extracted automatically
2286
+ if z is S.Infinity:
2287
+ return S.Half
2288
+
2289
+ # Value at zero
2290
+ if z.is_zero:
2291
+ return S.Zero
2292
+
2293
+ # Try to pull out factors of -1 and I
2294
+ prefact = S.One
2295
+ newarg = z
2296
+ changed = False
2297
+
2298
+ nz = newarg.extract_multiplicatively(-1)
2299
+ if nz is not None:
2300
+ prefact = -prefact
2301
+ newarg = nz
2302
+ changed = True
2303
+
2304
+ nz = newarg.extract_multiplicatively(I)
2305
+ if nz is not None:
2306
+ prefact = cls._sign*I*prefact
2307
+ newarg = nz
2308
+ changed = True
2309
+
2310
+ if changed:
2311
+ return prefact*cls(newarg)
2312
+
2313
+ def fdiff(self, argindex=1):
2314
+ if argindex == 1:
2315
+ return self._trigfunc(S.Half*pi*self.args[0]**2)
2316
+ else:
2317
+ raise ArgumentIndexError(self, argindex)
2318
+
2319
+ def _eval_is_extended_real(self):
2320
+ return self.args[0].is_extended_real
2321
+
2322
+ _eval_is_finite = _eval_is_extended_real
2323
+
2324
+ def _eval_is_zero(self):
2325
+ return self.args[0].is_zero
2326
+
2327
+ def _eval_conjugate(self):
2328
+ return self.func(self.args[0].conjugate())
2329
+
2330
+ as_real_imag = real_to_real_as_real_imag
2331
+
2332
+
2333
+ class fresnels(FresnelIntegral):
2334
+ r"""
2335
+ Fresnel integral S.
2336
+
2337
+ Explanation
2338
+ ===========
2339
+
2340
+ This function is defined by
2341
+
2342
+ .. math:: \operatorname{S}(z) = \int_0^z \sin{\frac{\pi}{2} t^2} \mathrm{d}t.
2343
+
2344
+ It is an entire function.
2345
+
2346
+ Examples
2347
+ ========
2348
+
2349
+ >>> from sympy import I, oo, fresnels
2350
+ >>> from sympy.abc import z
2351
+
2352
+ Several special values are known:
2353
+
2354
+ >>> fresnels(0)
2355
+ 0
2356
+ >>> fresnels(oo)
2357
+ 1/2
2358
+ >>> fresnels(-oo)
2359
+ -1/2
2360
+ >>> fresnels(I*oo)
2361
+ -I/2
2362
+ >>> fresnels(-I*oo)
2363
+ I/2
2364
+
2365
+ In general one can pull out factors of -1 and $i$ from the argument:
2366
+
2367
+ >>> fresnels(-z)
2368
+ -fresnels(z)
2369
+ >>> fresnels(I*z)
2370
+ -I*fresnels(z)
2371
+
2372
+ The Fresnel S integral obeys the mirror symmetry
2373
+ $\overline{S(z)} = S(\bar{z})$:
2374
+
2375
+ >>> from sympy import conjugate
2376
+ >>> conjugate(fresnels(z))
2377
+ fresnels(conjugate(z))
2378
+
2379
+ Differentiation with respect to $z$ is supported:
2380
+
2381
+ >>> from sympy import diff
2382
+ >>> diff(fresnels(z), z)
2383
+ sin(pi*z**2/2)
2384
+
2385
+ Defining the Fresnel functions via an integral:
2386
+
2387
+ >>> from sympy import integrate, pi, sin, expand_func
2388
+ >>> integrate(sin(pi*z**2/2), z)
2389
+ 3*fresnels(z)*gamma(3/4)/(4*gamma(7/4))
2390
+ >>> expand_func(integrate(sin(pi*z**2/2), z))
2391
+ fresnels(z)
2392
+
2393
+ We can numerically evaluate the Fresnel integral to arbitrary precision
2394
+ on the whole complex plane:
2395
+
2396
+ >>> fresnels(2).evalf(30)
2397
+ 0.343415678363698242195300815958
2398
+
2399
+ >>> fresnels(-2*I).evalf(30)
2400
+ 0.343415678363698242195300815958*I
2401
+
2402
+ See Also
2403
+ ========
2404
+
2405
+ fresnelc: Fresnel cosine integral.
2406
+
2407
+ References
2408
+ ==========
2409
+
2410
+ .. [1] https://en.wikipedia.org/wiki/Fresnel_integral
2411
+ .. [2] https://dlmf.nist.gov/7
2412
+ .. [3] https://mathworld.wolfram.com/FresnelIntegrals.html
2413
+ .. [4] https://functions.wolfram.com/GammaBetaErf/FresnelS
2414
+ .. [5] The converging factors for the fresnel integrals
2415
+ by John W. Wrench Jr. and Vicki Alley
2416
+
2417
+ """
2418
+ _trigfunc = sin
2419
+ _sign = -S.One
2420
+
2421
+ @staticmethod
2422
+ @cacheit
2423
+ def taylor_term(n, x, *previous_terms):
2424
+ if n < 0:
2425
+ return S.Zero
2426
+ else:
2427
+ x = sympify(x)
2428
+ if len(previous_terms) > 1:
2429
+ p = previous_terms[-1]
2430
+ return (-pi**2*x**4*(4*n - 1)/(8*n*(2*n + 1)*(4*n + 3))) * p
2431
+ else:
2432
+ return x**3 * (-x**4)**n * (S(2)**(-2*n - 1)*pi**(2*n + 1)) / ((4*n + 3)*factorial(2*n + 1))
2433
+
2434
+ def _eval_rewrite_as_erf(self, z, **kwargs):
2435
+ return (S.One + I)/4 * (erf((S.One + I)/2*sqrt(pi)*z) - I*erf((S.One - I)/2*sqrt(pi)*z))
2436
+
2437
+ def _eval_rewrite_as_hyper(self, z, **kwargs):
2438
+ return pi*z**3/6 * hyper([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)], -pi**2*z**4/16)
2439
+
2440
+ def _eval_rewrite_as_meijerg(self, z, **kwargs):
2441
+ return (pi*z**Rational(9, 4) / (sqrt(2)*(z**2)**Rational(3, 4)*(-z)**Rational(3, 4))
2442
+ * meijerg([], [1], [Rational(3, 4)], [Rational(1, 4), 0], -pi**2*z**4/16))
2443
+
2444
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
2445
+ from sympy.series.order import Order
2446
+ arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
2447
+ arg0 = arg.subs(x, 0)
2448
+
2449
+ if arg0 is S.ComplexInfinity:
2450
+ arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
2451
+ if arg0.is_zero:
2452
+ return pi*arg**3/6
2453
+ elif arg0 in [S.Infinity, S.NegativeInfinity]:
2454
+ s = 1 if arg0 is S.Infinity else -1
2455
+ return s*S.Half + Order(x, x)
2456
+ else:
2457
+ return self.func(arg0)
2458
+
2459
+ def _eval_aseries(self, n, args0, x, logx):
2460
+ from sympy.series.order import Order
2461
+ point = args0[0]
2462
+
2463
+ # Expansion at oo and -oo
2464
+ if point in [S.Infinity, -S.Infinity]:
2465
+ z = self.args[0]
2466
+
2467
+ # expansion of S(x) = S1(x*sqrt(pi/2)), see reference[5] page 1-8
2468
+ # as only real infinities are dealt with, sin and cos are O(1)
2469
+ p = [S.NegativeOne**k * factorial(4*k + 1) /
2470
+ (2**(2*k + 2) * z**(4*k + 3) * 2**(2*k)*factorial(2*k))
2471
+ for k in range(0, n) if 4*k + 3 < n]
2472
+ q = [1/(2*z)] + [S.NegativeOne**k * factorial(4*k - 1) /
2473
+ (2**(2*k + 1) * z**(4*k + 1) * 2**(2*k - 1)*factorial(2*k - 1))
2474
+ for k in range(1, n) if 4*k + 1 < n]
2475
+
2476
+ p = [-sqrt(2/pi)*t for t in p]
2477
+ q = [-sqrt(2/pi)*t for t in q]
2478
+ s = 1 if point is S.Infinity else -1
2479
+ # The expansion at oo is 1/2 + some odd powers of z
2480
+ # To get the expansion at -oo, replace z by -z and flip the sign
2481
+ # The result -1/2 + the same odd powers of z as before.
2482
+ return s*S.Half + (sin(z**2)*Add(*p) + cos(z**2)*Add(*q)
2483
+ ).subs(x, sqrt(2/pi)*x) + Order(1/z**n, x)
2484
+
2485
+ # All other points are not handled
2486
+ return super()._eval_aseries(n, args0, x, logx)
2487
+
2488
+
2489
+ class fresnelc(FresnelIntegral):
2490
+ r"""
2491
+ Fresnel integral C.
2492
+
2493
+ Explanation
2494
+ ===========
2495
+
2496
+ This function is defined by
2497
+
2498
+ .. math:: \operatorname{C}(z) = \int_0^z \cos{\frac{\pi}{2} t^2} \mathrm{d}t.
2499
+
2500
+ It is an entire function.
2501
+
2502
+ Examples
2503
+ ========
2504
+
2505
+ >>> from sympy import I, oo, fresnelc
2506
+ >>> from sympy.abc import z
2507
+
2508
+ Several special values are known:
2509
+
2510
+ >>> fresnelc(0)
2511
+ 0
2512
+ >>> fresnelc(oo)
2513
+ 1/2
2514
+ >>> fresnelc(-oo)
2515
+ -1/2
2516
+ >>> fresnelc(I*oo)
2517
+ I/2
2518
+ >>> fresnelc(-I*oo)
2519
+ -I/2
2520
+
2521
+ In general one can pull out factors of -1 and $i$ from the argument:
2522
+
2523
+ >>> fresnelc(-z)
2524
+ -fresnelc(z)
2525
+ >>> fresnelc(I*z)
2526
+ I*fresnelc(z)
2527
+
2528
+ The Fresnel C integral obeys the mirror symmetry
2529
+ $\overline{C(z)} = C(\bar{z})$:
2530
+
2531
+ >>> from sympy import conjugate
2532
+ >>> conjugate(fresnelc(z))
2533
+ fresnelc(conjugate(z))
2534
+
2535
+ Differentiation with respect to $z$ is supported:
2536
+
2537
+ >>> from sympy import diff
2538
+ >>> diff(fresnelc(z), z)
2539
+ cos(pi*z**2/2)
2540
+
2541
+ Defining the Fresnel functions via an integral:
2542
+
2543
+ >>> from sympy import integrate, pi, cos, expand_func
2544
+ >>> integrate(cos(pi*z**2/2), z)
2545
+ fresnelc(z)*gamma(1/4)/(4*gamma(5/4))
2546
+ >>> expand_func(integrate(cos(pi*z**2/2), z))
2547
+ fresnelc(z)
2548
+
2549
+ We can numerically evaluate the Fresnel integral to arbitrary precision
2550
+ on the whole complex plane:
2551
+
2552
+ >>> fresnelc(2).evalf(30)
2553
+ 0.488253406075340754500223503357
2554
+
2555
+ >>> fresnelc(-2*I).evalf(30)
2556
+ -0.488253406075340754500223503357*I
2557
+
2558
+ See Also
2559
+ ========
2560
+
2561
+ fresnels: Fresnel sine integral.
2562
+
2563
+ References
2564
+ ==========
2565
+
2566
+ .. [1] https://en.wikipedia.org/wiki/Fresnel_integral
2567
+ .. [2] https://dlmf.nist.gov/7
2568
+ .. [3] https://mathworld.wolfram.com/FresnelIntegrals.html
2569
+ .. [4] https://functions.wolfram.com/GammaBetaErf/FresnelC
2570
+ .. [5] The converging factors for the fresnel integrals
2571
+ by John W. Wrench Jr. and Vicki Alley
2572
+
2573
+ """
2574
+ _trigfunc = cos
2575
+ _sign = S.One
2576
+
2577
+ @staticmethod
2578
+ @cacheit
2579
+ def taylor_term(n, x, *previous_terms):
2580
+ if n < 0:
2581
+ return S.Zero
2582
+ else:
2583
+ x = sympify(x)
2584
+ if len(previous_terms) > 1:
2585
+ p = previous_terms[-1]
2586
+ return (-pi**2*x**4*(4*n - 3)/(8*n*(2*n - 1)*(4*n + 1))) * p
2587
+ else:
2588
+ return x * (-x**4)**n * (S(2)**(-2*n)*pi**(2*n)) / ((4*n + 1)*factorial(2*n))
2589
+
2590
+ def _eval_rewrite_as_erf(self, z, **kwargs):
2591
+ return (S.One - I)/4 * (erf((S.One + I)/2*sqrt(pi)*z) + I*erf((S.One - I)/2*sqrt(pi)*z))
2592
+
2593
+ def _eval_rewrite_as_hyper(self, z, **kwargs):
2594
+ return z * hyper([Rational(1, 4)], [S.Half, Rational(5, 4)], -pi**2*z**4/16)
2595
+
2596
+ def _eval_rewrite_as_meijerg(self, z, **kwargs):
2597
+ return (pi*z**Rational(3, 4) / (sqrt(2)*root(z**2, 4)*root(-z, 4))
2598
+ * meijerg([], [1], [Rational(1, 4)], [Rational(3, 4), 0], -pi**2*z**4/16))
2599
+
2600
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
2601
+ from sympy.series.order import Order
2602
+ arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
2603
+ arg0 = arg.subs(x, 0)
2604
+
2605
+ if arg0 is S.ComplexInfinity:
2606
+ arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
2607
+ if arg0.is_zero:
2608
+ return arg
2609
+ elif arg0 in [S.Infinity, S.NegativeInfinity]:
2610
+ s = 1 if arg0 is S.Infinity else -1
2611
+ return s*S.Half + Order(x, x)
2612
+ else:
2613
+ return self.func(arg0)
2614
+
2615
+ def _eval_aseries(self, n, args0, x, logx):
2616
+ from sympy.series.order import Order
2617
+ point = args0[0]
2618
+
2619
+ # Expansion at oo
2620
+ if point in [S.Infinity, -S.Infinity]:
2621
+ z = self.args[0]
2622
+
2623
+ # expansion of C(x) = C1(x*sqrt(pi/2)), see reference[5] page 1-8
2624
+ # as only real infinities are dealt with, sin and cos are O(1)
2625
+ p = [S.NegativeOne**k * factorial(4*k + 1) /
2626
+ (2**(2*k + 2) * z**(4*k + 3) * 2**(2*k)*factorial(2*k))
2627
+ for k in range(n) if 4*k + 3 < n]
2628
+ q = [1/(2*z)] + [S.NegativeOne**k * factorial(4*k - 1) /
2629
+ (2**(2*k + 1) * z**(4*k + 1) * 2**(2*k - 1)*factorial(2*k - 1))
2630
+ for k in range(1, n) if 4*k + 1 < n]
2631
+
2632
+ p = [-sqrt(2/pi)*t for t in p]
2633
+ q = [ sqrt(2/pi)*t for t in q]
2634
+ s = 1 if point is S.Infinity else -1
2635
+ # The expansion at oo is 1/2 + some odd powers of z
2636
+ # To get the expansion at -oo, replace z by -z and flip the sign
2637
+ # The result -1/2 + the same odd powers of z as before.
2638
+ return s*S.Half + (cos(z**2)*Add(*p) + sin(z**2)*Add(*q)
2639
+ ).subs(x, sqrt(2/pi)*x) + Order(1/z**n, x)
2640
+
2641
+ # All other points are not handled
2642
+ return super()._eval_aseries(n, args0, x, logx)
2643
+
2644
+
2645
+ ###############################################################################
2646
+ #################### HELPER FUNCTIONS #########################################
2647
+ ###############################################################################
2648
+
2649
+
2650
+ class _erfs(Function):
2651
+ """
2652
+ Helper function to make the $\\mathrm{erf}(z)$ function
2653
+ tractable for the Gruntz algorithm.
2654
+
2655
+ """
2656
+ @classmethod
2657
+ def eval(cls, arg):
2658
+ if arg.is_zero:
2659
+ return S.One
2660
+
2661
+ def _eval_aseries(self, n, args0, x, logx):
2662
+ from sympy.series.order import Order
2663
+ point = args0[0]
2664
+
2665
+ # Expansion at oo
2666
+ if point is S.Infinity:
2667
+ z = self.args[0]
2668
+ l = [1/sqrt(pi) * factorial(2*k)*(-S(
2669
+ 4))**(-k)/factorial(k) * (1/z)**(2*k + 1) for k in range(n)]
2670
+ o = Order(1/z**(2*n + 1), x)
2671
+ # It is very inefficient to first add the order and then do the nseries
2672
+ return (Add(*l))._eval_nseries(x, n, logx) + o
2673
+
2674
+ # Expansion at I*oo
2675
+ t = point.extract_multiplicatively(I)
2676
+ if t is S.Infinity:
2677
+ z = self.args[0]
2678
+ # TODO: is the series really correct?
2679
+ l = [1/sqrt(pi) * factorial(2*k)*(-S(
2680
+ 4))**(-k)/factorial(k) * (1/z)**(2*k + 1) for k in range(n)]
2681
+ o = Order(1/z**(2*n + 1), x)
2682
+ # It is very inefficient to first add the order and then do the nseries
2683
+ return (Add(*l))._eval_nseries(x, n, logx) + o
2684
+
2685
+ # All other points are not handled
2686
+ return super()._eval_aseries(n, args0, x, logx)
2687
+
2688
+ def fdiff(self, argindex=1):
2689
+ if argindex == 1:
2690
+ z = self.args[0]
2691
+ return -2/sqrt(pi) + 2*z*_erfs(z)
2692
+ else:
2693
+ raise ArgumentIndexError(self, argindex)
2694
+
2695
+ def _eval_rewrite_as_intractable(self, z, **kwargs):
2696
+ return (S.One - erf(z))*exp(z**2)
2697
+
2698
+
2699
+ class _eis(Function):
2700
+ """
2701
+ Helper function to make the $\\mathrm{Ei}(z)$ and $\\mathrm{li}(z)$
2702
+ functions tractable for the Gruntz algorithm.
2703
+
2704
+ """
2705
+
2706
+
2707
+ def _eval_aseries(self, n, args0, x, logx):
2708
+ from sympy.series.order import Order
2709
+ if args0[0] != S.Infinity:
2710
+ return super(_erfs, self)._eval_aseries(n, args0, x, logx)
2711
+
2712
+ z = self.args[0]
2713
+ l = [factorial(k) * (1/z)**(k + 1) for k in range(n)]
2714
+ o = Order(1/z**(n + 1), x)
2715
+ # It is very inefficient to first add the order and then do the nseries
2716
+ return (Add(*l))._eval_nseries(x, n, logx) + o
2717
+
2718
+
2719
+ def fdiff(self, argindex=1):
2720
+ if argindex == 1:
2721
+ z = self.args[0]
2722
+ return S.One / z - _eis(z)
2723
+ else:
2724
+ raise ArgumentIndexError(self, argindex)
2725
+
2726
+ def _eval_rewrite_as_intractable(self, z, **kwargs):
2727
+ return exp(-z)*Ei(z)
2728
+
2729
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
2730
+ x0 = self.args[0].limit(x, 0)
2731
+ if x0.is_zero:
2732
+ f = self._eval_rewrite_as_intractable(*self.args)
2733
+ return f._eval_as_leading_term(x, logx=logx, cdir=cdir)
2734
+ return super()._eval_as_leading_term(x, logx=logx, cdir=cdir)
2735
+
2736
+ def _eval_nseries(self, x, n, logx, cdir=0):
2737
+ x0 = self.args[0].limit(x, 0)
2738
+ if x0.is_zero:
2739
+ f = self._eval_rewrite_as_intractable(*self.args)
2740
+ return f._eval_nseries(x, n, logx)
2741
+ return super()._eval_nseries(x, n, logx)
venv/lib/python3.10/site-packages/sympy/functions/special/gamma_functions.py ADDED
@@ -0,0 +1,1344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import prod
2
+
3
+ from sympy.core import Add, S, Dummy, expand_func
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.function import Function, ArgumentIndexError, PoleError
6
+ from sympy.core.logic import fuzzy_and, fuzzy_not
7
+ from sympy.core.numbers import Rational, pi, oo, I
8
+ from sympy.core.power import Pow
9
+ from sympy.functions.special.zeta_functions import zeta
10
+ from sympy.functions.special.error_functions import erf, erfc, Ei
11
+ from sympy.functions.elementary.complexes import re, unpolarify
12
+ from sympy.functions.elementary.exponential import exp, log
13
+ from sympy.functions.elementary.integers import ceiling, floor
14
+ from sympy.functions.elementary.miscellaneous import sqrt
15
+ from sympy.functions.elementary.trigonometric import sin, cos, cot
16
+ from sympy.functions.combinatorial.numbers import bernoulli, harmonic
17
+ from sympy.functions.combinatorial.factorials import factorial, rf, RisingFactorial
18
+ from sympy.utilities.misc import as_int
19
+
20
+ from mpmath import mp, workprec
21
+ from mpmath.libmp.libmpf import prec_to_dps
22
+
23
+ def intlike(n):
24
+ try:
25
+ as_int(n, strict=False)
26
+ return True
27
+ except ValueError:
28
+ return False
29
+
30
+ ###############################################################################
31
+ ############################ COMPLETE GAMMA FUNCTION ##########################
32
+ ###############################################################################
33
+
34
+ class gamma(Function):
35
+ r"""
36
+ The gamma function
37
+
38
+ .. math::
39
+ \Gamma(x) := \int^{\infty}_{0} t^{x-1} e^{-t} \mathrm{d}t.
40
+
41
+ Explanation
42
+ ===========
43
+
44
+ The ``gamma`` function implements the function which passes through the
45
+ values of the factorial function (i.e., $\Gamma(n) = (n - 1)!$ when n is
46
+ an integer). More generally, $\Gamma(z)$ is defined in the whole complex
47
+ plane except at the negative integers where there are simple poles.
48
+
49
+ Examples
50
+ ========
51
+
52
+ >>> from sympy import S, I, pi, gamma
53
+ >>> from sympy.abc import x
54
+
55
+ Several special values are known:
56
+
57
+ >>> gamma(1)
58
+ 1
59
+ >>> gamma(4)
60
+ 6
61
+ >>> gamma(S(3)/2)
62
+ sqrt(pi)/2
63
+
64
+ The ``gamma`` function obeys the mirror symmetry:
65
+
66
+ >>> from sympy import conjugate
67
+ >>> conjugate(gamma(x))
68
+ gamma(conjugate(x))
69
+
70
+ Differentiation with respect to $x$ is supported:
71
+
72
+ >>> from sympy import diff
73
+ >>> diff(gamma(x), x)
74
+ gamma(x)*polygamma(0, x)
75
+
76
+ Series expansion is also supported:
77
+
78
+ >>> from sympy import series
79
+ >>> series(gamma(x), x, 0, 3)
80
+ 1/x - EulerGamma + x*(EulerGamma**2/2 + pi**2/12) + x**2*(-EulerGamma*pi**2/12 - zeta(3)/3 - EulerGamma**3/6) + O(x**3)
81
+
82
+ We can numerically evaluate the ``gamma`` function to arbitrary precision
83
+ on the whole complex plane:
84
+
85
+ >>> gamma(pi).evalf(40)
86
+ 2.288037795340032417959588909060233922890
87
+ >>> gamma(1+I).evalf(20)
88
+ 0.49801566811835604271 - 0.15494982830181068512*I
89
+
90
+ See Also
91
+ ========
92
+
93
+ lowergamma: Lower incomplete gamma function.
94
+ uppergamma: Upper incomplete gamma function.
95
+ polygamma: Polygamma function.
96
+ loggamma: Log Gamma function.
97
+ digamma: Digamma function.
98
+ trigamma: Trigamma function.
99
+ beta: Euler Beta function.
100
+
101
+ References
102
+ ==========
103
+
104
+ .. [1] https://en.wikipedia.org/wiki/Gamma_function
105
+ .. [2] https://dlmf.nist.gov/5
106
+ .. [3] https://mathworld.wolfram.com/GammaFunction.html
107
+ .. [4] https://functions.wolfram.com/GammaBetaErf/Gamma/
108
+
109
+ """
110
+
111
+ unbranched = True
112
+ _singularities = (S.ComplexInfinity,)
113
+
114
+ def fdiff(self, argindex=1):
115
+ if argindex == 1:
116
+ return self.func(self.args[0])*polygamma(0, self.args[0])
117
+ else:
118
+ raise ArgumentIndexError(self, argindex)
119
+
120
+ @classmethod
121
+ def eval(cls, arg):
122
+ if arg.is_Number:
123
+ if arg is S.NaN:
124
+ return S.NaN
125
+ elif arg is oo:
126
+ return oo
127
+ elif intlike(arg):
128
+ if arg.is_positive:
129
+ return factorial(arg - 1)
130
+ else:
131
+ return S.ComplexInfinity
132
+ elif arg.is_Rational:
133
+ if arg.q == 2:
134
+ n = abs(arg.p) // arg.q
135
+
136
+ if arg.is_positive:
137
+ k, coeff = n, S.One
138
+ else:
139
+ n = k = n + 1
140
+
141
+ if n & 1 == 0:
142
+ coeff = S.One
143
+ else:
144
+ coeff = S.NegativeOne
145
+
146
+ coeff *= prod(range(3, 2*k, 2))
147
+
148
+ if arg.is_positive:
149
+ return coeff*sqrt(pi) / 2**n
150
+ else:
151
+ return 2**n*sqrt(pi) / coeff
152
+
153
+ def _eval_expand_func(self, **hints):
154
+ arg = self.args[0]
155
+ if arg.is_Rational:
156
+ if abs(arg.p) > arg.q:
157
+ x = Dummy('x')
158
+ n = arg.p // arg.q
159
+ p = arg.p - n*arg.q
160
+ return self.func(x + n)._eval_expand_func().subs(x, Rational(p, arg.q))
161
+
162
+ if arg.is_Add:
163
+ coeff, tail = arg.as_coeff_add()
164
+ if coeff and coeff.q != 1:
165
+ intpart = floor(coeff)
166
+ tail = (coeff - intpart,) + tail
167
+ coeff = intpart
168
+ tail = arg._new_rawargs(*tail, reeval=False)
169
+ return self.func(tail)*RisingFactorial(tail, coeff)
170
+
171
+ return self.func(*self.args)
172
+
173
+ def _eval_conjugate(self):
174
+ return self.func(self.args[0].conjugate())
175
+
176
+ def _eval_is_real(self):
177
+ x = self.args[0]
178
+ if x.is_nonpositive and x.is_integer:
179
+ return False
180
+ if intlike(x) and x <= 0:
181
+ return False
182
+ if x.is_positive or x.is_noninteger:
183
+ return True
184
+
185
+ def _eval_is_positive(self):
186
+ x = self.args[0]
187
+ if x.is_positive:
188
+ return True
189
+ elif x.is_noninteger:
190
+ return floor(x).is_even
191
+
192
+ def _eval_rewrite_as_tractable(self, z, limitvar=None, **kwargs):
193
+ return exp(loggamma(z))
194
+
195
+ def _eval_rewrite_as_factorial(self, z, **kwargs):
196
+ return factorial(z - 1)
197
+
198
+ def _eval_nseries(self, x, n, logx, cdir=0):
199
+ x0 = self.args[0].limit(x, 0)
200
+ if not (x0.is_Integer and x0 <= 0):
201
+ return super()._eval_nseries(x, n, logx)
202
+ t = self.args[0] - x0
203
+ return (self.func(t + 1)/rf(self.args[0], -x0 + 1))._eval_nseries(x, n, logx)
204
+
205
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
206
+ arg = self.args[0]
207
+ x0 = arg.subs(x, 0)
208
+
209
+ if x0.is_integer and x0.is_nonpositive:
210
+ n = -x0
211
+ res = S.NegativeOne**n/self.func(n + 1)
212
+ return res/(arg + n).as_leading_term(x)
213
+ elif not x0.is_infinite:
214
+ return self.func(x0)
215
+ raise PoleError()
216
+
217
+
218
+ ###############################################################################
219
+ ################## LOWER and UPPER INCOMPLETE GAMMA FUNCTIONS #################
220
+ ###############################################################################
221
+
222
+ class lowergamma(Function):
223
+ r"""
224
+ The lower incomplete gamma function.
225
+
226
+ Explanation
227
+ ===========
228
+
229
+ It can be defined as the meromorphic continuation of
230
+
231
+ .. math::
232
+ \gamma(s, x) := \int_0^x t^{s-1} e^{-t} \mathrm{d}t = \Gamma(s) - \Gamma(s, x).
233
+
234
+ This can be shown to be the same as
235
+
236
+ .. math::
237
+ \gamma(s, x) = \frac{x^s}{s} {}_1F_1\left({s \atop s+1} \middle| -x\right),
238
+
239
+ where ${}_1F_1$ is the (confluent) hypergeometric function.
240
+
241
+ Examples
242
+ ========
243
+
244
+ >>> from sympy import lowergamma, S
245
+ >>> from sympy.abc import s, x
246
+ >>> lowergamma(s, x)
247
+ lowergamma(s, x)
248
+ >>> lowergamma(3, x)
249
+ -2*(x**2/2 + x + 1)*exp(-x) + 2
250
+ >>> lowergamma(-S(1)/2, x)
251
+ -2*sqrt(pi)*erf(sqrt(x)) - 2*exp(-x)/sqrt(x)
252
+
253
+ See Also
254
+ ========
255
+
256
+ gamma: Gamma function.
257
+ uppergamma: Upper incomplete gamma function.
258
+ polygamma: Polygamma function.
259
+ loggamma: Log Gamma function.
260
+ digamma: Digamma function.
261
+ trigamma: Trigamma function.
262
+ beta: Euler Beta function.
263
+
264
+ References
265
+ ==========
266
+
267
+ .. [1] https://en.wikipedia.org/wiki/Incomplete_gamma_function#Lower_incomplete_gamma_function
268
+ .. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6,
269
+ Section 5, Handbook of Mathematical Functions with Formulas, Graphs,
270
+ and Mathematical Tables
271
+ .. [3] https://dlmf.nist.gov/8
272
+ .. [4] https://functions.wolfram.com/GammaBetaErf/Gamma2/
273
+ .. [5] https://functions.wolfram.com/GammaBetaErf/Gamma3/
274
+
275
+ """
276
+
277
+
278
+ def fdiff(self, argindex=2):
279
+ from sympy.functions.special.hyper import meijerg
280
+ if argindex == 2:
281
+ a, z = self.args
282
+ return exp(-unpolarify(z))*z**(a - 1)
283
+ elif argindex == 1:
284
+ a, z = self.args
285
+ return gamma(a)*digamma(a) - log(z)*uppergamma(a, z) \
286
+ - meijerg([], [1, 1], [0, 0, a], [], z)
287
+
288
+ else:
289
+ raise ArgumentIndexError(self, argindex)
290
+
291
+ @classmethod
292
+ def eval(cls, a, x):
293
+ # For lack of a better place, we use this one to extract branching
294
+ # information. The following can be
295
+ # found in the literature (c/f references given above), albeit scattered:
296
+ # 1) For fixed x != 0, lowergamma(s, x) is an entire function of s
297
+ # 2) For fixed positive integers s, lowergamma(s, x) is an entire
298
+ # function of x.
299
+ # 3) For fixed non-positive integers s,
300
+ # lowergamma(s, exp(I*2*pi*n)*x) =
301
+ # 2*pi*I*n*(-1)**(-s)/factorial(-s) + lowergamma(s, x)
302
+ # (this follows from lowergamma(s, x).diff(x) = x**(s-1)*exp(-x)).
303
+ # 4) For fixed non-integral s,
304
+ # lowergamma(s, x) = x**s*gamma(s)*lowergamma_unbranched(s, x),
305
+ # where lowergamma_unbranched(s, x) is an entire function (in fact
306
+ # of both s and x), i.e.
307
+ # lowergamma(s, exp(2*I*pi*n)*x) = exp(2*pi*I*n*a)*lowergamma(a, x)
308
+ if x is S.Zero:
309
+ return S.Zero
310
+ nx, n = x.extract_branch_factor()
311
+ if a.is_integer and a.is_positive:
312
+ nx = unpolarify(x)
313
+ if nx != x:
314
+ return lowergamma(a, nx)
315
+ elif a.is_integer and a.is_nonpositive:
316
+ if n != 0:
317
+ return 2*pi*I*n*S.NegativeOne**(-a)/factorial(-a) + lowergamma(a, nx)
318
+ elif n != 0:
319
+ return exp(2*pi*I*n*a)*lowergamma(a, nx)
320
+
321
+ # Special values.
322
+ if a.is_Number:
323
+ if a is S.One:
324
+ return S.One - exp(-x)
325
+ elif a is S.Half:
326
+ return sqrt(pi)*erf(sqrt(x))
327
+ elif a.is_Integer or (2*a).is_Integer:
328
+ b = a - 1
329
+ if b.is_positive:
330
+ if a.is_integer:
331
+ return factorial(b) - exp(-x) * factorial(b) * Add(*[x ** k / factorial(k) for k in range(a)])
332
+ else:
333
+ return gamma(a)*(lowergamma(S.Half, x)/sqrt(pi) - exp(-x)*Add(*[x**(k - S.Half)/gamma(S.Half + k) for k in range(1, a + S.Half)]))
334
+
335
+ if not a.is_Integer:
336
+ return S.NegativeOne**(S.Half - a)*pi*erf(sqrt(x))/gamma(1 - a) + exp(-x)*Add(*[x**(k + a - 1)*gamma(a)/gamma(a + k) for k in range(1, Rational(3, 2) - a)])
337
+
338
+ if x.is_zero:
339
+ return S.Zero
340
+
341
+ def _eval_evalf(self, prec):
342
+ if all(x.is_number for x in self.args):
343
+ a = self.args[0]._to_mpmath(prec)
344
+ z = self.args[1]._to_mpmath(prec)
345
+ with workprec(prec):
346
+ res = mp.gammainc(a, 0, z)
347
+ return Expr._from_mpmath(res, prec)
348
+ else:
349
+ return self
350
+
351
+ def _eval_conjugate(self):
352
+ x = self.args[1]
353
+ if x not in (S.Zero, S.NegativeInfinity):
354
+ return self.func(self.args[0].conjugate(), x.conjugate())
355
+
356
+ def _eval_is_meromorphic(self, x, a):
357
+ # By https://en.wikipedia.org/wiki/Incomplete_gamma_function#Holomorphic_extension,
358
+ # lowergamma(s, z) = z**s*gamma(s)*gammastar(s, z),
359
+ # where gammastar(s, z) is holomorphic for all s and z.
360
+ # Hence the singularities of lowergamma are z = 0 (branch
361
+ # point) and nonpositive integer values of s (poles of gamma(s)).
362
+ s, z = self.args
363
+ args_merom = fuzzy_and([z._eval_is_meromorphic(x, a),
364
+ s._eval_is_meromorphic(x, a)])
365
+ if not args_merom:
366
+ return args_merom
367
+ z0 = z.subs(x, a)
368
+ if s.is_integer:
369
+ return fuzzy_and([s.is_positive, z0.is_finite])
370
+ s0 = s.subs(x, a)
371
+ return fuzzy_and([s0.is_finite, z0.is_finite, fuzzy_not(z0.is_zero)])
372
+
373
+ def _eval_aseries(self, n, args0, x, logx):
374
+ from sympy.series.order import O
375
+ s, z = self.args
376
+ if args0[0] is oo and not z.has(x):
377
+ coeff = z**s*exp(-z)
378
+ sum_expr = sum(z**k/rf(s, k + 1) for k in range(n - 1))
379
+ o = O(z**s*s**(-n))
380
+ return coeff*sum_expr + o
381
+ return super()._eval_aseries(n, args0, x, logx)
382
+
383
+ def _eval_rewrite_as_uppergamma(self, s, x, **kwargs):
384
+ return gamma(s) - uppergamma(s, x)
385
+
386
+ def _eval_rewrite_as_expint(self, s, x, **kwargs):
387
+ from sympy.functions.special.error_functions import expint
388
+ if s.is_integer and s.is_nonpositive:
389
+ return self
390
+ return self.rewrite(uppergamma).rewrite(expint)
391
+
392
+ def _eval_is_zero(self):
393
+ x = self.args[1]
394
+ if x.is_zero:
395
+ return True
396
+
397
+
398
+ class uppergamma(Function):
399
+ r"""
400
+ The upper incomplete gamma function.
401
+
402
+ Explanation
403
+ ===========
404
+
405
+ It can be defined as the meromorphic continuation of
406
+
407
+ .. math::
408
+ \Gamma(s, x) := \int_x^\infty t^{s-1} e^{-t} \mathrm{d}t = \Gamma(s) - \gamma(s, x).
409
+
410
+ where $\gamma(s, x)$ is the lower incomplete gamma function,
411
+ :class:`lowergamma`. This can be shown to be the same as
412
+
413
+ .. math::
414
+ \Gamma(s, x) = \Gamma(s) - \frac{x^s}{s} {}_1F_1\left({s \atop s+1} \middle| -x\right),
415
+
416
+ where ${}_1F_1$ is the (confluent) hypergeometric function.
417
+
418
+ The upper incomplete gamma function is also essentially equivalent to the
419
+ generalized exponential integral:
420
+
421
+ .. math::
422
+ \operatorname{E}_{n}(x) = \int_{1}^{\infty}{\frac{e^{-xt}}{t^n} \, dt} = x^{n-1}\Gamma(1-n,x).
423
+
424
+ Examples
425
+ ========
426
+
427
+ >>> from sympy import uppergamma, S
428
+ >>> from sympy.abc import s, x
429
+ >>> uppergamma(s, x)
430
+ uppergamma(s, x)
431
+ >>> uppergamma(3, x)
432
+ 2*(x**2/2 + x + 1)*exp(-x)
433
+ >>> uppergamma(-S(1)/2, x)
434
+ -2*sqrt(pi)*erfc(sqrt(x)) + 2*exp(-x)/sqrt(x)
435
+ >>> uppergamma(-2, x)
436
+ expint(3, x)/x**2
437
+
438
+ See Also
439
+ ========
440
+
441
+ gamma: Gamma function.
442
+ lowergamma: Lower incomplete gamma function.
443
+ polygamma: Polygamma function.
444
+ loggamma: Log Gamma function.
445
+ digamma: Digamma function.
446
+ trigamma: Trigamma function.
447
+ beta: Euler Beta function.
448
+
449
+ References
450
+ ==========
451
+
452
+ .. [1] https://en.wikipedia.org/wiki/Incomplete_gamma_function#Upper_incomplete_gamma_function
453
+ .. [2] Abramowitz, Milton; Stegun, Irene A., eds. (1965), Chapter 6,
454
+ Section 5, Handbook of Mathematical Functions with Formulas, Graphs,
455
+ and Mathematical Tables
456
+ .. [3] https://dlmf.nist.gov/8
457
+ .. [4] https://functions.wolfram.com/GammaBetaErf/Gamma2/
458
+ .. [5] https://functions.wolfram.com/GammaBetaErf/Gamma3/
459
+ .. [6] https://en.wikipedia.org/wiki/Exponential_integral#Relation_with_other_functions
460
+
461
+ """
462
+
463
+
464
+ def fdiff(self, argindex=2):
465
+ from sympy.functions.special.hyper import meijerg
466
+ if argindex == 2:
467
+ a, z = self.args
468
+ return -exp(-unpolarify(z))*z**(a - 1)
469
+ elif argindex == 1:
470
+ a, z = self.args
471
+ return uppergamma(a, z)*log(z) + meijerg([], [1, 1], [0, 0, a], [], z)
472
+ else:
473
+ raise ArgumentIndexError(self, argindex)
474
+
475
+ def _eval_evalf(self, prec):
476
+ if all(x.is_number for x in self.args):
477
+ a = self.args[0]._to_mpmath(prec)
478
+ z = self.args[1]._to_mpmath(prec)
479
+ with workprec(prec):
480
+ res = mp.gammainc(a, z, mp.inf)
481
+ return Expr._from_mpmath(res, prec)
482
+ return self
483
+
484
+ @classmethod
485
+ def eval(cls, a, z):
486
+ from sympy.functions.special.error_functions import expint
487
+ if z.is_Number:
488
+ if z is S.NaN:
489
+ return S.NaN
490
+ elif z is oo:
491
+ return S.Zero
492
+ elif z.is_zero:
493
+ if re(a).is_positive:
494
+ return gamma(a)
495
+
496
+ # We extract branching information here. C/f lowergamma.
497
+ nx, n = z.extract_branch_factor()
498
+ if a.is_integer and a.is_positive:
499
+ nx = unpolarify(z)
500
+ if z != nx:
501
+ return uppergamma(a, nx)
502
+ elif a.is_integer and a.is_nonpositive:
503
+ if n != 0:
504
+ return -2*pi*I*n*S.NegativeOne**(-a)/factorial(-a) + uppergamma(a, nx)
505
+ elif n != 0:
506
+ return gamma(a)*(1 - exp(2*pi*I*n*a)) + exp(2*pi*I*n*a)*uppergamma(a, nx)
507
+
508
+ # Special values.
509
+ if a.is_Number:
510
+ if a is S.Zero and z.is_positive:
511
+ return -Ei(-z)
512
+ elif a is S.One:
513
+ return exp(-z)
514
+ elif a is S.Half:
515
+ return sqrt(pi)*erfc(sqrt(z))
516
+ elif a.is_Integer or (2*a).is_Integer:
517
+ b = a - 1
518
+ if b.is_positive:
519
+ if a.is_integer:
520
+ return exp(-z) * factorial(b) * Add(*[z**k / factorial(k)
521
+ for k in range(a)])
522
+ else:
523
+ return (gamma(a) * erfc(sqrt(z)) +
524
+ S.NegativeOne**(a - S(3)/2) * exp(-z) * sqrt(z)
525
+ * Add(*[gamma(-S.Half - k) * (-z)**k / gamma(1-a)
526
+ for k in range(a - S.Half)]))
527
+ elif b.is_Integer:
528
+ return expint(-b, z)*unpolarify(z)**(b + 1)
529
+
530
+ if not a.is_Integer:
531
+ return (S.NegativeOne**(S.Half - a) * pi*erfc(sqrt(z))/gamma(1-a)
532
+ - z**a * exp(-z) * Add(*[z**k * gamma(a) / gamma(a+k+1)
533
+ for k in range(S.Half - a)]))
534
+
535
+ if a.is_zero and z.is_positive:
536
+ return -Ei(-z)
537
+
538
+ if z.is_zero and re(a).is_positive:
539
+ return gamma(a)
540
+
541
+ def _eval_conjugate(self):
542
+ z = self.args[1]
543
+ if z not in (S.Zero, S.NegativeInfinity):
544
+ return self.func(self.args[0].conjugate(), z.conjugate())
545
+
546
+ def _eval_is_meromorphic(self, x, a):
547
+ return lowergamma._eval_is_meromorphic(self, x, a)
548
+
549
+ def _eval_rewrite_as_lowergamma(self, s, x, **kwargs):
550
+ return gamma(s) - lowergamma(s, x)
551
+
552
+ def _eval_rewrite_as_tractable(self, s, x, **kwargs):
553
+ return exp(loggamma(s)) - lowergamma(s, x)
554
+
555
+ def _eval_rewrite_as_expint(self, s, x, **kwargs):
556
+ from sympy.functions.special.error_functions import expint
557
+ return expint(1 - s, x)*x**s
558
+
559
+
560
+ ###############################################################################
561
+ ###################### POLYGAMMA and LOGGAMMA FUNCTIONS #######################
562
+ ###############################################################################
563
+
564
+ class polygamma(Function):
565
+ r"""
566
+ The function ``polygamma(n, z)`` returns ``log(gamma(z)).diff(n + 1)``.
567
+
568
+ Explanation
569
+ ===========
570
+
571
+ It is a meromorphic function on $\mathbb{C}$ and defined as the $(n+1)$-th
572
+ derivative of the logarithm of the gamma function:
573
+
574
+ .. math::
575
+ \psi^{(n)} (z) := \frac{\mathrm{d}^{n+1}}{\mathrm{d} z^{n+1}} \log\Gamma(z).
576
+
577
+ For `n` not a nonnegative integer the generalization by Espinosa and Moll [5]_
578
+ is used:
579
+
580
+ .. math:: \psi(s,z) = \frac{\zeta'(s+1, z) + (\gamma + \psi(-s)) \zeta(s+1, z)}
581
+ {\Gamma(-s)}
582
+
583
+ Examples
584
+ ========
585
+
586
+ Several special values are known:
587
+
588
+ >>> from sympy import S, polygamma
589
+ >>> polygamma(0, 1)
590
+ -EulerGamma
591
+ >>> polygamma(0, 1/S(2))
592
+ -2*log(2) - EulerGamma
593
+ >>> polygamma(0, 1/S(3))
594
+ -log(3) - sqrt(3)*pi/6 - EulerGamma - log(sqrt(3))
595
+ >>> polygamma(0, 1/S(4))
596
+ -pi/2 - log(4) - log(2) - EulerGamma
597
+ >>> polygamma(0, 2)
598
+ 1 - EulerGamma
599
+ >>> polygamma(0, 23)
600
+ 19093197/5173168 - EulerGamma
601
+
602
+ >>> from sympy import oo, I
603
+ >>> polygamma(0, oo)
604
+ oo
605
+ >>> polygamma(0, -oo)
606
+ oo
607
+ >>> polygamma(0, I*oo)
608
+ oo
609
+ >>> polygamma(0, -I*oo)
610
+ oo
611
+
612
+ Differentiation with respect to $x$ is supported:
613
+
614
+ >>> from sympy import Symbol, diff
615
+ >>> x = Symbol("x")
616
+ >>> diff(polygamma(0, x), x)
617
+ polygamma(1, x)
618
+ >>> diff(polygamma(0, x), x, 2)
619
+ polygamma(2, x)
620
+ >>> diff(polygamma(0, x), x, 3)
621
+ polygamma(3, x)
622
+ >>> diff(polygamma(1, x), x)
623
+ polygamma(2, x)
624
+ >>> diff(polygamma(1, x), x, 2)
625
+ polygamma(3, x)
626
+ >>> diff(polygamma(2, x), x)
627
+ polygamma(3, x)
628
+ >>> diff(polygamma(2, x), x, 2)
629
+ polygamma(4, x)
630
+
631
+ >>> n = Symbol("n")
632
+ >>> diff(polygamma(n, x), x)
633
+ polygamma(n + 1, x)
634
+ >>> diff(polygamma(n, x), x, 2)
635
+ polygamma(n + 2, x)
636
+
637
+ We can rewrite ``polygamma`` functions in terms of harmonic numbers:
638
+
639
+ >>> from sympy import harmonic
640
+ >>> polygamma(0, x).rewrite(harmonic)
641
+ harmonic(x - 1) - EulerGamma
642
+ >>> polygamma(2, x).rewrite(harmonic)
643
+ 2*harmonic(x - 1, 3) - 2*zeta(3)
644
+ >>> ni = Symbol("n", integer=True)
645
+ >>> polygamma(ni, x).rewrite(harmonic)
646
+ (-1)**(n + 1)*(-harmonic(x - 1, n + 1) + zeta(n + 1))*factorial(n)
647
+
648
+ See Also
649
+ ========
650
+
651
+ gamma: Gamma function.
652
+ lowergamma: Lower incomplete gamma function.
653
+ uppergamma: Upper incomplete gamma function.
654
+ loggamma: Log Gamma function.
655
+ digamma: Digamma function.
656
+ trigamma: Trigamma function.
657
+ beta: Euler Beta function.
658
+
659
+ References
660
+ ==========
661
+
662
+ .. [1] https://en.wikipedia.org/wiki/Polygamma_function
663
+ .. [2] https://mathworld.wolfram.com/PolygammaFunction.html
664
+ .. [3] https://functions.wolfram.com/GammaBetaErf/PolyGamma/
665
+ .. [4] https://functions.wolfram.com/GammaBetaErf/PolyGamma2/
666
+ .. [5] O. Espinosa and V. Moll, "A generalized polygamma function",
667
+ *Integral Transforms and Special Functions* (2004), 101-115.
668
+
669
+ """
670
+
671
+ @classmethod
672
+ def eval(cls, n, z):
673
+ if n is S.NaN or z is S.NaN:
674
+ return S.NaN
675
+ elif z is oo:
676
+ return oo if n.is_zero else S.Zero
677
+ elif z.is_Integer and z.is_nonpositive:
678
+ return S.ComplexInfinity
679
+ elif n is S.NegativeOne:
680
+ return loggamma(z) - log(2*pi) / 2
681
+ elif n.is_zero:
682
+ if z is -oo or z.extract_multiplicatively(I) in (oo, -oo):
683
+ return oo
684
+ elif z.is_Integer:
685
+ return harmonic(z-1) - S.EulerGamma
686
+ elif z.is_Rational:
687
+ # TODO n == 1 also can do some rational z
688
+ p, q = z.as_numer_denom()
689
+ # only expand for small denominators to avoid creating long expressions
690
+ if q <= 6:
691
+ return expand_func(polygamma(S.Zero, z, evaluate=False))
692
+ elif n.is_integer and n.is_nonnegative:
693
+ nz = unpolarify(z)
694
+ if z != nz:
695
+ return polygamma(n, nz)
696
+ if z.is_Integer:
697
+ return S.NegativeOne**(n+1) * factorial(n) * zeta(n+1, z)
698
+ elif z is S.Half:
699
+ return S.NegativeOne**(n+1) * factorial(n) * (2**(n+1)-1) * zeta(n+1)
700
+
701
+ def _eval_is_real(self):
702
+ if self.args[0].is_positive and self.args[1].is_positive:
703
+ return True
704
+
705
+ def _eval_is_complex(self):
706
+ z = self.args[1]
707
+ is_negative_integer = fuzzy_and([z.is_negative, z.is_integer])
708
+ return fuzzy_and([z.is_complex, fuzzy_not(is_negative_integer)])
709
+
710
+ def _eval_is_positive(self):
711
+ n, z = self.args
712
+ if n.is_positive:
713
+ if n.is_odd and z.is_real:
714
+ return True
715
+ if n.is_even and z.is_positive:
716
+ return False
717
+
718
+ def _eval_is_negative(self):
719
+ n, z = self.args
720
+ if n.is_positive:
721
+ if n.is_even and z.is_positive:
722
+ return True
723
+ if n.is_odd and z.is_real:
724
+ return False
725
+
726
+ def _eval_expand_func(self, **hints):
727
+ n, z = self.args
728
+
729
+ if n.is_Integer and n.is_nonnegative:
730
+ if z.is_Add:
731
+ coeff = z.args[0]
732
+ if coeff.is_Integer:
733
+ e = -(n + 1)
734
+ if coeff > 0:
735
+ tail = Add(*[Pow(
736
+ z - i, e) for i in range(1, int(coeff) + 1)])
737
+ else:
738
+ tail = -Add(*[Pow(
739
+ z + i, e) for i in range(int(-coeff))])
740
+ return polygamma(n, z - coeff) + S.NegativeOne**n*factorial(n)*tail
741
+
742
+ elif z.is_Mul:
743
+ coeff, z = z.as_two_terms()
744
+ if coeff.is_Integer and coeff.is_positive:
745
+ tail = [polygamma(n, z + Rational(
746
+ i, coeff)) for i in range(int(coeff))]
747
+ if n == 0:
748
+ return Add(*tail)/coeff + log(coeff)
749
+ else:
750
+ return Add(*tail)/coeff**(n + 1)
751
+ z *= coeff
752
+
753
+ if n == 0 and z.is_Rational:
754
+ p, q = z.as_numer_denom()
755
+
756
+ # Reference:
757
+ # Values of the polygamma functions at rational arguments, J. Choi, 2007
758
+ part_1 = -S.EulerGamma - pi * cot(p * pi / q) / 2 - log(q) + Add(
759
+ *[cos(2 * k * pi * p / q) * log(2 * sin(k * pi / q)) for k in range(1, q)])
760
+
761
+ if z > 0:
762
+ n = floor(z)
763
+ z0 = z - n
764
+ return part_1 + Add(*[1 / (z0 + k) for k in range(n)])
765
+ elif z < 0:
766
+ n = floor(1 - z)
767
+ z0 = z + n
768
+ return part_1 - Add(*[1 / (z0 - 1 - k) for k in range(n)])
769
+
770
+ if n == -1:
771
+ return loggamma(z) - log(2*pi) / 2
772
+ if n.is_integer is False or n.is_nonnegative is False:
773
+ s = Dummy("s")
774
+ dzt = zeta(s, z).diff(s).subs(s, n+1)
775
+ return (dzt + (S.EulerGamma + digamma(-n)) * zeta(n+1, z)) / gamma(-n)
776
+
777
+ return polygamma(n, z)
778
+
779
+ def _eval_rewrite_as_zeta(self, n, z, **kwargs):
780
+ if n.is_integer and n.is_positive:
781
+ return S.NegativeOne**(n + 1)*factorial(n)*zeta(n + 1, z)
782
+
783
+ def _eval_rewrite_as_harmonic(self, n, z, **kwargs):
784
+ if n.is_integer:
785
+ if n.is_zero:
786
+ return harmonic(z - 1) - S.EulerGamma
787
+ else:
788
+ return S.NegativeOne**(n+1) * factorial(n) * (zeta(n+1) - harmonic(z-1, n+1))
789
+
790
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
791
+ from sympy.series.order import Order
792
+ n, z = [a.as_leading_term(x) for a in self.args]
793
+ o = Order(z, x)
794
+ if n == 0 and o.contains(1/x):
795
+ logx = log(x) if logx is None else logx
796
+ return o.getn() * logx
797
+ else:
798
+ return self.func(n, z)
799
+
800
+ def fdiff(self, argindex=2):
801
+ if argindex == 2:
802
+ n, z = self.args[:2]
803
+ return polygamma(n + 1, z)
804
+ else:
805
+ raise ArgumentIndexError(self, argindex)
806
+
807
+ def _eval_aseries(self, n, args0, x, logx):
808
+ from sympy.series.order import Order
809
+ if args0[1] != oo or not \
810
+ (self.args[0].is_Integer and self.args[0].is_nonnegative):
811
+ return super()._eval_aseries(n, args0, x, logx)
812
+ z = self.args[1]
813
+ N = self.args[0]
814
+
815
+ if N == 0:
816
+ # digamma function series
817
+ # Abramowitz & Stegun, p. 259, 6.3.18
818
+ r = log(z) - 1/(2*z)
819
+ o = None
820
+ if n < 2:
821
+ o = Order(1/z, x)
822
+ else:
823
+ m = ceiling((n + 1)//2)
824
+ l = [bernoulli(2*k) / (2*k*z**(2*k)) for k in range(1, m)]
825
+ r -= Add(*l)
826
+ o = Order(1/z**n, x)
827
+ return r._eval_nseries(x, n, logx) + o
828
+ else:
829
+ # proper polygamma function
830
+ # Abramowitz & Stegun, p. 260, 6.4.10
831
+ # We return terms to order higher than O(x**n) on purpose
832
+ # -- otherwise we would not be able to return any terms for
833
+ # quite a long time!
834
+ fac = gamma(N)
835
+ e0 = fac + N*fac/(2*z)
836
+ m = ceiling((n + 1)//2)
837
+ for k in range(1, m):
838
+ fac = fac*(2*k + N - 1)*(2*k + N - 2) / ((2*k)*(2*k - 1))
839
+ e0 += bernoulli(2*k)*fac/z**(2*k)
840
+ o = Order(1/z**(2*m), x)
841
+ if n == 0:
842
+ o = Order(1/z, x)
843
+ elif n == 1:
844
+ o = Order(1/z**2, x)
845
+ r = e0._eval_nseries(z, n, logx) + o
846
+ return (-1 * (-1/z)**N * r)._eval_nseries(x, n, logx)
847
+
848
+ def _eval_evalf(self, prec):
849
+ if not all(i.is_number for i in self.args):
850
+ return
851
+ s = self.args[0]._to_mpmath(prec+12)
852
+ z = self.args[1]._to_mpmath(prec+12)
853
+ if mp.isint(z) and z <= 0:
854
+ return S.ComplexInfinity
855
+ with workprec(prec+12):
856
+ if mp.isint(s) and s >= 0:
857
+ res = mp.polygamma(s, z)
858
+ else:
859
+ zt = mp.zeta(s+1, z)
860
+ dzt = mp.zeta(s+1, z, 1)
861
+ res = (dzt + (mp.euler + mp.digamma(-s)) * zt) * mp.rgamma(-s)
862
+ return Expr._from_mpmath(res, prec)
863
+
864
+
865
+ class loggamma(Function):
866
+ r"""
867
+ The ``loggamma`` function implements the logarithm of the
868
+ gamma function (i.e., $\log\Gamma(x)$).
869
+
870
+ Examples
871
+ ========
872
+
873
+ Several special values are known. For numerical integral
874
+ arguments we have:
875
+
876
+ >>> from sympy import loggamma
877
+ >>> loggamma(-2)
878
+ oo
879
+ >>> loggamma(0)
880
+ oo
881
+ >>> loggamma(1)
882
+ 0
883
+ >>> loggamma(2)
884
+ 0
885
+ >>> loggamma(3)
886
+ log(2)
887
+
888
+ And for symbolic values:
889
+
890
+ >>> from sympy import Symbol
891
+ >>> n = Symbol("n", integer=True, positive=True)
892
+ >>> loggamma(n)
893
+ log(gamma(n))
894
+ >>> loggamma(-n)
895
+ oo
896
+
897
+ For half-integral values:
898
+
899
+ >>> from sympy import S
900
+ >>> loggamma(S(5)/2)
901
+ log(3*sqrt(pi)/4)
902
+ >>> loggamma(n/2)
903
+ log(2**(1 - n)*sqrt(pi)*gamma(n)/gamma(n/2 + 1/2))
904
+
905
+ And general rational arguments:
906
+
907
+ >>> from sympy import expand_func
908
+ >>> L = loggamma(S(16)/3)
909
+ >>> expand_func(L).doit()
910
+ -5*log(3) + loggamma(1/3) + log(4) + log(7) + log(10) + log(13)
911
+ >>> L = loggamma(S(19)/4)
912
+ >>> expand_func(L).doit()
913
+ -4*log(4) + loggamma(3/4) + log(3) + log(7) + log(11) + log(15)
914
+ >>> L = loggamma(S(23)/7)
915
+ >>> expand_func(L).doit()
916
+ -3*log(7) + log(2) + loggamma(2/7) + log(9) + log(16)
917
+
918
+ The ``loggamma`` function has the following limits towards infinity:
919
+
920
+ >>> from sympy import oo
921
+ >>> loggamma(oo)
922
+ oo
923
+ >>> loggamma(-oo)
924
+ zoo
925
+
926
+ The ``loggamma`` function obeys the mirror symmetry
927
+ if $x \in \mathbb{C} \setminus \{-\infty, 0\}$:
928
+
929
+ >>> from sympy.abc import x
930
+ >>> from sympy import conjugate
931
+ >>> conjugate(loggamma(x))
932
+ loggamma(conjugate(x))
933
+
934
+ Differentiation with respect to $x$ is supported:
935
+
936
+ >>> from sympy import diff
937
+ >>> diff(loggamma(x), x)
938
+ polygamma(0, x)
939
+
940
+ Series expansion is also supported:
941
+
942
+ >>> from sympy import series
943
+ >>> series(loggamma(x), x, 0, 4).cancel()
944
+ -log(x) - EulerGamma*x + pi**2*x**2/12 - x**3*zeta(3)/3 + O(x**4)
945
+
946
+ We can numerically evaluate the ``loggamma`` function
947
+ to arbitrary precision on the whole complex plane:
948
+
949
+ >>> from sympy import I
950
+ >>> loggamma(5).evalf(30)
951
+ 3.17805383034794561964694160130
952
+ >>> loggamma(I).evalf(20)
953
+ -0.65092319930185633889 - 1.8724366472624298171*I
954
+
955
+ See Also
956
+ ========
957
+
958
+ gamma: Gamma function.
959
+ lowergamma: Lower incomplete gamma function.
960
+ uppergamma: Upper incomplete gamma function.
961
+ polygamma: Polygamma function.
962
+ digamma: Digamma function.
963
+ trigamma: Trigamma function.
964
+ beta: Euler Beta function.
965
+
966
+ References
967
+ ==========
968
+
969
+ .. [1] https://en.wikipedia.org/wiki/Gamma_function
970
+ .. [2] https://dlmf.nist.gov/5
971
+ .. [3] https://mathworld.wolfram.com/LogGammaFunction.html
972
+ .. [4] https://functions.wolfram.com/GammaBetaErf/LogGamma/
973
+
974
+ """
975
+ @classmethod
976
+ def eval(cls, z):
977
+ if z.is_integer:
978
+ if z.is_nonpositive:
979
+ return oo
980
+ elif z.is_positive:
981
+ return log(gamma(z))
982
+ elif z.is_rational:
983
+ p, q = z.as_numer_denom()
984
+ # Half-integral values:
985
+ if p.is_positive and q == 2:
986
+ return log(sqrt(pi) * 2**(1 - p) * gamma(p) / gamma((p + 1)*S.Half))
987
+
988
+ if z is oo:
989
+ return oo
990
+ elif abs(z) is oo:
991
+ return S.ComplexInfinity
992
+ if z is S.NaN:
993
+ return S.NaN
994
+
995
+ def _eval_expand_func(self, **hints):
996
+ from sympy.concrete.summations import Sum
997
+ z = self.args[0]
998
+
999
+ if z.is_Rational:
1000
+ p, q = z.as_numer_denom()
1001
+ # General rational arguments (u + p/q)
1002
+ # Split z as n + p/q with p < q
1003
+ n = p // q
1004
+ p = p - n*q
1005
+ if p.is_positive and q.is_positive and p < q:
1006
+ k = Dummy("k")
1007
+ if n.is_positive:
1008
+ return loggamma(p / q) - n*log(q) + Sum(log((k - 1)*q + p), (k, 1, n))
1009
+ elif n.is_negative:
1010
+ return loggamma(p / q) - n*log(q) + pi*I*n - Sum(log(k*q - p), (k, 1, -n))
1011
+ elif n.is_zero:
1012
+ return loggamma(p / q)
1013
+
1014
+ return self
1015
+
1016
+ def _eval_nseries(self, x, n, logx=None, cdir=0):
1017
+ x0 = self.args[0].limit(x, 0)
1018
+ if x0.is_zero:
1019
+ f = self._eval_rewrite_as_intractable(*self.args)
1020
+ return f._eval_nseries(x, n, logx)
1021
+ return super()._eval_nseries(x, n, logx)
1022
+
1023
+ def _eval_aseries(self, n, args0, x, logx):
1024
+ from sympy.series.order import Order
1025
+ if args0[0] != oo:
1026
+ return super()._eval_aseries(n, args0, x, logx)
1027
+ z = self.args[0]
1028
+ r = log(z)*(z - S.Half) - z + log(2*pi)/2
1029
+ l = [bernoulli(2*k) / (2*k*(2*k - 1)*z**(2*k - 1)) for k in range(1, n)]
1030
+ o = None
1031
+ if n == 0:
1032
+ o = Order(1, x)
1033
+ else:
1034
+ o = Order(1/z**n, x)
1035
+ # It is very inefficient to first add the order and then do the nseries
1036
+ return (r + Add(*l))._eval_nseries(x, n, logx) + o
1037
+
1038
+ def _eval_rewrite_as_intractable(self, z, **kwargs):
1039
+ return log(gamma(z))
1040
+
1041
+ def _eval_is_real(self):
1042
+ z = self.args[0]
1043
+ if z.is_positive:
1044
+ return True
1045
+ elif z.is_nonpositive:
1046
+ return False
1047
+
1048
+ def _eval_conjugate(self):
1049
+ z = self.args[0]
1050
+ if z not in (S.Zero, S.NegativeInfinity):
1051
+ return self.func(z.conjugate())
1052
+
1053
+ def fdiff(self, argindex=1):
1054
+ if argindex == 1:
1055
+ return polygamma(0, self.args[0])
1056
+ else:
1057
+ raise ArgumentIndexError(self, argindex)
1058
+
1059
+
1060
+ class digamma(Function):
1061
+ r"""
1062
+ The ``digamma`` function is the first derivative of the ``loggamma``
1063
+ function
1064
+
1065
+ .. math::
1066
+ \psi(x) := \frac{\mathrm{d}}{\mathrm{d} z} \log\Gamma(z)
1067
+ = \frac{\Gamma'(z)}{\Gamma(z) }.
1068
+
1069
+ In this case, ``digamma(z) = polygamma(0, z)``.
1070
+
1071
+ Examples
1072
+ ========
1073
+
1074
+ >>> from sympy import digamma
1075
+ >>> digamma(0)
1076
+ zoo
1077
+ >>> from sympy import Symbol
1078
+ >>> z = Symbol('z')
1079
+ >>> digamma(z)
1080
+ polygamma(0, z)
1081
+
1082
+ To retain ``digamma`` as it is:
1083
+
1084
+ >>> digamma(0, evaluate=False)
1085
+ digamma(0)
1086
+ >>> digamma(z, evaluate=False)
1087
+ digamma(z)
1088
+
1089
+ See Also
1090
+ ========
1091
+
1092
+ gamma: Gamma function.
1093
+ lowergamma: Lower incomplete gamma function.
1094
+ uppergamma: Upper incomplete gamma function.
1095
+ polygamma: Polygamma function.
1096
+ loggamma: Log Gamma function.
1097
+ trigamma: Trigamma function.
1098
+ beta: Euler Beta function.
1099
+
1100
+ References
1101
+ ==========
1102
+
1103
+ .. [1] https://en.wikipedia.org/wiki/Digamma_function
1104
+ .. [2] https://mathworld.wolfram.com/DigammaFunction.html
1105
+ .. [3] https://functions.wolfram.com/GammaBetaErf/PolyGamma2/
1106
+
1107
+ """
1108
+ def _eval_evalf(self, prec):
1109
+ z = self.args[0]
1110
+ nprec = prec_to_dps(prec)
1111
+ return polygamma(0, z).evalf(n=nprec)
1112
+
1113
+ def fdiff(self, argindex=1):
1114
+ z = self.args[0]
1115
+ return polygamma(0, z).fdiff()
1116
+
1117
+ def _eval_is_real(self):
1118
+ z = self.args[0]
1119
+ return polygamma(0, z).is_real
1120
+
1121
+ def _eval_is_positive(self):
1122
+ z = self.args[0]
1123
+ return polygamma(0, z).is_positive
1124
+
1125
+ def _eval_is_negative(self):
1126
+ z = self.args[0]
1127
+ return polygamma(0, z).is_negative
1128
+
1129
+ def _eval_aseries(self, n, args0, x, logx):
1130
+ as_polygamma = self.rewrite(polygamma)
1131
+ args0 = [S.Zero,] + args0
1132
+ return as_polygamma._eval_aseries(n, args0, x, logx)
1133
+
1134
+ @classmethod
1135
+ def eval(cls, z):
1136
+ return polygamma(0, z)
1137
+
1138
+ def _eval_expand_func(self, **hints):
1139
+ z = self.args[0]
1140
+ return polygamma(0, z).expand(func=True)
1141
+
1142
+ def _eval_rewrite_as_harmonic(self, z, **kwargs):
1143
+ return harmonic(z - 1) - S.EulerGamma
1144
+
1145
+ def _eval_rewrite_as_polygamma(self, z, **kwargs):
1146
+ return polygamma(0, z)
1147
+
1148
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
1149
+ z = self.args[0]
1150
+ return polygamma(0, z).as_leading_term(x)
1151
+
1152
+
1153
+
1154
+ class trigamma(Function):
1155
+ r"""
1156
+ The ``trigamma`` function is the second derivative of the ``loggamma``
1157
+ function
1158
+
1159
+ .. math::
1160
+ \psi^{(1)}(z) := \frac{\mathrm{d}^{2}}{\mathrm{d} z^{2}} \log\Gamma(z).
1161
+
1162
+ In this case, ``trigamma(z) = polygamma(1, z)``.
1163
+
1164
+ Examples
1165
+ ========
1166
+
1167
+ >>> from sympy import trigamma
1168
+ >>> trigamma(0)
1169
+ zoo
1170
+ >>> from sympy import Symbol
1171
+ >>> z = Symbol('z')
1172
+ >>> trigamma(z)
1173
+ polygamma(1, z)
1174
+
1175
+ To retain ``trigamma`` as it is:
1176
+
1177
+ >>> trigamma(0, evaluate=False)
1178
+ trigamma(0)
1179
+ >>> trigamma(z, evaluate=False)
1180
+ trigamma(z)
1181
+
1182
+
1183
+ See Also
1184
+ ========
1185
+
1186
+ gamma: Gamma function.
1187
+ lowergamma: Lower incomplete gamma function.
1188
+ uppergamma: Upper incomplete gamma function.
1189
+ polygamma: Polygamma function.
1190
+ loggamma: Log Gamma function.
1191
+ digamma: Digamma function.
1192
+ beta: Euler Beta function.
1193
+
1194
+ References
1195
+ ==========
1196
+
1197
+ .. [1] https://en.wikipedia.org/wiki/Trigamma_function
1198
+ .. [2] https://mathworld.wolfram.com/TrigammaFunction.html
1199
+ .. [3] https://functions.wolfram.com/GammaBetaErf/PolyGamma2/
1200
+
1201
+ """
1202
+ def _eval_evalf(self, prec):
1203
+ z = self.args[0]
1204
+ nprec = prec_to_dps(prec)
1205
+ return polygamma(1, z).evalf(n=nprec)
1206
+
1207
+ def fdiff(self, argindex=1):
1208
+ z = self.args[0]
1209
+ return polygamma(1, z).fdiff()
1210
+
1211
+ def _eval_is_real(self):
1212
+ z = self.args[0]
1213
+ return polygamma(1, z).is_real
1214
+
1215
+ def _eval_is_positive(self):
1216
+ z = self.args[0]
1217
+ return polygamma(1, z).is_positive
1218
+
1219
+ def _eval_is_negative(self):
1220
+ z = self.args[0]
1221
+ return polygamma(1, z).is_negative
1222
+
1223
+ def _eval_aseries(self, n, args0, x, logx):
1224
+ as_polygamma = self.rewrite(polygamma)
1225
+ args0 = [S.One,] + args0
1226
+ return as_polygamma._eval_aseries(n, args0, x, logx)
1227
+
1228
+ @classmethod
1229
+ def eval(cls, z):
1230
+ return polygamma(1, z)
1231
+
1232
+ def _eval_expand_func(self, **hints):
1233
+ z = self.args[0]
1234
+ return polygamma(1, z).expand(func=True)
1235
+
1236
+ def _eval_rewrite_as_zeta(self, z, **kwargs):
1237
+ return zeta(2, z)
1238
+
1239
+ def _eval_rewrite_as_polygamma(self, z, **kwargs):
1240
+ return polygamma(1, z)
1241
+
1242
+ def _eval_rewrite_as_harmonic(self, z, **kwargs):
1243
+ return -harmonic(z - 1, 2) + pi**2 / 6
1244
+
1245
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
1246
+ z = self.args[0]
1247
+ return polygamma(1, z).as_leading_term(x)
1248
+
1249
+
1250
+ ###############################################################################
1251
+ ##################### COMPLETE MULTIVARIATE GAMMA FUNCTION ####################
1252
+ ###############################################################################
1253
+
1254
+
1255
+ class multigamma(Function):
1256
+ r"""
1257
+ The multivariate gamma function is a generalization of the gamma function
1258
+
1259
+ .. math::
1260
+ \Gamma_p(z) = \pi^{p(p-1)/4}\prod_{k=1}^p \Gamma[z + (1 - k)/2].
1261
+
1262
+ In a special case, ``multigamma(x, 1) = gamma(x)``.
1263
+
1264
+ Examples
1265
+ ========
1266
+
1267
+ >>> from sympy import S, multigamma
1268
+ >>> from sympy import Symbol
1269
+ >>> x = Symbol('x')
1270
+ >>> p = Symbol('p', positive=True, integer=True)
1271
+
1272
+ >>> multigamma(x, p)
1273
+ pi**(p*(p - 1)/4)*Product(gamma(-_k/2 + x + 1/2), (_k, 1, p))
1274
+
1275
+ Several special values are known:
1276
+
1277
+ >>> multigamma(1, 1)
1278
+ 1
1279
+ >>> multigamma(4, 1)
1280
+ 6
1281
+ >>> multigamma(S(3)/2, 1)
1282
+ sqrt(pi)/2
1283
+
1284
+ Writing ``multigamma`` in terms of the ``gamma`` function:
1285
+
1286
+ >>> multigamma(x, 1)
1287
+ gamma(x)
1288
+
1289
+ >>> multigamma(x, 2)
1290
+ sqrt(pi)*gamma(x)*gamma(x - 1/2)
1291
+
1292
+ >>> multigamma(x, 3)
1293
+ pi**(3/2)*gamma(x)*gamma(x - 1)*gamma(x - 1/2)
1294
+
1295
+ Parameters
1296
+ ==========
1297
+
1298
+ p : order or dimension of the multivariate gamma function
1299
+
1300
+ See Also
1301
+ ========
1302
+
1303
+ gamma, lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma,
1304
+ beta
1305
+
1306
+ References
1307
+ ==========
1308
+
1309
+ .. [1] https://en.wikipedia.org/wiki/Multivariate_gamma_function
1310
+
1311
+ """
1312
+ unbranched = True
1313
+
1314
+ def fdiff(self, argindex=2):
1315
+ from sympy.concrete.summations import Sum
1316
+ if argindex == 2:
1317
+ x, p = self.args
1318
+ k = Dummy("k")
1319
+ return self.func(x, p)*Sum(polygamma(0, x + (1 - k)/2), (k, 1, p))
1320
+ else:
1321
+ raise ArgumentIndexError(self, argindex)
1322
+
1323
+ @classmethod
1324
+ def eval(cls, x, p):
1325
+ from sympy.concrete.products import Product
1326
+ if p.is_positive is False or p.is_integer is False:
1327
+ raise ValueError('Order parameter p must be positive integer.')
1328
+ k = Dummy("k")
1329
+ return (pi**(p*(p - 1)/4)*Product(gamma(x + (1 - k)/2),
1330
+ (k, 1, p))).doit()
1331
+
1332
+ def _eval_conjugate(self):
1333
+ x, p = self.args
1334
+ return self.func(x.conjugate(), p)
1335
+
1336
+ def _eval_is_real(self):
1337
+ x, p = self.args
1338
+ y = 2*x
1339
+ if y.is_integer and (y <= (p - 1)) is True:
1340
+ return False
1341
+ if intlike(y) and (y <= (p - 1)):
1342
+ return False
1343
+ if y > (p - 1) or y.is_noninteger:
1344
+ return True
venv/lib/python3.10/site-packages/sympy/functions/special/hyper.py ADDED
@@ -0,0 +1,1152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hypergeometric and Meijer G-functions"""
2
+ from functools import reduce
3
+
4
+ from sympy.core import S, ilcm, Mod
5
+ from sympy.core.add import Add
6
+ from sympy.core.expr import Expr
7
+ from sympy.core.function import Function, Derivative, ArgumentIndexError
8
+
9
+ from sympy.core.containers import Tuple
10
+ from sympy.core.mul import Mul
11
+ from sympy.core.numbers import I, pi, oo, zoo
12
+ from sympy.core.relational import Ne
13
+ from sympy.core.sorting import default_sort_key
14
+ from sympy.core.symbol import Dummy
15
+
16
+ from sympy.functions import (sqrt, exp, log, sin, cos, asin, atan,
17
+ sinh, cosh, asinh, acosh, atanh, acoth)
18
+ from sympy.functions import factorial, RisingFactorial
19
+ from sympy.functions.elementary.complexes import Abs, re, unpolarify
20
+ from sympy.functions.elementary.exponential import exp_polar
21
+ from sympy.functions.elementary.integers import ceiling
22
+ from sympy.functions.elementary.piecewise import Piecewise
23
+ from sympy.logic.boolalg import (And, Or)
24
+
25
+ class TupleArg(Tuple):
26
+ def limit(self, x, xlim, dir='+'):
27
+ """ Compute limit x->xlim.
28
+ """
29
+ from sympy.series.limits import limit
30
+ return TupleArg(*[limit(f, x, xlim, dir) for f in self.args])
31
+
32
+
33
+ # TODO should __new__ accept **options?
34
+ # TODO should constructors should check if parameters are sensible?
35
+
36
+
37
+ def _prep_tuple(v):
38
+ """
39
+ Turn an iterable argument *v* into a tuple and unpolarify, since both
40
+ hypergeometric and meijer g-functions are unbranched in their parameters.
41
+
42
+ Examples
43
+ ========
44
+
45
+ >>> from sympy.functions.special.hyper import _prep_tuple
46
+ >>> _prep_tuple([1, 2, 3])
47
+ (1, 2, 3)
48
+ >>> _prep_tuple((4, 5))
49
+ (4, 5)
50
+ >>> _prep_tuple((7, 8, 9))
51
+ (7, 8, 9)
52
+
53
+ """
54
+ return TupleArg(*[unpolarify(x) for x in v])
55
+
56
+
57
+ class TupleParametersBase(Function):
58
+ """ Base class that takes care of differentiation, when some of
59
+ the arguments are actually tuples. """
60
+ # This is not deduced automatically since there are Tuples as arguments.
61
+ is_commutative = True
62
+
63
+ def _eval_derivative(self, s):
64
+ try:
65
+ res = 0
66
+ if self.args[0].has(s) or self.args[1].has(s):
67
+ for i, p in enumerate(self._diffargs):
68
+ m = self._diffargs[i].diff(s)
69
+ if m != 0:
70
+ res += self.fdiff((1, i))*m
71
+ return res + self.fdiff(3)*self.args[2].diff(s)
72
+ except (ArgumentIndexError, NotImplementedError):
73
+ return Derivative(self, s)
74
+
75
+
76
+ class hyper(TupleParametersBase):
77
+ r"""
78
+ The generalized hypergeometric function is defined by a series where
79
+ the ratios of successive terms are a rational function of the summation
80
+ index. When convergent, it is continued analytically to the largest
81
+ possible domain.
82
+
83
+ Explanation
84
+ ===========
85
+
86
+ The hypergeometric function depends on two vectors of parameters, called
87
+ the numerator parameters $a_p$, and the denominator parameters
88
+ $b_q$. It also has an argument $z$. The series definition is
89
+
90
+ .. math ::
91
+ {}_pF_q\left(\begin{matrix} a_1, \cdots, a_p \\ b_1, \cdots, b_q \end{matrix}
92
+ \middle| z \right)
93
+ = \sum_{n=0}^\infty \frac{(a_1)_n \cdots (a_p)_n}{(b_1)_n \cdots (b_q)_n}
94
+ \frac{z^n}{n!},
95
+
96
+ where $(a)_n = (a)(a+1)\cdots(a+n-1)$ denotes the rising factorial.
97
+
98
+ If one of the $b_q$ is a non-positive integer then the series is
99
+ undefined unless one of the $a_p$ is a larger (i.e., smaller in
100
+ magnitude) non-positive integer. If none of the $b_q$ is a
101
+ non-positive integer and one of the $a_p$ is a non-positive
102
+ integer, then the series reduces to a polynomial. To simplify the
103
+ following discussion, we assume that none of the $a_p$ or
104
+ $b_q$ is a non-positive integer. For more details, see the
105
+ references.
106
+
107
+ The series converges for all $z$ if $p \le q$, and thus
108
+ defines an entire single-valued function in this case. If $p =
109
+ q+1$ the series converges for $|z| < 1$, and can be continued
110
+ analytically into a half-plane. If $p > q+1$ the series is
111
+ divergent for all $z$.
112
+
113
+ Please note the hypergeometric function constructor currently does *not*
114
+ check if the parameters actually yield a well-defined function.
115
+
116
+ Examples
117
+ ========
118
+
119
+ The parameters $a_p$ and $b_q$ can be passed as arbitrary
120
+ iterables, for example:
121
+
122
+ >>> from sympy import hyper
123
+ >>> from sympy.abc import x, n, a
124
+ >>> hyper((1, 2, 3), [3, 4], x)
125
+ hyper((1, 2, 3), (3, 4), x)
126
+
127
+ There is also pretty printing (it looks better using Unicode):
128
+
129
+ >>> from sympy import pprint
130
+ >>> pprint(hyper((1, 2, 3), [3, 4], x), use_unicode=False)
131
+ _
132
+ |_ /1, 2, 3 | \
133
+ | | | x|
134
+ 3 2 \ 3, 4 | /
135
+
136
+ The parameters must always be iterables, even if they are vectors of
137
+ length one or zero:
138
+
139
+ >>> hyper((1, ), [], x)
140
+ hyper((1,), (), x)
141
+
142
+ But of course they may be variables (but if they depend on $x$ then you
143
+ should not expect much implemented functionality):
144
+
145
+ >>> hyper((n, a), (n**2,), x)
146
+ hyper((n, a), (n**2,), x)
147
+
148
+ The hypergeometric function generalizes many named special functions.
149
+ The function ``hyperexpand()`` tries to express a hypergeometric function
150
+ using named special functions. For example:
151
+
152
+ >>> from sympy import hyperexpand
153
+ >>> hyperexpand(hyper([], [], x))
154
+ exp(x)
155
+
156
+ You can also use ``expand_func()``:
157
+
158
+ >>> from sympy import expand_func
159
+ >>> expand_func(x*hyper([1, 1], [2], -x))
160
+ log(x + 1)
161
+
162
+ More examples:
163
+
164
+ >>> from sympy import S
165
+ >>> hyperexpand(hyper([], [S(1)/2], -x**2/4))
166
+ cos(x)
167
+ >>> hyperexpand(x*hyper([S(1)/2, S(1)/2], [S(3)/2], x**2))
168
+ asin(x)
169
+
170
+ We can also sometimes ``hyperexpand()`` parametric functions:
171
+
172
+ >>> from sympy.abc import a
173
+ >>> hyperexpand(hyper([-a], [], x))
174
+ (1 - x)**a
175
+
176
+ See Also
177
+ ========
178
+
179
+ sympy.simplify.hyperexpand
180
+ gamma
181
+ meijerg
182
+
183
+ References
184
+ ==========
185
+
186
+ .. [1] Luke, Y. L. (1969), The Special Functions and Their Approximations,
187
+ Volume 1
188
+ .. [2] https://en.wikipedia.org/wiki/Generalized_hypergeometric_function
189
+
190
+ """
191
+
192
+
193
+ def __new__(cls, ap, bq, z, **kwargs):
194
+ # TODO should we check convergence conditions?
195
+ return Function.__new__(cls, _prep_tuple(ap), _prep_tuple(bq), z, **kwargs)
196
+
197
+ @classmethod
198
+ def eval(cls, ap, bq, z):
199
+ if len(ap) <= len(bq) or (len(ap) == len(bq) + 1 and (Abs(z) <= 1) == True):
200
+ nz = unpolarify(z)
201
+ if z != nz:
202
+ return hyper(ap, bq, nz)
203
+
204
+ def fdiff(self, argindex=3):
205
+ if argindex != 3:
206
+ raise ArgumentIndexError(self, argindex)
207
+ nap = Tuple(*[a + 1 for a in self.ap])
208
+ nbq = Tuple(*[b + 1 for b in self.bq])
209
+ fac = Mul(*self.ap)/Mul(*self.bq)
210
+ return fac*hyper(nap, nbq, self.argument)
211
+
212
+ def _eval_expand_func(self, **hints):
213
+ from sympy.functions.special.gamma_functions import gamma
214
+ from sympy.simplify.hyperexpand import hyperexpand
215
+ if len(self.ap) == 2 and len(self.bq) == 1 and self.argument == 1:
216
+ a, b = self.ap
217
+ c = self.bq[0]
218
+ return gamma(c)*gamma(c - a - b)/gamma(c - a)/gamma(c - b)
219
+ return hyperexpand(self)
220
+
221
+ def _eval_rewrite_as_Sum(self, ap, bq, z, **kwargs):
222
+ from sympy.concrete.summations import Sum
223
+ n = Dummy("n", integer=True)
224
+ rfap = [RisingFactorial(a, n) for a in ap]
225
+ rfbq = [RisingFactorial(b, n) for b in bq]
226
+ coeff = Mul(*rfap) / Mul(*rfbq)
227
+ return Piecewise((Sum(coeff * z**n / factorial(n), (n, 0, oo)),
228
+ self.convergence_statement), (self, True))
229
+
230
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
231
+ arg = self.args[2]
232
+ x0 = arg.subs(x, 0)
233
+ if x0 is S.NaN:
234
+ x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
235
+
236
+ if x0 is S.Zero:
237
+ return S.One
238
+ return super()._eval_as_leading_term(x, logx=logx, cdir=cdir)
239
+
240
+ def _eval_nseries(self, x, n, logx, cdir=0):
241
+
242
+ from sympy.series.order import Order
243
+
244
+ arg = self.args[2]
245
+ x0 = arg.limit(x, 0)
246
+ ap = self.args[0]
247
+ bq = self.args[1]
248
+
249
+ if x0 != 0:
250
+ return super()._eval_nseries(x, n, logx)
251
+
252
+ terms = []
253
+
254
+ for i in range(n):
255
+ num = Mul(*[RisingFactorial(a, i) for a in ap])
256
+ den = Mul(*[RisingFactorial(b, i) for b in bq])
257
+ terms.append(((num/den) * (arg**i)) / factorial(i))
258
+
259
+ return (Add(*terms) + Order(x**n,x))
260
+
261
+ @property
262
+ def argument(self):
263
+ """ Argument of the hypergeometric function. """
264
+ return self.args[2]
265
+
266
+ @property
267
+ def ap(self):
268
+ """ Numerator parameters of the hypergeometric function. """
269
+ return Tuple(*self.args[0])
270
+
271
+ @property
272
+ def bq(self):
273
+ """ Denominator parameters of the hypergeometric function. """
274
+ return Tuple(*self.args[1])
275
+
276
+ @property
277
+ def _diffargs(self):
278
+ return self.ap + self.bq
279
+
280
+ @property
281
+ def eta(self):
282
+ """ A quantity related to the convergence of the series. """
283
+ return sum(self.ap) - sum(self.bq)
284
+
285
+ @property
286
+ def radius_of_convergence(self):
287
+ """
288
+ Compute the radius of convergence of the defining series.
289
+
290
+ Explanation
291
+ ===========
292
+
293
+ Note that even if this is not ``oo``, the function may still be
294
+ evaluated outside of the radius of convergence by analytic
295
+ continuation. But if this is zero, then the function is not actually
296
+ defined anywhere else.
297
+
298
+ Examples
299
+ ========
300
+
301
+ >>> from sympy import hyper
302
+ >>> from sympy.abc import z
303
+ >>> hyper((1, 2), [3], z).radius_of_convergence
304
+ 1
305
+ >>> hyper((1, 2, 3), [4], z).radius_of_convergence
306
+ 0
307
+ >>> hyper((1, 2), (3, 4), z).radius_of_convergence
308
+ oo
309
+
310
+ """
311
+ if any(a.is_integer and (a <= 0) == True for a in self.ap + self.bq):
312
+ aints = [a for a in self.ap if a.is_Integer and (a <= 0) == True]
313
+ bints = [a for a in self.bq if a.is_Integer and (a <= 0) == True]
314
+ if len(aints) < len(bints):
315
+ return S.Zero
316
+ popped = False
317
+ for b in bints:
318
+ cancelled = False
319
+ while aints:
320
+ a = aints.pop()
321
+ if a >= b:
322
+ cancelled = True
323
+ break
324
+ popped = True
325
+ if not cancelled:
326
+ return S.Zero
327
+ if aints or popped:
328
+ # There are still non-positive numerator parameters.
329
+ # This is a polynomial.
330
+ return oo
331
+ if len(self.ap) == len(self.bq) + 1:
332
+ return S.One
333
+ elif len(self.ap) <= len(self.bq):
334
+ return oo
335
+ else:
336
+ return S.Zero
337
+
338
+ @property
339
+ def convergence_statement(self):
340
+ """ Return a condition on z under which the series converges. """
341
+ R = self.radius_of_convergence
342
+ if R == 0:
343
+ return False
344
+ if R == oo:
345
+ return True
346
+ # The special functions and their approximations, page 44
347
+ e = self.eta
348
+ z = self.argument
349
+ c1 = And(re(e) < 0, abs(z) <= 1)
350
+ c2 = And(0 <= re(e), re(e) < 1, abs(z) <= 1, Ne(z, 1))
351
+ c3 = And(re(e) >= 1, abs(z) < 1)
352
+ return Or(c1, c2, c3)
353
+
354
+ def _eval_simplify(self, **kwargs):
355
+ from sympy.simplify.hyperexpand import hyperexpand
356
+ return hyperexpand(self)
357
+
358
+
359
+ class meijerg(TupleParametersBase):
360
+ r"""
361
+ The Meijer G-function is defined by a Mellin-Barnes type integral that
362
+ resembles an inverse Mellin transform. It generalizes the hypergeometric
363
+ functions.
364
+
365
+ Explanation
366
+ ===========
367
+
368
+ The Meijer G-function depends on four sets of parameters. There are
369
+ "*numerator parameters*"
370
+ $a_1, \ldots, a_n$ and $a_{n+1}, \ldots, a_p$, and there are
371
+ "*denominator parameters*"
372
+ $b_1, \ldots, b_m$ and $b_{m+1}, \ldots, b_q$.
373
+ Confusingly, it is traditionally denoted as follows (note the position
374
+ of $m$, $n$, $p$, $q$, and how they relate to the lengths of the four
375
+ parameter vectors):
376
+
377
+ .. math ::
378
+ G_{p,q}^{m,n} \left(\begin{matrix}a_1, \cdots, a_n & a_{n+1}, \cdots, a_p \\
379
+ b_1, \cdots, b_m & b_{m+1}, \cdots, b_q
380
+ \end{matrix} \middle| z \right).
381
+
382
+ However, in SymPy the four parameter vectors are always available
383
+ separately (see examples), so that there is no need to keep track of the
384
+ decorating sub- and super-scripts on the G symbol.
385
+
386
+ The G function is defined as the following integral:
387
+
388
+ .. math ::
389
+ \frac{1}{2 \pi i} \int_L \frac{\prod_{j=1}^m \Gamma(b_j - s)
390
+ \prod_{j=1}^n \Gamma(1 - a_j + s)}{\prod_{j=m+1}^q \Gamma(1- b_j +s)
391
+ \prod_{j=n+1}^p \Gamma(a_j - s)} z^s \mathrm{d}s,
392
+
393
+ where $\Gamma(z)$ is the gamma function. There are three possible
394
+ contours which we will not describe in detail here (see the references).
395
+ If the integral converges along more than one of them, the definitions
396
+ agree. The contours all separate the poles of $\Gamma(1-a_j+s)$
397
+ from the poles of $\Gamma(b_k-s)$, so in particular the G function
398
+ is undefined if $a_j - b_k \in \mathbb{Z}_{>0}$ for some
399
+ $j \le n$ and $k \le m$.
400
+
401
+ The conditions under which one of the contours yields a convergent integral
402
+ are complicated and we do not state them here, see the references.
403
+
404
+ Please note currently the Meijer G-function constructor does *not* check any
405
+ convergence conditions.
406
+
407
+ Examples
408
+ ========
409
+
410
+ You can pass the parameters either as four separate vectors:
411
+
412
+ >>> from sympy import meijerg, Tuple, pprint
413
+ >>> from sympy.abc import x, a
414
+ >>> pprint(meijerg((1, 2), (a, 4), (5,), [], x), use_unicode=False)
415
+ __1, 2 /1, 2 a, 4 | \
416
+ /__ | | x|
417
+ \_|4, 1 \ 5 | /
418
+
419
+ Or as two nested vectors:
420
+
421
+ >>> pprint(meijerg([(1, 2), (3, 4)], ([5], Tuple()), x), use_unicode=False)
422
+ __1, 2 /1, 2 3, 4 | \
423
+ /__ | | x|
424
+ \_|4, 1 \ 5 | /
425
+
426
+ As with the hypergeometric function, the parameters may be passed as
427
+ arbitrary iterables. Vectors of length zero and one also have to be
428
+ passed as iterables. The parameters need not be constants, but if they
429
+ depend on the argument then not much implemented functionality should be
430
+ expected.
431
+
432
+ All the subvectors of parameters are available:
433
+
434
+ >>> from sympy import pprint
435
+ >>> g = meijerg([1], [2], [3], [4], x)
436
+ >>> pprint(g, use_unicode=False)
437
+ __1, 1 /1 2 | \
438
+ /__ | | x|
439
+ \_|2, 2 \3 4 | /
440
+ >>> g.an
441
+ (1,)
442
+ >>> g.ap
443
+ (1, 2)
444
+ >>> g.aother
445
+ (2,)
446
+ >>> g.bm
447
+ (3,)
448
+ >>> g.bq
449
+ (3, 4)
450
+ >>> g.bother
451
+ (4,)
452
+
453
+ The Meijer G-function generalizes the hypergeometric functions.
454
+ In some cases it can be expressed in terms of hypergeometric functions,
455
+ using Slater's theorem. For example:
456
+
457
+ >>> from sympy import hyperexpand
458
+ >>> from sympy.abc import a, b, c
459
+ >>> hyperexpand(meijerg([a], [], [c], [b], x), allow_hyper=True)
460
+ x**c*gamma(-a + c + 1)*hyper((-a + c + 1,),
461
+ (-b + c + 1,), -x)/gamma(-b + c + 1)
462
+
463
+ Thus the Meijer G-function also subsumes many named functions as special
464
+ cases. You can use ``expand_func()`` or ``hyperexpand()`` to (try to)
465
+ rewrite a Meijer G-function in terms of named special functions. For
466
+ example:
467
+
468
+ >>> from sympy import expand_func, S
469
+ >>> expand_func(meijerg([[],[]], [[0],[]], -x))
470
+ exp(x)
471
+ >>> hyperexpand(meijerg([[],[]], [[S(1)/2],[0]], (x/2)**2))
472
+ sin(x)/sqrt(pi)
473
+
474
+ See Also
475
+ ========
476
+
477
+ hyper
478
+ sympy.simplify.hyperexpand
479
+
480
+ References
481
+ ==========
482
+
483
+ .. [1] Luke, Y. L. (1969), The Special Functions and Their Approximations,
484
+ Volume 1
485
+ .. [2] https://en.wikipedia.org/wiki/Meijer_G-function
486
+
487
+ """
488
+
489
+
490
+ def __new__(cls, *args, **kwargs):
491
+ if len(args) == 5:
492
+ args = [(args[0], args[1]), (args[2], args[3]), args[4]]
493
+ if len(args) != 3:
494
+ raise TypeError("args must be either as, as', bs, bs', z or "
495
+ "as, bs, z")
496
+
497
+ def tr(p):
498
+ if len(p) != 2:
499
+ raise TypeError("wrong argument")
500
+ return TupleArg(_prep_tuple(p[0]), _prep_tuple(p[1]))
501
+
502
+ arg0, arg1 = tr(args[0]), tr(args[1])
503
+ if Tuple(arg0, arg1).has(oo, zoo, -oo):
504
+ raise ValueError("G-function parameters must be finite")
505
+ if any((a - b).is_Integer and a - b > 0
506
+ for a in arg0[0] for b in arg1[0]):
507
+ raise ValueError("no parameter a1, ..., an may differ from "
508
+ "any b1, ..., bm by a positive integer")
509
+
510
+ # TODO should we check convergence conditions?
511
+ return Function.__new__(cls, arg0, arg1, args[2], **kwargs)
512
+
513
+ def fdiff(self, argindex=3):
514
+ if argindex != 3:
515
+ return self._diff_wrt_parameter(argindex[1])
516
+ if len(self.an) >= 1:
517
+ a = list(self.an)
518
+ a[0] -= 1
519
+ G = meijerg(a, self.aother, self.bm, self.bother, self.argument)
520
+ return 1/self.argument * ((self.an[0] - 1)*self + G)
521
+ elif len(self.bm) >= 1:
522
+ b = list(self.bm)
523
+ b[0] += 1
524
+ G = meijerg(self.an, self.aother, b, self.bother, self.argument)
525
+ return 1/self.argument * (self.bm[0]*self - G)
526
+ else:
527
+ return S.Zero
528
+
529
+ def _diff_wrt_parameter(self, idx):
530
+ # Differentiation wrt a parameter can only be done in very special
531
+ # cases. In particular, if we want to differentiate with respect to
532
+ # `a`, all other gamma factors have to reduce to rational functions.
533
+ #
534
+ # Let MT denote mellin transform. Suppose T(-s) is the gamma factor
535
+ # appearing in the definition of G. Then
536
+ #
537
+ # MT(log(z)G(z)) = d/ds T(s) = d/da T(s) + ...
538
+ #
539
+ # Thus d/da G(z) = log(z)G(z) - ...
540
+ # The ... can be evaluated as a G function under the above conditions,
541
+ # the formula being most easily derived by using
542
+ #
543
+ # d Gamma(s + n) Gamma(s + n) / 1 1 1 \
544
+ # -- ------------ = ------------ | - + ---- + ... + --------- |
545
+ # ds Gamma(s) Gamma(s) \ s s + 1 s + n - 1 /
546
+ #
547
+ # which follows from the difference equation of the digamma function.
548
+ # (There is a similar equation for -n instead of +n).
549
+
550
+ # We first figure out how to pair the parameters.
551
+ an = list(self.an)
552
+ ap = list(self.aother)
553
+ bm = list(self.bm)
554
+ bq = list(self.bother)
555
+ if idx < len(an):
556
+ an.pop(idx)
557
+ else:
558
+ idx -= len(an)
559
+ if idx < len(ap):
560
+ ap.pop(idx)
561
+ else:
562
+ idx -= len(ap)
563
+ if idx < len(bm):
564
+ bm.pop(idx)
565
+ else:
566
+ bq.pop(idx - len(bm))
567
+ pairs1 = []
568
+ pairs2 = []
569
+ for l1, l2, pairs in [(an, bq, pairs1), (ap, bm, pairs2)]:
570
+ while l1:
571
+ x = l1.pop()
572
+ found = None
573
+ for i, y in enumerate(l2):
574
+ if not Mod((x - y).simplify(), 1):
575
+ found = i
576
+ break
577
+ if found is None:
578
+ raise NotImplementedError('Derivative not expressible '
579
+ 'as G-function?')
580
+ y = l2[i]
581
+ l2.pop(i)
582
+ pairs.append((x, y))
583
+
584
+ # Now build the result.
585
+ res = log(self.argument)*self
586
+
587
+ for a, b in pairs1:
588
+ sign = 1
589
+ n = a - b
590
+ base = b
591
+ if n < 0:
592
+ sign = -1
593
+ n = b - a
594
+ base = a
595
+ for k in range(n):
596
+ res -= sign*meijerg(self.an + (base + k + 1,), self.aother,
597
+ self.bm, self.bother + (base + k + 0,),
598
+ self.argument)
599
+
600
+ for a, b in pairs2:
601
+ sign = 1
602
+ n = b - a
603
+ base = a
604
+ if n < 0:
605
+ sign = -1
606
+ n = a - b
607
+ base = b
608
+ for k in range(n):
609
+ res -= sign*meijerg(self.an, self.aother + (base + k + 1,),
610
+ self.bm + (base + k + 0,), self.bother,
611
+ self.argument)
612
+
613
+ return res
614
+
615
+ def get_period(self):
616
+ """
617
+ Return a number $P$ such that $G(x*exp(I*P)) == G(x)$.
618
+
619
+ Examples
620
+ ========
621
+
622
+ >>> from sympy import meijerg, pi, S
623
+ >>> from sympy.abc import z
624
+
625
+ >>> meijerg([1], [], [], [], z).get_period()
626
+ 2*pi
627
+ >>> meijerg([pi], [], [], [], z).get_period()
628
+ oo
629
+ >>> meijerg([1, 2], [], [], [], z).get_period()
630
+ oo
631
+ >>> meijerg([1,1], [2], [1, S(1)/2, S(1)/3], [1], z).get_period()
632
+ 12*pi
633
+
634
+ """
635
+ # This follows from slater's theorem.
636
+ def compute(l):
637
+ # first check that no two differ by an integer
638
+ for i, b in enumerate(l):
639
+ if not b.is_Rational:
640
+ return oo
641
+ for j in range(i + 1, len(l)):
642
+ if not Mod((b - l[j]).simplify(), 1):
643
+ return oo
644
+ return reduce(ilcm, (x.q for x in l), 1)
645
+ beta = compute(self.bm)
646
+ alpha = compute(self.an)
647
+ p, q = len(self.ap), len(self.bq)
648
+ if p == q:
649
+ if oo in (alpha, beta):
650
+ return oo
651
+ return 2*pi*ilcm(alpha, beta)
652
+ elif p < q:
653
+ return 2*pi*beta
654
+ else:
655
+ return 2*pi*alpha
656
+
657
+ def _eval_expand_func(self, **hints):
658
+ from sympy.simplify.hyperexpand import hyperexpand
659
+ return hyperexpand(self)
660
+
661
+ def _eval_evalf(self, prec):
662
+ # The default code is insufficient for polar arguments.
663
+ # mpmath provides an optional argument "r", which evaluates
664
+ # G(z**(1/r)). I am not sure what its intended use is, but we hijack it
665
+ # here in the following way: to evaluate at a number z of |argument|
666
+ # less than (say) n*pi, we put r=1/n, compute z' = root(z, n)
667
+ # (carefully so as not to loose the branch information), and evaluate
668
+ # G(z'**(1/r)) = G(z'**n) = G(z).
669
+ import mpmath
670
+ znum = self.argument._eval_evalf(prec)
671
+ if znum.has(exp_polar):
672
+ znum, branch = znum.as_coeff_mul(exp_polar)
673
+ if len(branch) != 1:
674
+ return
675
+ branch = branch[0].args[0]/I
676
+ else:
677
+ branch = S.Zero
678
+ n = ceiling(abs(branch/pi)) + 1
679
+ znum = znum**(S.One/n)*exp(I*branch / n)
680
+
681
+ # Convert all args to mpf or mpc
682
+ try:
683
+ [z, r, ap, bq] = [arg._to_mpmath(prec)
684
+ for arg in [znum, 1/n, self.args[0], self.args[1]]]
685
+ except ValueError:
686
+ return
687
+
688
+ with mpmath.workprec(prec):
689
+ v = mpmath.meijerg(ap, bq, z, r)
690
+
691
+ return Expr._from_mpmath(v, prec)
692
+
693
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
694
+ from sympy.simplify.hyperexpand import hyperexpand
695
+ return hyperexpand(self).as_leading_term(x, logx=logx, cdir=cdir)
696
+
697
+ def integrand(self, s):
698
+ """ Get the defining integrand D(s). """
699
+ from sympy.functions.special.gamma_functions import gamma
700
+ return self.argument**s \
701
+ * Mul(*(gamma(b - s) for b in self.bm)) \
702
+ * Mul(*(gamma(1 - a + s) for a in self.an)) \
703
+ / Mul(*(gamma(1 - b + s) for b in self.bother)) \
704
+ / Mul(*(gamma(a - s) for a in self.aother))
705
+
706
+ @property
707
+ def argument(self):
708
+ """ Argument of the Meijer G-function. """
709
+ return self.args[2]
710
+
711
+ @property
712
+ def an(self):
713
+ """ First set of numerator parameters. """
714
+ return Tuple(*self.args[0][0])
715
+
716
+ @property
717
+ def ap(self):
718
+ """ Combined numerator parameters. """
719
+ return Tuple(*(self.args[0][0] + self.args[0][1]))
720
+
721
+ @property
722
+ def aother(self):
723
+ """ Second set of numerator parameters. """
724
+ return Tuple(*self.args[0][1])
725
+
726
+ @property
727
+ def bm(self):
728
+ """ First set of denominator parameters. """
729
+ return Tuple(*self.args[1][0])
730
+
731
+ @property
732
+ def bq(self):
733
+ """ Combined denominator parameters. """
734
+ return Tuple(*(self.args[1][0] + self.args[1][1]))
735
+
736
+ @property
737
+ def bother(self):
738
+ """ Second set of denominator parameters. """
739
+ return Tuple(*self.args[1][1])
740
+
741
+ @property
742
+ def _diffargs(self):
743
+ return self.ap + self.bq
744
+
745
+ @property
746
+ def nu(self):
747
+ """ A quantity related to the convergence region of the integral,
748
+ c.f. references. """
749
+ return sum(self.bq) - sum(self.ap)
750
+
751
+ @property
752
+ def delta(self):
753
+ """ A quantity related to the convergence region of the integral,
754
+ c.f. references. """
755
+ return len(self.bm) + len(self.an) - S(len(self.ap) + len(self.bq))/2
756
+
757
+ @property
758
+ def is_number(self):
759
+ """ Returns true if expression has numeric data only. """
760
+ return not self.free_symbols
761
+
762
+
763
+ class HyperRep(Function):
764
+ """
765
+ A base class for "hyper representation functions".
766
+
767
+ This is used exclusively in ``hyperexpand()``, but fits more logically here.
768
+
769
+ pFq is branched at 1 if p == q+1. For use with slater-expansion, we want
770
+ define an "analytic continuation" to all polar numbers, which is
771
+ continuous on circles and on the ray t*exp_polar(I*pi). Moreover, we want
772
+ a "nice" expression for the various cases.
773
+
774
+ This base class contains the core logic, concrete derived classes only
775
+ supply the actual functions.
776
+
777
+ """
778
+
779
+
780
+ @classmethod
781
+ def eval(cls, *args):
782
+ newargs = tuple(map(unpolarify, args[:-1])) + args[-1:]
783
+ if args != newargs:
784
+ return cls(*newargs)
785
+
786
+ @classmethod
787
+ def _expr_small(cls, x):
788
+ """ An expression for F(x) which holds for |x| < 1. """
789
+ raise NotImplementedError
790
+
791
+ @classmethod
792
+ def _expr_small_minus(cls, x):
793
+ """ An expression for F(-x) which holds for |x| < 1. """
794
+ raise NotImplementedError
795
+
796
+ @classmethod
797
+ def _expr_big(cls, x, n):
798
+ """ An expression for F(exp_polar(2*I*pi*n)*x), |x| > 1. """
799
+ raise NotImplementedError
800
+
801
+ @classmethod
802
+ def _expr_big_minus(cls, x, n):
803
+ """ An expression for F(exp_polar(2*I*pi*n + pi*I)*x), |x| > 1. """
804
+ raise NotImplementedError
805
+
806
+ def _eval_rewrite_as_nonrep(self, *args, **kwargs):
807
+ x, n = self.args[-1].extract_branch_factor(allow_half=True)
808
+ minus = False
809
+ newargs = self.args[:-1] + (x,)
810
+ if not n.is_Integer:
811
+ minus = True
812
+ n -= S.Half
813
+ newerargs = newargs + (n,)
814
+ if minus:
815
+ small = self._expr_small_minus(*newargs)
816
+ big = self._expr_big_minus(*newerargs)
817
+ else:
818
+ small = self._expr_small(*newargs)
819
+ big = self._expr_big(*newerargs)
820
+
821
+ if big == small:
822
+ return small
823
+ return Piecewise((big, abs(x) > 1), (small, True))
824
+
825
+ def _eval_rewrite_as_nonrepsmall(self, *args, **kwargs):
826
+ x, n = self.args[-1].extract_branch_factor(allow_half=True)
827
+ args = self.args[:-1] + (x,)
828
+ if not n.is_Integer:
829
+ return self._expr_small_minus(*args)
830
+ return self._expr_small(*args)
831
+
832
+
833
+ class HyperRep_power1(HyperRep):
834
+ """ Return a representative for hyper([-a], [], z) == (1 - z)**a. """
835
+
836
+ @classmethod
837
+ def _expr_small(cls, a, x):
838
+ return (1 - x)**a
839
+
840
+ @classmethod
841
+ def _expr_small_minus(cls, a, x):
842
+ return (1 + x)**a
843
+
844
+ @classmethod
845
+ def _expr_big(cls, a, x, n):
846
+ if a.is_integer:
847
+ return cls._expr_small(a, x)
848
+ return (x - 1)**a*exp((2*n - 1)*pi*I*a)
849
+
850
+ @classmethod
851
+ def _expr_big_minus(cls, a, x, n):
852
+ if a.is_integer:
853
+ return cls._expr_small_minus(a, x)
854
+ return (1 + x)**a*exp(2*n*pi*I*a)
855
+
856
+
857
+ class HyperRep_power2(HyperRep):
858
+ """ Return a representative for hyper([a, a - 1/2], [2*a], z). """
859
+
860
+ @classmethod
861
+ def _expr_small(cls, a, x):
862
+ return 2**(2*a - 1)*(1 + sqrt(1 - x))**(1 - 2*a)
863
+
864
+ @classmethod
865
+ def _expr_small_minus(cls, a, x):
866
+ return 2**(2*a - 1)*(1 + sqrt(1 + x))**(1 - 2*a)
867
+
868
+ @classmethod
869
+ def _expr_big(cls, a, x, n):
870
+ sgn = -1
871
+ if n.is_odd:
872
+ sgn = 1
873
+ n -= 1
874
+ return 2**(2*a - 1)*(1 + sgn*I*sqrt(x - 1))**(1 - 2*a) \
875
+ *exp(-2*n*pi*I*a)
876
+
877
+ @classmethod
878
+ def _expr_big_minus(cls, a, x, n):
879
+ sgn = 1
880
+ if n.is_odd:
881
+ sgn = -1
882
+ return sgn*2**(2*a - 1)*(sqrt(1 + x) + sgn)**(1 - 2*a)*exp(-2*pi*I*a*n)
883
+
884
+
885
+ class HyperRep_log1(HyperRep):
886
+ """ Represent -z*hyper([1, 1], [2], z) == log(1 - z). """
887
+ @classmethod
888
+ def _expr_small(cls, x):
889
+ return log(1 - x)
890
+
891
+ @classmethod
892
+ def _expr_small_minus(cls, x):
893
+ return log(1 + x)
894
+
895
+ @classmethod
896
+ def _expr_big(cls, x, n):
897
+ return log(x - 1) + (2*n - 1)*pi*I
898
+
899
+ @classmethod
900
+ def _expr_big_minus(cls, x, n):
901
+ return log(1 + x) + 2*n*pi*I
902
+
903
+
904
+ class HyperRep_atanh(HyperRep):
905
+ """ Represent hyper([1/2, 1], [3/2], z) == atanh(sqrt(z))/sqrt(z). """
906
+ @classmethod
907
+ def _expr_small(cls, x):
908
+ return atanh(sqrt(x))/sqrt(x)
909
+
910
+ def _expr_small_minus(cls, x):
911
+ return atan(sqrt(x))/sqrt(x)
912
+
913
+ def _expr_big(cls, x, n):
914
+ if n.is_even:
915
+ return (acoth(sqrt(x)) + I*pi/2)/sqrt(x)
916
+ else:
917
+ return (acoth(sqrt(x)) - I*pi/2)/sqrt(x)
918
+
919
+ def _expr_big_minus(cls, x, n):
920
+ if n.is_even:
921
+ return atan(sqrt(x))/sqrt(x)
922
+ else:
923
+ return (atan(sqrt(x)) - pi)/sqrt(x)
924
+
925
+
926
+ class HyperRep_asin1(HyperRep):
927
+ """ Represent hyper([1/2, 1/2], [3/2], z) == asin(sqrt(z))/sqrt(z). """
928
+ @classmethod
929
+ def _expr_small(cls, z):
930
+ return asin(sqrt(z))/sqrt(z)
931
+
932
+ @classmethod
933
+ def _expr_small_minus(cls, z):
934
+ return asinh(sqrt(z))/sqrt(z)
935
+
936
+ @classmethod
937
+ def _expr_big(cls, z, n):
938
+ return S.NegativeOne**n*((S.Half - n)*pi/sqrt(z) + I*acosh(sqrt(z))/sqrt(z))
939
+
940
+ @classmethod
941
+ def _expr_big_minus(cls, z, n):
942
+ return S.NegativeOne**n*(asinh(sqrt(z))/sqrt(z) + n*pi*I/sqrt(z))
943
+
944
+
945
+ class HyperRep_asin2(HyperRep):
946
+ """ Represent hyper([1, 1], [3/2], z) == asin(sqrt(z))/sqrt(z)/sqrt(1-z). """
947
+ # TODO this can be nicer
948
+ @classmethod
949
+ def _expr_small(cls, z):
950
+ return HyperRep_asin1._expr_small(z) \
951
+ /HyperRep_power1._expr_small(S.Half, z)
952
+
953
+ @classmethod
954
+ def _expr_small_minus(cls, z):
955
+ return HyperRep_asin1._expr_small_minus(z) \
956
+ /HyperRep_power1._expr_small_minus(S.Half, z)
957
+
958
+ @classmethod
959
+ def _expr_big(cls, z, n):
960
+ return HyperRep_asin1._expr_big(z, n) \
961
+ /HyperRep_power1._expr_big(S.Half, z, n)
962
+
963
+ @classmethod
964
+ def _expr_big_minus(cls, z, n):
965
+ return HyperRep_asin1._expr_big_minus(z, n) \
966
+ /HyperRep_power1._expr_big_minus(S.Half, z, n)
967
+
968
+
969
+ class HyperRep_sqrts1(HyperRep):
970
+ """ Return a representative for hyper([-a, 1/2 - a], [1/2], z). """
971
+
972
+ @classmethod
973
+ def _expr_small(cls, a, z):
974
+ return ((1 - sqrt(z))**(2*a) + (1 + sqrt(z))**(2*a))/2
975
+
976
+ @classmethod
977
+ def _expr_small_minus(cls, a, z):
978
+ return (1 + z)**a*cos(2*a*atan(sqrt(z)))
979
+
980
+ @classmethod
981
+ def _expr_big(cls, a, z, n):
982
+ if n.is_even:
983
+ return ((sqrt(z) + 1)**(2*a)*exp(2*pi*I*n*a) +
984
+ (sqrt(z) - 1)**(2*a)*exp(2*pi*I*(n - 1)*a))/2
985
+ else:
986
+ n -= 1
987
+ return ((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n + 1)) +
988
+ (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n))/2
989
+
990
+ @classmethod
991
+ def _expr_big_minus(cls, a, z, n):
992
+ if n.is_even:
993
+ return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z)))
994
+ else:
995
+ return (1 + z)**a*exp(2*pi*I*n*a)*cos(2*a*atan(sqrt(z)) - 2*pi*a)
996
+
997
+
998
+ class HyperRep_sqrts2(HyperRep):
999
+ """ Return a representative for
1000
+ sqrt(z)/2*[(1-sqrt(z))**2a - (1 + sqrt(z))**2a]
1001
+ == -2*z/(2*a+1) d/dz hyper([-a - 1/2, -a], [1/2], z)"""
1002
+
1003
+ @classmethod
1004
+ def _expr_small(cls, a, z):
1005
+ return sqrt(z)*((1 - sqrt(z))**(2*a) - (1 + sqrt(z))**(2*a))/2
1006
+
1007
+ @classmethod
1008
+ def _expr_small_minus(cls, a, z):
1009
+ return sqrt(z)*(1 + z)**a*sin(2*a*atan(sqrt(z)))
1010
+
1011
+ @classmethod
1012
+ def _expr_big(cls, a, z, n):
1013
+ if n.is_even:
1014
+ return sqrt(z)/2*((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n - 1)) -
1015
+ (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n))
1016
+ else:
1017
+ n -= 1
1018
+ return sqrt(z)/2*((sqrt(z) - 1)**(2*a)*exp(2*pi*I*a*(n + 1)) -
1019
+ (sqrt(z) + 1)**(2*a)*exp(2*pi*I*a*n))
1020
+
1021
+ def _expr_big_minus(cls, a, z, n):
1022
+ if n.is_even:
1023
+ return (1 + z)**a*exp(2*pi*I*n*a)*sqrt(z)*sin(2*a*atan(sqrt(z)))
1024
+ else:
1025
+ return (1 + z)**a*exp(2*pi*I*n*a)*sqrt(z) \
1026
+ *sin(2*a*atan(sqrt(z)) - 2*pi*a)
1027
+
1028
+
1029
+ class HyperRep_log2(HyperRep):
1030
+ """ Represent log(1/2 + sqrt(1 - z)/2) == -z/4*hyper([3/2, 1, 1], [2, 2], z) """
1031
+
1032
+ @classmethod
1033
+ def _expr_small(cls, z):
1034
+ return log(S.Half + sqrt(1 - z)/2)
1035
+
1036
+ @classmethod
1037
+ def _expr_small_minus(cls, z):
1038
+ return log(S.Half + sqrt(1 + z)/2)
1039
+
1040
+ @classmethod
1041
+ def _expr_big(cls, z, n):
1042
+ if n.is_even:
1043
+ return (n - S.Half)*pi*I + log(sqrt(z)/2) + I*asin(1/sqrt(z))
1044
+ else:
1045
+ return (n - S.Half)*pi*I + log(sqrt(z)/2) - I*asin(1/sqrt(z))
1046
+
1047
+ def _expr_big_minus(cls, z, n):
1048
+ if n.is_even:
1049
+ return pi*I*n + log(S.Half + sqrt(1 + z)/2)
1050
+ else:
1051
+ return pi*I*n + log(sqrt(1 + z)/2 - S.Half)
1052
+
1053
+
1054
+ class HyperRep_cosasin(HyperRep):
1055
+ """ Represent hyper([a, -a], [1/2], z) == cos(2*a*asin(sqrt(z))). """
1056
+ # Note there are many alternative expressions, e.g. as powers of a sum of
1057
+ # square roots.
1058
+
1059
+ @classmethod
1060
+ def _expr_small(cls, a, z):
1061
+ return cos(2*a*asin(sqrt(z)))
1062
+
1063
+ @classmethod
1064
+ def _expr_small_minus(cls, a, z):
1065
+ return cosh(2*a*asinh(sqrt(z)))
1066
+
1067
+ @classmethod
1068
+ def _expr_big(cls, a, z, n):
1069
+ return cosh(2*a*acosh(sqrt(z)) + a*pi*I*(2*n - 1))
1070
+
1071
+ @classmethod
1072
+ def _expr_big_minus(cls, a, z, n):
1073
+ return cosh(2*a*asinh(sqrt(z)) + 2*a*pi*I*n)
1074
+
1075
+
1076
+ class HyperRep_sinasin(HyperRep):
1077
+ """ Represent 2*a*z*hyper([1 - a, 1 + a], [3/2], z)
1078
+ == sqrt(z)/sqrt(1-z)*sin(2*a*asin(sqrt(z))) """
1079
+
1080
+ @classmethod
1081
+ def _expr_small(cls, a, z):
1082
+ return sqrt(z)/sqrt(1 - z)*sin(2*a*asin(sqrt(z)))
1083
+
1084
+ @classmethod
1085
+ def _expr_small_minus(cls, a, z):
1086
+ return -sqrt(z)/sqrt(1 + z)*sinh(2*a*asinh(sqrt(z)))
1087
+
1088
+ @classmethod
1089
+ def _expr_big(cls, a, z, n):
1090
+ return -1/sqrt(1 - 1/z)*sinh(2*a*acosh(sqrt(z)) + a*pi*I*(2*n - 1))
1091
+
1092
+ @classmethod
1093
+ def _expr_big_minus(cls, a, z, n):
1094
+ return -1/sqrt(1 + 1/z)*sinh(2*a*asinh(sqrt(z)) + 2*a*pi*I*n)
1095
+
1096
+ class appellf1(Function):
1097
+ r"""
1098
+ This is the Appell hypergeometric function of two variables as:
1099
+
1100
+ .. math ::
1101
+ F_1(a,b_1,b_2,c,x,y) = \sum_{m=0}^{\infty} \sum_{n=0}^{\infty}
1102
+ \frac{(a)_{m+n} (b_1)_m (b_2)_n}{(c)_{m+n}}
1103
+ \frac{x^m y^n}{m! n!}.
1104
+
1105
+ Examples
1106
+ ========
1107
+
1108
+ >>> from sympy import appellf1, symbols
1109
+ >>> x, y, a, b1, b2, c = symbols('x y a b1 b2 c')
1110
+ >>> appellf1(2., 1., 6., 4., 5., 6.)
1111
+ 0.0063339426292673
1112
+ >>> appellf1(12., 12., 6., 4., 0.5, 0.12)
1113
+ 172870711.659936
1114
+ >>> appellf1(40, 2, 6, 4, 15, 60)
1115
+ appellf1(40, 2, 6, 4, 15, 60)
1116
+ >>> appellf1(20., 12., 10., 3., 0.5, 0.12)
1117
+ 15605338197184.4
1118
+ >>> appellf1(40, 2, 6, 4, x, y)
1119
+ appellf1(40, 2, 6, 4, x, y)
1120
+ >>> appellf1(a, b1, b2, c, x, y)
1121
+ appellf1(a, b1, b2, c, x, y)
1122
+
1123
+ References
1124
+ ==========
1125
+
1126
+ .. [1] https://en.wikipedia.org/wiki/Appell_series
1127
+ .. [2] https://functions.wolfram.com/HypergeometricFunctions/AppellF1/
1128
+
1129
+ """
1130
+
1131
+ @classmethod
1132
+ def eval(cls, a, b1, b2, c, x, y):
1133
+ if default_sort_key(b1) > default_sort_key(b2):
1134
+ b1, b2 = b2, b1
1135
+ x, y = y, x
1136
+ return cls(a, b1, b2, c, x, y)
1137
+ elif b1 == b2 and default_sort_key(x) > default_sort_key(y):
1138
+ x, y = y, x
1139
+ return cls(a, b1, b2, c, x, y)
1140
+ if x == 0 and y == 0:
1141
+ return S.One
1142
+
1143
+ def fdiff(self, argindex=5):
1144
+ a, b1, b2, c, x, y = self.args
1145
+ if argindex == 5:
1146
+ return (a*b1/c)*appellf1(a + 1, b1 + 1, b2, c + 1, x, y)
1147
+ elif argindex == 6:
1148
+ return (a*b2/c)*appellf1(a + 1, b1, b2 + 1, c + 1, x, y)
1149
+ elif argindex in (1, 2, 3, 4):
1150
+ return Derivative(self, self.args[argindex-1])
1151
+ else:
1152
+ raise ArgumentIndexError(self, argindex)
venv/lib/python3.10/site-packages/sympy/functions/special/mathieu_functions.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ This module contains the Mathieu functions.
2
+ """
3
+
4
+ from sympy.core.function import Function, ArgumentIndexError
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.elementary.trigonometric import sin, cos
7
+
8
+
9
+ class MathieuBase(Function):
10
+ """
11
+ Abstract base class for Mathieu functions.
12
+
13
+ This class is meant to reduce code duplication.
14
+
15
+ """
16
+
17
+ unbranched = True
18
+
19
+ def _eval_conjugate(self):
20
+ a, q, z = self.args
21
+ return self.func(a.conjugate(), q.conjugate(), z.conjugate())
22
+
23
+
24
+ class mathieus(MathieuBase):
25
+ r"""
26
+ The Mathieu Sine function $S(a,q,z)$.
27
+
28
+ Explanation
29
+ ===========
30
+
31
+ This function is one solution of the Mathieu differential equation:
32
+
33
+ .. math ::
34
+ y(x)^{\prime\prime} + (a - 2 q \cos(2 x)) y(x) = 0
35
+
36
+ The other solution is the Mathieu Cosine function.
37
+
38
+ Examples
39
+ ========
40
+
41
+ >>> from sympy import diff, mathieus
42
+ >>> from sympy.abc import a, q, z
43
+
44
+ >>> mathieus(a, q, z)
45
+ mathieus(a, q, z)
46
+
47
+ >>> mathieus(a, 0, z)
48
+ sin(sqrt(a)*z)
49
+
50
+ >>> diff(mathieus(a, q, z), z)
51
+ mathieusprime(a, q, z)
52
+
53
+ See Also
54
+ ========
55
+
56
+ mathieuc: Mathieu cosine function.
57
+ mathieusprime: Derivative of Mathieu sine function.
58
+ mathieucprime: Derivative of Mathieu cosine function.
59
+
60
+ References
61
+ ==========
62
+
63
+ .. [1] https://en.wikipedia.org/wiki/Mathieu_function
64
+ .. [2] https://dlmf.nist.gov/28
65
+ .. [3] https://mathworld.wolfram.com/MathieuFunction.html
66
+ .. [4] https://functions.wolfram.com/MathieuandSpheroidalFunctions/MathieuS/
67
+
68
+ """
69
+
70
+ def fdiff(self, argindex=1):
71
+ if argindex == 3:
72
+ a, q, z = self.args
73
+ return mathieusprime(a, q, z)
74
+ else:
75
+ raise ArgumentIndexError(self, argindex)
76
+
77
+ @classmethod
78
+ def eval(cls, a, q, z):
79
+ if q.is_Number and q.is_zero:
80
+ return sin(sqrt(a)*z)
81
+ # Try to pull out factors of -1
82
+ if z.could_extract_minus_sign():
83
+ return -cls(a, q, -z)
84
+
85
+
86
+ class mathieuc(MathieuBase):
87
+ r"""
88
+ The Mathieu Cosine function $C(a,q,z)$.
89
+
90
+ Explanation
91
+ ===========
92
+
93
+ This function is one solution of the Mathieu differential equation:
94
+
95
+ .. math ::
96
+ y(x)^{\prime\prime} + (a - 2 q \cos(2 x)) y(x) = 0
97
+
98
+ The other solution is the Mathieu Sine function.
99
+
100
+ Examples
101
+ ========
102
+
103
+ >>> from sympy import diff, mathieuc
104
+ >>> from sympy.abc import a, q, z
105
+
106
+ >>> mathieuc(a, q, z)
107
+ mathieuc(a, q, z)
108
+
109
+ >>> mathieuc(a, 0, z)
110
+ cos(sqrt(a)*z)
111
+
112
+ >>> diff(mathieuc(a, q, z), z)
113
+ mathieucprime(a, q, z)
114
+
115
+ See Also
116
+ ========
117
+
118
+ mathieus: Mathieu sine function
119
+ mathieusprime: Derivative of Mathieu sine function
120
+ mathieucprime: Derivative of Mathieu cosine function
121
+
122
+ References
123
+ ==========
124
+
125
+ .. [1] https://en.wikipedia.org/wiki/Mathieu_function
126
+ .. [2] https://dlmf.nist.gov/28
127
+ .. [3] https://mathworld.wolfram.com/MathieuFunction.html
128
+ .. [4] https://functions.wolfram.com/MathieuandSpheroidalFunctions/MathieuC/
129
+
130
+ """
131
+
132
+ def fdiff(self, argindex=1):
133
+ if argindex == 3:
134
+ a, q, z = self.args
135
+ return mathieucprime(a, q, z)
136
+ else:
137
+ raise ArgumentIndexError(self, argindex)
138
+
139
+ @classmethod
140
+ def eval(cls, a, q, z):
141
+ if q.is_Number and q.is_zero:
142
+ return cos(sqrt(a)*z)
143
+ # Try to pull out factors of -1
144
+ if z.could_extract_minus_sign():
145
+ return cls(a, q, -z)
146
+
147
+
148
+ class mathieusprime(MathieuBase):
149
+ r"""
150
+ The derivative $S^{\prime}(a,q,z)$ of the Mathieu Sine function.
151
+
152
+ Explanation
153
+ ===========
154
+
155
+ This function is one solution of the Mathieu differential equation:
156
+
157
+ .. math ::
158
+ y(x)^{\prime\prime} + (a - 2 q \cos(2 x)) y(x) = 0
159
+
160
+ The other solution is the Mathieu Cosine function.
161
+
162
+ Examples
163
+ ========
164
+
165
+ >>> from sympy import diff, mathieusprime
166
+ >>> from sympy.abc import a, q, z
167
+
168
+ >>> mathieusprime(a, q, z)
169
+ mathieusprime(a, q, z)
170
+
171
+ >>> mathieusprime(a, 0, z)
172
+ sqrt(a)*cos(sqrt(a)*z)
173
+
174
+ >>> diff(mathieusprime(a, q, z), z)
175
+ (-a + 2*q*cos(2*z))*mathieus(a, q, z)
176
+
177
+ See Also
178
+ ========
179
+
180
+ mathieus: Mathieu sine function
181
+ mathieuc: Mathieu cosine function
182
+ mathieucprime: Derivative of Mathieu cosine function
183
+
184
+ References
185
+ ==========
186
+
187
+ .. [1] https://en.wikipedia.org/wiki/Mathieu_function
188
+ .. [2] https://dlmf.nist.gov/28
189
+ .. [3] https://mathworld.wolfram.com/MathieuFunction.html
190
+ .. [4] https://functions.wolfram.com/MathieuandSpheroidalFunctions/MathieuSPrime/
191
+
192
+ """
193
+
194
+ def fdiff(self, argindex=1):
195
+ if argindex == 3:
196
+ a, q, z = self.args
197
+ return (2*q*cos(2*z) - a)*mathieus(a, q, z)
198
+ else:
199
+ raise ArgumentIndexError(self, argindex)
200
+
201
+ @classmethod
202
+ def eval(cls, a, q, z):
203
+ if q.is_Number and q.is_zero:
204
+ return sqrt(a)*cos(sqrt(a)*z)
205
+ # Try to pull out factors of -1
206
+ if z.could_extract_minus_sign():
207
+ return cls(a, q, -z)
208
+
209
+
210
+ class mathieucprime(MathieuBase):
211
+ r"""
212
+ The derivative $C^{\prime}(a,q,z)$ of the Mathieu Cosine function.
213
+
214
+ Explanation
215
+ ===========
216
+
217
+ This function is one solution of the Mathieu differential equation:
218
+
219
+ .. math ::
220
+ y(x)^{\prime\prime} + (a - 2 q \cos(2 x)) y(x) = 0
221
+
222
+ The other solution is the Mathieu Sine function.
223
+
224
+ Examples
225
+ ========
226
+
227
+ >>> from sympy import diff, mathieucprime
228
+ >>> from sympy.abc import a, q, z
229
+
230
+ >>> mathieucprime(a, q, z)
231
+ mathieucprime(a, q, z)
232
+
233
+ >>> mathieucprime(a, 0, z)
234
+ -sqrt(a)*sin(sqrt(a)*z)
235
+
236
+ >>> diff(mathieucprime(a, q, z), z)
237
+ (-a + 2*q*cos(2*z))*mathieuc(a, q, z)
238
+
239
+ See Also
240
+ ========
241
+
242
+ mathieus: Mathieu sine function
243
+ mathieuc: Mathieu cosine function
244
+ mathieusprime: Derivative of Mathieu sine function
245
+
246
+ References
247
+ ==========
248
+
249
+ .. [1] https://en.wikipedia.org/wiki/Mathieu_function
250
+ .. [2] https://dlmf.nist.gov/28
251
+ .. [3] https://mathworld.wolfram.com/MathieuFunction.html
252
+ .. [4] https://functions.wolfram.com/MathieuandSpheroidalFunctions/MathieuCPrime/
253
+
254
+ """
255
+
256
+ def fdiff(self, argindex=1):
257
+ if argindex == 3:
258
+ a, q, z = self.args
259
+ return (2*q*cos(2*z) - a)*mathieuc(a, q, z)
260
+ else:
261
+ raise ArgumentIndexError(self, argindex)
262
+
263
+ @classmethod
264
+ def eval(cls, a, q, z):
265
+ if q.is_Number and q.is_zero:
266
+ return -sqrt(a)*sin(sqrt(a)*z)
267
+ # Try to pull out factors of -1
268
+ if z.could_extract_minus_sign():
269
+ return -cls(a, q, -z)
venv/lib/python3.10/site-packages/sympy/functions/special/polynomials.py ADDED
@@ -0,0 +1,1447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module mainly implements special orthogonal polynomials.
3
+
4
+ See also functions.combinatorial.numbers which contains some
5
+ combinatorial polynomials.
6
+
7
+ """
8
+
9
+ from sympy.core import Rational
10
+ from sympy.core.function import Function, ArgumentIndexError
11
+ from sympy.core.singleton import S
12
+ from sympy.core.symbol import Dummy
13
+ from sympy.functions.combinatorial.factorials import binomial, factorial, RisingFactorial
14
+ from sympy.functions.elementary.complexes import re
15
+ from sympy.functions.elementary.exponential import exp
16
+ from sympy.functions.elementary.integers import floor
17
+ from sympy.functions.elementary.miscellaneous import sqrt
18
+ from sympy.functions.elementary.trigonometric import cos, sec
19
+ from sympy.functions.special.gamma_functions import gamma
20
+ from sympy.functions.special.hyper import hyper
21
+ from sympy.polys.orthopolys import (chebyshevt_poly, chebyshevu_poly,
22
+ gegenbauer_poly, hermite_poly, hermite_prob_poly,
23
+ jacobi_poly, laguerre_poly, legendre_poly)
24
+
25
+ _x = Dummy('x')
26
+
27
+
28
+ class OrthogonalPolynomial(Function):
29
+ """Base class for orthogonal polynomials.
30
+ """
31
+
32
+ @classmethod
33
+ def _eval_at_order(cls, n, x):
34
+ if n.is_integer and n >= 0:
35
+ return cls._ortho_poly(int(n), _x).subs(_x, x)
36
+
37
+ def _eval_conjugate(self):
38
+ return self.func(self.args[0], self.args[1].conjugate())
39
+
40
+ #----------------------------------------------------------------------------
41
+ # Jacobi polynomials
42
+ #
43
+
44
+
45
+ class jacobi(OrthogonalPolynomial):
46
+ r"""
47
+ Jacobi polynomial $P_n^{\left(\alpha, \beta\right)}(x)$.
48
+
49
+ Explanation
50
+ ===========
51
+
52
+ ``jacobi(n, alpha, beta, x)`` gives the $n$th Jacobi polynomial
53
+ in $x$, $P_n^{\left(\alpha, \beta\right)}(x)$.
54
+
55
+ The Jacobi polynomials are orthogonal on $[-1, 1]$ with respect
56
+ to the weight $\left(1-x\right)^\alpha \left(1+x\right)^\beta$.
57
+
58
+ Examples
59
+ ========
60
+
61
+ >>> from sympy import jacobi, S, conjugate, diff
62
+ >>> from sympy.abc import a, b, n, x
63
+
64
+ >>> jacobi(0, a, b, x)
65
+ 1
66
+ >>> jacobi(1, a, b, x)
67
+ a/2 - b/2 + x*(a/2 + b/2 + 1)
68
+ >>> jacobi(2, a, b, x)
69
+ a**2/8 - a*b/4 - a/8 + b**2/8 - b/8 + x**2*(a**2/8 + a*b/4 + 7*a/8 + b**2/8 + 7*b/8 + 3/2) + x*(a**2/4 + 3*a/4 - b**2/4 - 3*b/4) - 1/2
70
+
71
+ >>> jacobi(n, a, b, x)
72
+ jacobi(n, a, b, x)
73
+
74
+ >>> jacobi(n, a, a, x)
75
+ RisingFactorial(a + 1, n)*gegenbauer(n,
76
+ a + 1/2, x)/RisingFactorial(2*a + 1, n)
77
+
78
+ >>> jacobi(n, 0, 0, x)
79
+ legendre(n, x)
80
+
81
+ >>> jacobi(n, S(1)/2, S(1)/2, x)
82
+ RisingFactorial(3/2, n)*chebyshevu(n, x)/factorial(n + 1)
83
+
84
+ >>> jacobi(n, -S(1)/2, -S(1)/2, x)
85
+ RisingFactorial(1/2, n)*chebyshevt(n, x)/factorial(n)
86
+
87
+ >>> jacobi(n, a, b, -x)
88
+ (-1)**n*jacobi(n, b, a, x)
89
+
90
+ >>> jacobi(n, a, b, 0)
91
+ gamma(a + n + 1)*hyper((-b - n, -n), (a + 1,), -1)/(2**n*factorial(n)*gamma(a + 1))
92
+ >>> jacobi(n, a, b, 1)
93
+ RisingFactorial(a + 1, n)/factorial(n)
94
+
95
+ >>> conjugate(jacobi(n, a, b, x))
96
+ jacobi(n, conjugate(a), conjugate(b), conjugate(x))
97
+
98
+ >>> diff(jacobi(n,a,b,x), x)
99
+ (a/2 + b/2 + n/2 + 1/2)*jacobi(n - 1, a + 1, b + 1, x)
100
+
101
+ See Also
102
+ ========
103
+
104
+ gegenbauer,
105
+ chebyshevt_root, chebyshevu, chebyshevu_root,
106
+ legendre, assoc_legendre,
107
+ hermite, hermite_prob,
108
+ laguerre, assoc_laguerre,
109
+ sympy.polys.orthopolys.jacobi_poly,
110
+ sympy.polys.orthopolys.gegenbauer_poly
111
+ sympy.polys.orthopolys.chebyshevt_poly
112
+ sympy.polys.orthopolys.chebyshevu_poly
113
+ sympy.polys.orthopolys.hermite_poly
114
+ sympy.polys.orthopolys.legendre_poly
115
+ sympy.polys.orthopolys.laguerre_poly
116
+
117
+ References
118
+ ==========
119
+
120
+ .. [1] https://en.wikipedia.org/wiki/Jacobi_polynomials
121
+ .. [2] https://mathworld.wolfram.com/JacobiPolynomial.html
122
+ .. [3] https://functions.wolfram.com/Polynomials/JacobiP/
123
+
124
+ """
125
+
126
+ @classmethod
127
+ def eval(cls, n, a, b, x):
128
+ # Simplify to other polynomials
129
+ # P^{a, a}_n(x)
130
+ if a == b:
131
+ if a == Rational(-1, 2):
132
+ return RisingFactorial(S.Half, n) / factorial(n) * chebyshevt(n, x)
133
+ elif a.is_zero:
134
+ return legendre(n, x)
135
+ elif a == S.Half:
136
+ return RisingFactorial(3*S.Half, n) / factorial(n + 1) * chebyshevu(n, x)
137
+ else:
138
+ return RisingFactorial(a + 1, n) / RisingFactorial(2*a + 1, n) * gegenbauer(n, a + S.Half, x)
139
+ elif b == -a:
140
+ # P^{a, -a}_n(x)
141
+ return gamma(n + a + 1) / gamma(n + 1) * (1 + x)**(a/2) / (1 - x)**(a/2) * assoc_legendre(n, -a, x)
142
+
143
+ if not n.is_Number:
144
+ # Symbolic result P^{a,b}_n(x)
145
+ # P^{a,b}_n(-x) ---> (-1)**n * P^{b,a}_n(-x)
146
+ if x.could_extract_minus_sign():
147
+ return S.NegativeOne**n * jacobi(n, b, a, -x)
148
+ # We can evaluate for some special values of x
149
+ if x.is_zero:
150
+ return (2**(-n) * gamma(a + n + 1) / (gamma(a + 1) * factorial(n)) *
151
+ hyper([-b - n, -n], [a + 1], -1))
152
+ if x == S.One:
153
+ return RisingFactorial(a + 1, n) / factorial(n)
154
+ elif x is S.Infinity:
155
+ if n.is_positive:
156
+ # Make sure a+b+2*n \notin Z
157
+ if (a + b + 2*n).is_integer:
158
+ raise ValueError("Error. a + b + 2*n should not be an integer.")
159
+ return RisingFactorial(a + b + n + 1, n) * S.Infinity
160
+ else:
161
+ # n is a given fixed integer, evaluate into polynomial
162
+ return jacobi_poly(n, a, b, x)
163
+
164
+ def fdiff(self, argindex=4):
165
+ from sympy.concrete.summations import Sum
166
+ if argindex == 1:
167
+ # Diff wrt n
168
+ raise ArgumentIndexError(self, argindex)
169
+ elif argindex == 2:
170
+ # Diff wrt a
171
+ n, a, b, x = self.args
172
+ k = Dummy("k")
173
+ f1 = 1 / (a + b + n + k + 1)
174
+ f2 = ((a + b + 2*k + 1) * RisingFactorial(b + k + 1, n - k) /
175
+ ((n - k) * RisingFactorial(a + b + k + 1, n - k)))
176
+ return Sum(f1 * (jacobi(n, a, b, x) + f2*jacobi(k, a, b, x)), (k, 0, n - 1))
177
+ elif argindex == 3:
178
+ # Diff wrt b
179
+ n, a, b, x = self.args
180
+ k = Dummy("k")
181
+ f1 = 1 / (a + b + n + k + 1)
182
+ f2 = (-1)**(n - k) * ((a + b + 2*k + 1) * RisingFactorial(a + k + 1, n - k) /
183
+ ((n - k) * RisingFactorial(a + b + k + 1, n - k)))
184
+ return Sum(f1 * (jacobi(n, a, b, x) + f2*jacobi(k, a, b, x)), (k, 0, n - 1))
185
+ elif argindex == 4:
186
+ # Diff wrt x
187
+ n, a, b, x = self.args
188
+ return S.Half * (a + b + n + 1) * jacobi(n - 1, a + 1, b + 1, x)
189
+ else:
190
+ raise ArgumentIndexError(self, argindex)
191
+
192
+ def _eval_rewrite_as_Sum(self, n, a, b, x, **kwargs):
193
+ from sympy.concrete.summations import Sum
194
+ # Make sure n \in N
195
+ if n.is_negative or n.is_integer is False:
196
+ raise ValueError("Error: n should be a non-negative integer.")
197
+ k = Dummy("k")
198
+ kern = (RisingFactorial(-n, k) * RisingFactorial(a + b + n + 1, k) * RisingFactorial(a + k + 1, n - k) /
199
+ factorial(k) * ((1 - x)/2)**k)
200
+ return 1 / factorial(n) * Sum(kern, (k, 0, n))
201
+
202
+ def _eval_rewrite_as_polynomial(self, n, a, b, x, **kwargs):
203
+ # This function is just kept for backwards compatibility
204
+ # but should not be used
205
+ return self._eval_rewrite_as_Sum(n, a, b, x, **kwargs)
206
+
207
+ def _eval_conjugate(self):
208
+ n, a, b, x = self.args
209
+ return self.func(n, a.conjugate(), b.conjugate(), x.conjugate())
210
+
211
+
212
+ def jacobi_normalized(n, a, b, x):
213
+ r"""
214
+ Jacobi polynomial $P_n^{\left(\alpha, \beta\right)}(x)$.
215
+
216
+ Explanation
217
+ ===========
218
+
219
+ ``jacobi_normalized(n, alpha, beta, x)`` gives the $n$th
220
+ Jacobi polynomial in $x$, $P_n^{\left(\alpha, \beta\right)}(x)$.
221
+
222
+ The Jacobi polynomials are orthogonal on $[-1, 1]$ with respect
223
+ to the weight $\left(1-x\right)^\alpha \left(1+x\right)^\beta$.
224
+
225
+ This functions returns the polynomials normilzed:
226
+
227
+ .. math::
228
+
229
+ \int_{-1}^{1}
230
+ P_m^{\left(\alpha, \beta\right)}(x)
231
+ P_n^{\left(\alpha, \beta\right)}(x)
232
+ (1-x)^{\alpha} (1+x)^{\beta} \mathrm{d}x
233
+ = \delta_{m,n}
234
+
235
+ Examples
236
+ ========
237
+
238
+ >>> from sympy import jacobi_normalized
239
+ >>> from sympy.abc import n,a,b,x
240
+
241
+ >>> jacobi_normalized(n, a, b, x)
242
+ jacobi(n, a, b, x)/sqrt(2**(a + b + 1)*gamma(a + n + 1)*gamma(b + n + 1)/((a + b + 2*n + 1)*factorial(n)*gamma(a + b + n + 1)))
243
+
244
+ Parameters
245
+ ==========
246
+
247
+ n : integer degree of polynomial
248
+
249
+ a : alpha value
250
+
251
+ b : beta value
252
+
253
+ x : symbol
254
+
255
+ See Also
256
+ ========
257
+
258
+ gegenbauer,
259
+ chebyshevt_root, chebyshevu, chebyshevu_root,
260
+ legendre, assoc_legendre,
261
+ hermite, hermite_prob,
262
+ laguerre, assoc_laguerre,
263
+ sympy.polys.orthopolys.jacobi_poly,
264
+ sympy.polys.orthopolys.gegenbauer_poly
265
+ sympy.polys.orthopolys.chebyshevt_poly
266
+ sympy.polys.orthopolys.chebyshevu_poly
267
+ sympy.polys.orthopolys.hermite_poly
268
+ sympy.polys.orthopolys.legendre_poly
269
+ sympy.polys.orthopolys.laguerre_poly
270
+
271
+ References
272
+ ==========
273
+
274
+ .. [1] https://en.wikipedia.org/wiki/Jacobi_polynomials
275
+ .. [2] https://mathworld.wolfram.com/JacobiPolynomial.html
276
+ .. [3] https://functions.wolfram.com/Polynomials/JacobiP/
277
+
278
+ """
279
+ nfactor = (S(2)**(a + b + 1) * (gamma(n + a + 1) * gamma(n + b + 1))
280
+ / (2*n + a + b + 1) / (factorial(n) * gamma(n + a + b + 1)))
281
+
282
+ return jacobi(n, a, b, x) / sqrt(nfactor)
283
+
284
+
285
+ #----------------------------------------------------------------------------
286
+ # Gegenbauer polynomials
287
+ #
288
+
289
+
290
+ class gegenbauer(OrthogonalPolynomial):
291
+ r"""
292
+ Gegenbauer polynomial $C_n^{\left(\alpha\right)}(x)$.
293
+
294
+ Explanation
295
+ ===========
296
+
297
+ ``gegenbauer(n, alpha, x)`` gives the $n$th Gegenbauer polynomial
298
+ in $x$, $C_n^{\left(\alpha\right)}(x)$.
299
+
300
+ The Gegenbauer polynomials are orthogonal on $[-1, 1]$ with
301
+ respect to the weight $\left(1-x^2\right)^{\alpha-\frac{1}{2}}$.
302
+
303
+ Examples
304
+ ========
305
+
306
+ >>> from sympy import gegenbauer, conjugate, diff
307
+ >>> from sympy.abc import n,a,x
308
+ >>> gegenbauer(0, a, x)
309
+ 1
310
+ >>> gegenbauer(1, a, x)
311
+ 2*a*x
312
+ >>> gegenbauer(2, a, x)
313
+ -a + x**2*(2*a**2 + 2*a)
314
+ >>> gegenbauer(3, a, x)
315
+ x**3*(4*a**3/3 + 4*a**2 + 8*a/3) + x*(-2*a**2 - 2*a)
316
+
317
+ >>> gegenbauer(n, a, x)
318
+ gegenbauer(n, a, x)
319
+ >>> gegenbauer(n, a, -x)
320
+ (-1)**n*gegenbauer(n, a, x)
321
+
322
+ >>> gegenbauer(n, a, 0)
323
+ 2**n*sqrt(pi)*gamma(a + n/2)/(gamma(a)*gamma(1/2 - n/2)*gamma(n + 1))
324
+ >>> gegenbauer(n, a, 1)
325
+ gamma(2*a + n)/(gamma(2*a)*gamma(n + 1))
326
+
327
+ >>> conjugate(gegenbauer(n, a, x))
328
+ gegenbauer(n, conjugate(a), conjugate(x))
329
+
330
+ >>> diff(gegenbauer(n, a, x), x)
331
+ 2*a*gegenbauer(n - 1, a + 1, x)
332
+
333
+ See Also
334
+ ========
335
+
336
+ jacobi,
337
+ chebyshevt_root, chebyshevu, chebyshevu_root,
338
+ legendre, assoc_legendre,
339
+ hermite, hermite_prob,
340
+ laguerre, assoc_laguerre,
341
+ sympy.polys.orthopolys.jacobi_poly
342
+ sympy.polys.orthopolys.gegenbauer_poly
343
+ sympy.polys.orthopolys.chebyshevt_poly
344
+ sympy.polys.orthopolys.chebyshevu_poly
345
+ sympy.polys.orthopolys.hermite_poly
346
+ sympy.polys.orthopolys.hermite_prob_poly
347
+ sympy.polys.orthopolys.legendre_poly
348
+ sympy.polys.orthopolys.laguerre_poly
349
+
350
+ References
351
+ ==========
352
+
353
+ .. [1] https://en.wikipedia.org/wiki/Gegenbauer_polynomials
354
+ .. [2] https://mathworld.wolfram.com/GegenbauerPolynomial.html
355
+ .. [3] https://functions.wolfram.com/Polynomials/GegenbauerC3/
356
+
357
+ """
358
+
359
+ @classmethod
360
+ def eval(cls, n, a, x):
361
+ # For negative n the polynomials vanish
362
+ # See https://functions.wolfram.com/Polynomials/GegenbauerC3/03/01/03/0012/
363
+ if n.is_negative:
364
+ return S.Zero
365
+
366
+ # Some special values for fixed a
367
+ if a == S.Half:
368
+ return legendre(n, x)
369
+ elif a == S.One:
370
+ return chebyshevu(n, x)
371
+ elif a == S.NegativeOne:
372
+ return S.Zero
373
+
374
+ if not n.is_Number:
375
+ # Handle this before the general sign extraction rule
376
+ if x == S.NegativeOne:
377
+ if (re(a) > S.Half) == True:
378
+ return S.ComplexInfinity
379
+ else:
380
+ return (cos(S.Pi*(a+n)) * sec(S.Pi*a) * gamma(2*a+n) /
381
+ (gamma(2*a) * gamma(n+1)))
382
+
383
+ # Symbolic result C^a_n(x)
384
+ # C^a_n(-x) ---> (-1)**n * C^a_n(x)
385
+ if x.could_extract_minus_sign():
386
+ return S.NegativeOne**n * gegenbauer(n, a, -x)
387
+ # We can evaluate for some special values of x
388
+ if x.is_zero:
389
+ return (2**n * sqrt(S.Pi) * gamma(a + S.Half*n) /
390
+ (gamma((1 - n)/2) * gamma(n + 1) * gamma(a)) )
391
+ if x == S.One:
392
+ return gamma(2*a + n) / (gamma(2*a) * gamma(n + 1))
393
+ elif x is S.Infinity:
394
+ if n.is_positive:
395
+ return RisingFactorial(a, n) * S.Infinity
396
+ else:
397
+ # n is a given fixed integer, evaluate into polynomial
398
+ return gegenbauer_poly(n, a, x)
399
+
400
+ def fdiff(self, argindex=3):
401
+ from sympy.concrete.summations import Sum
402
+ if argindex == 1:
403
+ # Diff wrt n
404
+ raise ArgumentIndexError(self, argindex)
405
+ elif argindex == 2:
406
+ # Diff wrt a
407
+ n, a, x = self.args
408
+ k = Dummy("k")
409
+ factor1 = 2 * (1 + (-1)**(n - k)) * (k + a) / ((k +
410
+ n + 2*a) * (n - k))
411
+ factor2 = 2*(k + 1) / ((k + 2*a) * (2*k + 2*a + 1)) + \
412
+ 2 / (k + n + 2*a)
413
+ kern = factor1*gegenbauer(k, a, x) + factor2*gegenbauer(n, a, x)
414
+ return Sum(kern, (k, 0, n - 1))
415
+ elif argindex == 3:
416
+ # Diff wrt x
417
+ n, a, x = self.args
418
+ return 2*a*gegenbauer(n - 1, a + 1, x)
419
+ else:
420
+ raise ArgumentIndexError(self, argindex)
421
+
422
+ def _eval_rewrite_as_Sum(self, n, a, x, **kwargs):
423
+ from sympy.concrete.summations import Sum
424
+ k = Dummy("k")
425
+ kern = ((-1)**k * RisingFactorial(a, n - k) * (2*x)**(n - 2*k) /
426
+ (factorial(k) * factorial(n - 2*k)))
427
+ return Sum(kern, (k, 0, floor(n/2)))
428
+
429
+ def _eval_rewrite_as_polynomial(self, n, a, x, **kwargs):
430
+ # This function is just kept for backwards compatibility
431
+ # but should not be used
432
+ return self._eval_rewrite_as_Sum(n, a, x, **kwargs)
433
+
434
+ def _eval_conjugate(self):
435
+ n, a, x = self.args
436
+ return self.func(n, a.conjugate(), x.conjugate())
437
+
438
+ #----------------------------------------------------------------------------
439
+ # Chebyshev polynomials of first and second kind
440
+ #
441
+
442
+
443
+ class chebyshevt(OrthogonalPolynomial):
444
+ r"""
445
+ Chebyshev polynomial of the first kind, $T_n(x)$.
446
+
447
+ Explanation
448
+ ===========
449
+
450
+ ``chebyshevt(n, x)`` gives the $n$th Chebyshev polynomial (of the first
451
+ kind) in $x$, $T_n(x)$.
452
+
453
+ The Chebyshev polynomials of the first kind are orthogonal on
454
+ $[-1, 1]$ with respect to the weight $\frac{1}{\sqrt{1-x^2}}$.
455
+
456
+ Examples
457
+ ========
458
+
459
+ >>> from sympy import chebyshevt, diff
460
+ >>> from sympy.abc import n,x
461
+ >>> chebyshevt(0, x)
462
+ 1
463
+ >>> chebyshevt(1, x)
464
+ x
465
+ >>> chebyshevt(2, x)
466
+ 2*x**2 - 1
467
+
468
+ >>> chebyshevt(n, x)
469
+ chebyshevt(n, x)
470
+ >>> chebyshevt(n, -x)
471
+ (-1)**n*chebyshevt(n, x)
472
+ >>> chebyshevt(-n, x)
473
+ chebyshevt(n, x)
474
+
475
+ >>> chebyshevt(n, 0)
476
+ cos(pi*n/2)
477
+ >>> chebyshevt(n, -1)
478
+ (-1)**n
479
+
480
+ >>> diff(chebyshevt(n, x), x)
481
+ n*chebyshevu(n - 1, x)
482
+
483
+ See Also
484
+ ========
485
+
486
+ jacobi, gegenbauer,
487
+ chebyshevt_root, chebyshevu, chebyshevu_root,
488
+ legendre, assoc_legendre,
489
+ hermite, hermite_prob,
490
+ laguerre, assoc_laguerre,
491
+ sympy.polys.orthopolys.jacobi_poly
492
+ sympy.polys.orthopolys.gegenbauer_poly
493
+ sympy.polys.orthopolys.chebyshevt_poly
494
+ sympy.polys.orthopolys.chebyshevu_poly
495
+ sympy.polys.orthopolys.hermite_poly
496
+ sympy.polys.orthopolys.hermite_prob_poly
497
+ sympy.polys.orthopolys.legendre_poly
498
+ sympy.polys.orthopolys.laguerre_poly
499
+
500
+ References
501
+ ==========
502
+
503
+ .. [1] https://en.wikipedia.org/wiki/Chebyshev_polynomial
504
+ .. [2] https://mathworld.wolfram.com/ChebyshevPolynomialoftheFirstKind.html
505
+ .. [3] https://mathworld.wolfram.com/ChebyshevPolynomialoftheSecondKind.html
506
+ .. [4] https://functions.wolfram.com/Polynomials/ChebyshevT/
507
+ .. [5] https://functions.wolfram.com/Polynomials/ChebyshevU/
508
+
509
+ """
510
+
511
+ _ortho_poly = staticmethod(chebyshevt_poly)
512
+
513
+ @classmethod
514
+ def eval(cls, n, x):
515
+ if not n.is_Number:
516
+ # Symbolic result T_n(x)
517
+ # T_n(-x) ---> (-1)**n * T_n(x)
518
+ if x.could_extract_minus_sign():
519
+ return S.NegativeOne**n * chebyshevt(n, -x)
520
+ # T_{-n}(x) ---> T_n(x)
521
+ if n.could_extract_minus_sign():
522
+ return chebyshevt(-n, x)
523
+ # We can evaluate for some special values of x
524
+ if x.is_zero:
525
+ return cos(S.Half * S.Pi * n)
526
+ if x == S.One:
527
+ return S.One
528
+ elif x is S.Infinity:
529
+ return S.Infinity
530
+ else:
531
+ # n is a given fixed integer, evaluate into polynomial
532
+ if n.is_negative:
533
+ # T_{-n}(x) == T_n(x)
534
+ return cls._eval_at_order(-n, x)
535
+ else:
536
+ return cls._eval_at_order(n, x)
537
+
538
+ def fdiff(self, argindex=2):
539
+ if argindex == 1:
540
+ # Diff wrt n
541
+ raise ArgumentIndexError(self, argindex)
542
+ elif argindex == 2:
543
+ # Diff wrt x
544
+ n, x = self.args
545
+ return n * chebyshevu(n - 1, x)
546
+ else:
547
+ raise ArgumentIndexError(self, argindex)
548
+
549
+ def _eval_rewrite_as_Sum(self, n, x, **kwargs):
550
+ from sympy.concrete.summations import Sum
551
+ k = Dummy("k")
552
+ kern = binomial(n, 2*k) * (x**2 - 1)**k * x**(n - 2*k)
553
+ return Sum(kern, (k, 0, floor(n/2)))
554
+
555
+ def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
556
+ # This function is just kept for backwards compatibility
557
+ # but should not be used
558
+ return self._eval_rewrite_as_Sum(n, x, **kwargs)
559
+
560
+
561
+ class chebyshevu(OrthogonalPolynomial):
562
+ r"""
563
+ Chebyshev polynomial of the second kind, $U_n(x)$.
564
+
565
+ Explanation
566
+ ===========
567
+
568
+ ``chebyshevu(n, x)`` gives the $n$th Chebyshev polynomial of the second
569
+ kind in x, $U_n(x)$.
570
+
571
+ The Chebyshev polynomials of the second kind are orthogonal on
572
+ $[-1, 1]$ with respect to the weight $\sqrt{1-x^2}$.
573
+
574
+ Examples
575
+ ========
576
+
577
+ >>> from sympy import chebyshevu, diff
578
+ >>> from sympy.abc import n,x
579
+ >>> chebyshevu(0, x)
580
+ 1
581
+ >>> chebyshevu(1, x)
582
+ 2*x
583
+ >>> chebyshevu(2, x)
584
+ 4*x**2 - 1
585
+
586
+ >>> chebyshevu(n, x)
587
+ chebyshevu(n, x)
588
+ >>> chebyshevu(n, -x)
589
+ (-1)**n*chebyshevu(n, x)
590
+ >>> chebyshevu(-n, x)
591
+ -chebyshevu(n - 2, x)
592
+
593
+ >>> chebyshevu(n, 0)
594
+ cos(pi*n/2)
595
+ >>> chebyshevu(n, 1)
596
+ n + 1
597
+
598
+ >>> diff(chebyshevu(n, x), x)
599
+ (-x*chebyshevu(n, x) + (n + 1)*chebyshevt(n + 1, x))/(x**2 - 1)
600
+
601
+ See Also
602
+ ========
603
+
604
+ jacobi, gegenbauer,
605
+ chebyshevt, chebyshevt_root, chebyshevu_root,
606
+ legendre, assoc_legendre,
607
+ hermite, hermite_prob,
608
+ laguerre, assoc_laguerre,
609
+ sympy.polys.orthopolys.jacobi_poly
610
+ sympy.polys.orthopolys.gegenbauer_poly
611
+ sympy.polys.orthopolys.chebyshevt_poly
612
+ sympy.polys.orthopolys.chebyshevu_poly
613
+ sympy.polys.orthopolys.hermite_poly
614
+ sympy.polys.orthopolys.hermite_prob_poly
615
+ sympy.polys.orthopolys.legendre_poly
616
+ sympy.polys.orthopolys.laguerre_poly
617
+
618
+ References
619
+ ==========
620
+
621
+ .. [1] https://en.wikipedia.org/wiki/Chebyshev_polynomial
622
+ .. [2] https://mathworld.wolfram.com/ChebyshevPolynomialoftheFirstKind.html
623
+ .. [3] https://mathworld.wolfram.com/ChebyshevPolynomialoftheSecondKind.html
624
+ .. [4] https://functions.wolfram.com/Polynomials/ChebyshevT/
625
+ .. [5] https://functions.wolfram.com/Polynomials/ChebyshevU/
626
+
627
+ """
628
+
629
+ _ortho_poly = staticmethod(chebyshevu_poly)
630
+
631
+ @classmethod
632
+ def eval(cls, n, x):
633
+ if not n.is_Number:
634
+ # Symbolic result U_n(x)
635
+ # U_n(-x) ---> (-1)**n * U_n(x)
636
+ if x.could_extract_minus_sign():
637
+ return S.NegativeOne**n * chebyshevu(n, -x)
638
+ # U_{-n}(x) ---> -U_{n-2}(x)
639
+ if n.could_extract_minus_sign():
640
+ if n == S.NegativeOne:
641
+ # n can not be -1 here
642
+ return S.Zero
643
+ elif not (-n - 2).could_extract_minus_sign():
644
+ return -chebyshevu(-n - 2, x)
645
+ # We can evaluate for some special values of x
646
+ if x.is_zero:
647
+ return cos(S.Half * S.Pi * n)
648
+ if x == S.One:
649
+ return S.One + n
650
+ elif x is S.Infinity:
651
+ return S.Infinity
652
+ else:
653
+ # n is a given fixed integer, evaluate into polynomial
654
+ if n.is_negative:
655
+ # U_{-n}(x) ---> -U_{n-2}(x)
656
+ if n == S.NegativeOne:
657
+ return S.Zero
658
+ else:
659
+ return -cls._eval_at_order(-n - 2, x)
660
+ else:
661
+ return cls._eval_at_order(n, x)
662
+
663
+ def fdiff(self, argindex=2):
664
+ if argindex == 1:
665
+ # Diff wrt n
666
+ raise ArgumentIndexError(self, argindex)
667
+ elif argindex == 2:
668
+ # Diff wrt x
669
+ n, x = self.args
670
+ return ((n + 1) * chebyshevt(n + 1, x) - x * chebyshevu(n, x)) / (x**2 - 1)
671
+ else:
672
+ raise ArgumentIndexError(self, argindex)
673
+
674
+ def _eval_rewrite_as_Sum(self, n, x, **kwargs):
675
+ from sympy.concrete.summations import Sum
676
+ k = Dummy("k")
677
+ kern = S.NegativeOne**k * factorial(
678
+ n - k) * (2*x)**(n - 2*k) / (factorial(k) * factorial(n - 2*k))
679
+ return Sum(kern, (k, 0, floor(n/2)))
680
+
681
+ def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
682
+ # This function is just kept for backwards compatibility
683
+ # but should not be used
684
+ return self._eval_rewrite_as_Sum(n, x, **kwargs)
685
+
686
+
687
+ class chebyshevt_root(Function):
688
+ r"""
689
+ ``chebyshev_root(n, k)`` returns the $k$th root (indexed from zero) of
690
+ the $n$th Chebyshev polynomial of the first kind; that is, if
691
+ $0 \le k < n$, ``chebyshevt(n, chebyshevt_root(n, k)) == 0``.
692
+
693
+ Examples
694
+ ========
695
+
696
+ >>> from sympy import chebyshevt, chebyshevt_root
697
+ >>> chebyshevt_root(3, 2)
698
+ -sqrt(3)/2
699
+ >>> chebyshevt(3, chebyshevt_root(3, 2))
700
+ 0
701
+
702
+ See Also
703
+ ========
704
+
705
+ jacobi, gegenbauer,
706
+ chebyshevt, chebyshevu, chebyshevu_root,
707
+ legendre, assoc_legendre,
708
+ hermite, hermite_prob,
709
+ laguerre, assoc_laguerre,
710
+ sympy.polys.orthopolys.jacobi_poly
711
+ sympy.polys.orthopolys.gegenbauer_poly
712
+ sympy.polys.orthopolys.chebyshevt_poly
713
+ sympy.polys.orthopolys.chebyshevu_poly
714
+ sympy.polys.orthopolys.hermite_poly
715
+ sympy.polys.orthopolys.hermite_prob_poly
716
+ sympy.polys.orthopolys.legendre_poly
717
+ sympy.polys.orthopolys.laguerre_poly
718
+ """
719
+
720
+ @classmethod
721
+ def eval(cls, n, k):
722
+ if not ((0 <= k) and (k < n)):
723
+ raise ValueError("must have 0 <= k < n, "
724
+ "got k = %s and n = %s" % (k, n))
725
+ return cos(S.Pi*(2*k + 1)/(2*n))
726
+
727
+
728
+ class chebyshevu_root(Function):
729
+ r"""
730
+ ``chebyshevu_root(n, k)`` returns the $k$th root (indexed from zero) of the
731
+ $n$th Chebyshev polynomial of the second kind; that is, if $0 \le k < n$,
732
+ ``chebyshevu(n, chebyshevu_root(n, k)) == 0``.
733
+
734
+ Examples
735
+ ========
736
+
737
+ >>> from sympy import chebyshevu, chebyshevu_root
738
+ >>> chebyshevu_root(3, 2)
739
+ -sqrt(2)/2
740
+ >>> chebyshevu(3, chebyshevu_root(3, 2))
741
+ 0
742
+
743
+ See Also
744
+ ========
745
+
746
+ chebyshevt, chebyshevt_root, chebyshevu,
747
+ legendre, assoc_legendre,
748
+ hermite, hermite_prob,
749
+ laguerre, assoc_laguerre,
750
+ sympy.polys.orthopolys.jacobi_poly
751
+ sympy.polys.orthopolys.gegenbauer_poly
752
+ sympy.polys.orthopolys.chebyshevt_poly
753
+ sympy.polys.orthopolys.chebyshevu_poly
754
+ sympy.polys.orthopolys.hermite_poly
755
+ sympy.polys.orthopolys.hermite_prob_poly
756
+ sympy.polys.orthopolys.legendre_poly
757
+ sympy.polys.orthopolys.laguerre_poly
758
+ """
759
+
760
+
761
+ @classmethod
762
+ def eval(cls, n, k):
763
+ if not ((0 <= k) and (k < n)):
764
+ raise ValueError("must have 0 <= k < n, "
765
+ "got k = %s and n = %s" % (k, n))
766
+ return cos(S.Pi*(k + 1)/(n + 1))
767
+
768
+ #----------------------------------------------------------------------------
769
+ # Legendre polynomials and Associated Legendre polynomials
770
+ #
771
+
772
+
773
+ class legendre(OrthogonalPolynomial):
774
+ r"""
775
+ ``legendre(n, x)`` gives the $n$th Legendre polynomial of $x$, $P_n(x)$
776
+
777
+ Explanation
778
+ ===========
779
+
780
+ The Legendre polynomials are orthogonal on $[-1, 1]$ with respect to
781
+ the constant weight 1. They satisfy $P_n(1) = 1$ for all $n$; further,
782
+ $P_n$ is odd for odd $n$ and even for even $n$.
783
+
784
+ Examples
785
+ ========
786
+
787
+ >>> from sympy import legendre, diff
788
+ >>> from sympy.abc import x, n
789
+ >>> legendre(0, x)
790
+ 1
791
+ >>> legendre(1, x)
792
+ x
793
+ >>> legendre(2, x)
794
+ 3*x**2/2 - 1/2
795
+ >>> legendre(n, x)
796
+ legendre(n, x)
797
+ >>> diff(legendre(n,x), x)
798
+ n*(x*legendre(n, x) - legendre(n - 1, x))/(x**2 - 1)
799
+
800
+ See Also
801
+ ========
802
+
803
+ jacobi, gegenbauer,
804
+ chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
805
+ assoc_legendre,
806
+ hermite, hermite_prob,
807
+ laguerre, assoc_laguerre,
808
+ sympy.polys.orthopolys.jacobi_poly
809
+ sympy.polys.orthopolys.gegenbauer_poly
810
+ sympy.polys.orthopolys.chebyshevt_poly
811
+ sympy.polys.orthopolys.chebyshevu_poly
812
+ sympy.polys.orthopolys.hermite_poly
813
+ sympy.polys.orthopolys.hermite_prob_poly
814
+ sympy.polys.orthopolys.legendre_poly
815
+ sympy.polys.orthopolys.laguerre_poly
816
+
817
+ References
818
+ ==========
819
+
820
+ .. [1] https://en.wikipedia.org/wiki/Legendre_polynomial
821
+ .. [2] https://mathworld.wolfram.com/LegendrePolynomial.html
822
+ .. [3] https://functions.wolfram.com/Polynomials/LegendreP/
823
+ .. [4] https://functions.wolfram.com/Polynomials/LegendreP2/
824
+
825
+ """
826
+
827
+ _ortho_poly = staticmethod(legendre_poly)
828
+
829
+ @classmethod
830
+ def eval(cls, n, x):
831
+ if not n.is_Number:
832
+ # Symbolic result L_n(x)
833
+ # L_n(-x) ---> (-1)**n * L_n(x)
834
+ if x.could_extract_minus_sign():
835
+ return S.NegativeOne**n * legendre(n, -x)
836
+ # L_{-n}(x) ---> L_{n-1}(x)
837
+ if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign():
838
+ return legendre(-n - S.One, x)
839
+ # We can evaluate for some special values of x
840
+ if x.is_zero:
841
+ return sqrt(S.Pi)/(gamma(S.Half - n/2)*gamma(S.One + n/2))
842
+ elif x == S.One:
843
+ return S.One
844
+ elif x is S.Infinity:
845
+ return S.Infinity
846
+ else:
847
+ # n is a given fixed integer, evaluate into polynomial;
848
+ # L_{-n}(x) ---> L_{n-1}(x)
849
+ if n.is_negative:
850
+ n = -n - S.One
851
+ return cls._eval_at_order(n, x)
852
+
853
+ def fdiff(self, argindex=2):
854
+ if argindex == 1:
855
+ # Diff wrt n
856
+ raise ArgumentIndexError(self, argindex)
857
+ elif argindex == 2:
858
+ # Diff wrt x
859
+ # Find better formula, this is unsuitable for x = +/-1
860
+ # https://www.autodiff.org/ad16/Oral/Buecker_Legendre.pdf says
861
+ # at x = 1:
862
+ # n*(n + 1)/2 , m = 0
863
+ # oo , m = 1
864
+ # -(n-1)*n*(n+1)*(n+2)/4 , m = 2
865
+ # 0 , m = 3, 4, ..., n
866
+ #
867
+ # at x = -1
868
+ # (-1)**(n+1)*n*(n + 1)/2 , m = 0
869
+ # (-1)**n*oo , m = 1
870
+ # (-1)**n*(n-1)*n*(n+1)*(n+2)/4 , m = 2
871
+ # 0 , m = 3, 4, ..., n
872
+ n, x = self.args
873
+ return n/(x**2 - 1)*(x*legendre(n, x) - legendre(n - 1, x))
874
+ else:
875
+ raise ArgumentIndexError(self, argindex)
876
+
877
+ def _eval_rewrite_as_Sum(self, n, x, **kwargs):
878
+ from sympy.concrete.summations import Sum
879
+ k = Dummy("k")
880
+ kern = S.NegativeOne**k*binomial(n, k)**2*((1 + x)/2)**(n - k)*((1 - x)/2)**k
881
+ return Sum(kern, (k, 0, n))
882
+
883
+ def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
884
+ # This function is just kept for backwards compatibility
885
+ # but should not be used
886
+ return self._eval_rewrite_as_Sum(n, x, **kwargs)
887
+
888
+
889
+ class assoc_legendre(Function):
890
+ r"""
891
+ ``assoc_legendre(n, m, x)`` gives $P_n^m(x)$, where $n$ and $m$ are
892
+ the degree and order or an expression which is related to the nth
893
+ order Legendre polynomial, $P_n(x)$ in the following manner:
894
+
895
+ .. math::
896
+ P_n^m(x) = (-1)^m (1 - x^2)^{\frac{m}{2}}
897
+ \frac{\mathrm{d}^m P_n(x)}{\mathrm{d} x^m}
898
+
899
+ Explanation
900
+ ===========
901
+
902
+ Associated Legendre polynomials are orthogonal on $[-1, 1]$ with:
903
+
904
+ - weight $= 1$ for the same $m$ and different $n$.
905
+ - weight $= \frac{1}{1-x^2}$ for the same $n$ and different $m$.
906
+
907
+ Examples
908
+ ========
909
+
910
+ >>> from sympy import assoc_legendre
911
+ >>> from sympy.abc import x, m, n
912
+ >>> assoc_legendre(0,0, x)
913
+ 1
914
+ >>> assoc_legendre(1,0, x)
915
+ x
916
+ >>> assoc_legendre(1,1, x)
917
+ -sqrt(1 - x**2)
918
+ >>> assoc_legendre(n,m,x)
919
+ assoc_legendre(n, m, x)
920
+
921
+ See Also
922
+ ========
923
+
924
+ jacobi, gegenbauer,
925
+ chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
926
+ legendre,
927
+ hermite, hermite_prob,
928
+ laguerre, assoc_laguerre,
929
+ sympy.polys.orthopolys.jacobi_poly
930
+ sympy.polys.orthopolys.gegenbauer_poly
931
+ sympy.polys.orthopolys.chebyshevt_poly
932
+ sympy.polys.orthopolys.chebyshevu_poly
933
+ sympy.polys.orthopolys.hermite_poly
934
+ sympy.polys.orthopolys.hermite_prob_poly
935
+ sympy.polys.orthopolys.legendre_poly
936
+ sympy.polys.orthopolys.laguerre_poly
937
+
938
+ References
939
+ ==========
940
+
941
+ .. [1] https://en.wikipedia.org/wiki/Associated_Legendre_polynomials
942
+ .. [2] https://mathworld.wolfram.com/LegendrePolynomial.html
943
+ .. [3] https://functions.wolfram.com/Polynomials/LegendreP/
944
+ .. [4] https://functions.wolfram.com/Polynomials/LegendreP2/
945
+
946
+ """
947
+
948
+ @classmethod
949
+ def _eval_at_order(cls, n, m):
950
+ P = legendre_poly(n, _x, polys=True).diff((_x, m))
951
+ return S.NegativeOne**m * (1 - _x**2)**Rational(m, 2) * P.as_expr()
952
+
953
+ @classmethod
954
+ def eval(cls, n, m, x):
955
+ if m.could_extract_minus_sign():
956
+ # P^{-m}_n ---> F * P^m_n
957
+ return S.NegativeOne**(-m) * (factorial(m + n)/factorial(n - m)) * assoc_legendre(n, -m, x)
958
+ if m == 0:
959
+ # P^0_n ---> L_n
960
+ return legendre(n, x)
961
+ if x == 0:
962
+ return 2**m*sqrt(S.Pi) / (gamma((1 - m - n)/2)*gamma(1 - (m - n)/2))
963
+ if n.is_Number and m.is_Number and n.is_integer and m.is_integer:
964
+ if n.is_negative:
965
+ raise ValueError("%s : 1st index must be nonnegative integer (got %r)" % (cls, n))
966
+ if abs(m) > n:
967
+ raise ValueError("%s : abs('2nd index') must be <= '1st index' (got %r, %r)" % (cls, n, m))
968
+ return cls._eval_at_order(int(n), abs(int(m))).subs(_x, x)
969
+
970
+ def fdiff(self, argindex=3):
971
+ if argindex == 1:
972
+ # Diff wrt n
973
+ raise ArgumentIndexError(self, argindex)
974
+ elif argindex == 2:
975
+ # Diff wrt m
976
+ raise ArgumentIndexError(self, argindex)
977
+ elif argindex == 3:
978
+ # Diff wrt x
979
+ # Find better formula, this is unsuitable for x = 1
980
+ n, m, x = self.args
981
+ return 1/(x**2 - 1)*(x*n*assoc_legendre(n, m, x) - (m + n)*assoc_legendre(n - 1, m, x))
982
+ else:
983
+ raise ArgumentIndexError(self, argindex)
984
+
985
+ def _eval_rewrite_as_Sum(self, n, m, x, **kwargs):
986
+ from sympy.concrete.summations import Sum
987
+ k = Dummy("k")
988
+ kern = factorial(2*n - 2*k)/(2**n*factorial(n - k)*factorial(
989
+ k)*factorial(n - 2*k - m))*S.NegativeOne**k*x**(n - m - 2*k)
990
+ return (1 - x**2)**(m/2) * Sum(kern, (k, 0, floor((n - m)*S.Half)))
991
+
992
+ def _eval_rewrite_as_polynomial(self, n, m, x, **kwargs):
993
+ # This function is just kept for backwards compatibility
994
+ # but should not be used
995
+ return self._eval_rewrite_as_Sum(n, m, x, **kwargs)
996
+
997
+ def _eval_conjugate(self):
998
+ n, m, x = self.args
999
+ return self.func(n, m.conjugate(), x.conjugate())
1000
+
1001
+ #----------------------------------------------------------------------------
1002
+ # Hermite polynomials
1003
+ #
1004
+
1005
+
1006
+ class hermite(OrthogonalPolynomial):
1007
+ r"""
1008
+ ``hermite(n, x)`` gives the $n$th Hermite polynomial in $x$, $H_n(x)$.
1009
+
1010
+ Explanation
1011
+ ===========
1012
+
1013
+ The Hermite polynomials are orthogonal on $(-\infty, \infty)$
1014
+ with respect to the weight $\exp\left(-x^2\right)$.
1015
+
1016
+ Examples
1017
+ ========
1018
+
1019
+ >>> from sympy import hermite, diff
1020
+ >>> from sympy.abc import x, n
1021
+ >>> hermite(0, x)
1022
+ 1
1023
+ >>> hermite(1, x)
1024
+ 2*x
1025
+ >>> hermite(2, x)
1026
+ 4*x**2 - 2
1027
+ >>> hermite(n, x)
1028
+ hermite(n, x)
1029
+ >>> diff(hermite(n,x), x)
1030
+ 2*n*hermite(n - 1, x)
1031
+ >>> hermite(n, -x)
1032
+ (-1)**n*hermite(n, x)
1033
+
1034
+ See Also
1035
+ ========
1036
+
1037
+ jacobi, gegenbauer,
1038
+ chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
1039
+ legendre, assoc_legendre,
1040
+ hermite_prob,
1041
+ laguerre, assoc_laguerre,
1042
+ sympy.polys.orthopolys.jacobi_poly
1043
+ sympy.polys.orthopolys.gegenbauer_poly
1044
+ sympy.polys.orthopolys.chebyshevt_poly
1045
+ sympy.polys.orthopolys.chebyshevu_poly
1046
+ sympy.polys.orthopolys.hermite_poly
1047
+ sympy.polys.orthopolys.hermite_prob_poly
1048
+ sympy.polys.orthopolys.legendre_poly
1049
+ sympy.polys.orthopolys.laguerre_poly
1050
+
1051
+ References
1052
+ ==========
1053
+
1054
+ .. [1] https://en.wikipedia.org/wiki/Hermite_polynomial
1055
+ .. [2] https://mathworld.wolfram.com/HermitePolynomial.html
1056
+ .. [3] https://functions.wolfram.com/Polynomials/HermiteH/
1057
+
1058
+ """
1059
+
1060
+ _ortho_poly = staticmethod(hermite_poly)
1061
+
1062
+ @classmethod
1063
+ def eval(cls, n, x):
1064
+ if not n.is_Number:
1065
+ # Symbolic result H_n(x)
1066
+ # H_n(-x) ---> (-1)**n * H_n(x)
1067
+ if x.could_extract_minus_sign():
1068
+ return S.NegativeOne**n * hermite(n, -x)
1069
+ # We can evaluate for some special values of x
1070
+ if x.is_zero:
1071
+ return 2**n * sqrt(S.Pi) / gamma((S.One - n)/2)
1072
+ elif x is S.Infinity:
1073
+ return S.Infinity
1074
+ else:
1075
+ # n is a given fixed integer, evaluate into polynomial
1076
+ if n.is_negative:
1077
+ raise ValueError(
1078
+ "The index n must be nonnegative integer (got %r)" % n)
1079
+ else:
1080
+ return cls._eval_at_order(n, x)
1081
+
1082
+ def fdiff(self, argindex=2):
1083
+ if argindex == 1:
1084
+ # Diff wrt n
1085
+ raise ArgumentIndexError(self, argindex)
1086
+ elif argindex == 2:
1087
+ # Diff wrt x
1088
+ n, x = self.args
1089
+ return 2*n*hermite(n - 1, x)
1090
+ else:
1091
+ raise ArgumentIndexError(self, argindex)
1092
+
1093
+ def _eval_rewrite_as_Sum(self, n, x, **kwargs):
1094
+ from sympy.concrete.summations import Sum
1095
+ k = Dummy("k")
1096
+ kern = S.NegativeOne**k / (factorial(k)*factorial(n - 2*k)) * (2*x)**(n - 2*k)
1097
+ return factorial(n)*Sum(kern, (k, 0, floor(n/2)))
1098
+
1099
+ def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
1100
+ # This function is just kept for backwards compatibility
1101
+ # but should not be used
1102
+ return self._eval_rewrite_as_Sum(n, x, **kwargs)
1103
+
1104
+ def _eval_rewrite_as_hermite_prob(self, n, x, **kwargs):
1105
+ return sqrt(2)**n * hermite_prob(n, x*sqrt(2))
1106
+
1107
+
1108
+ class hermite_prob(OrthogonalPolynomial):
1109
+ r"""
1110
+ ``hermite_prob(n, x)`` gives the $n$th probabilist's Hermite polynomial
1111
+ in $x$, $He_n(x)$.
1112
+
1113
+ Explanation
1114
+ ===========
1115
+
1116
+ The probabilist's Hermite polynomials are orthogonal on $(-\infty, \infty)$
1117
+ with respect to the weight $\exp\left(-\frac{x^2}{2}\right)$. They are monic
1118
+ polynomials, related to the plain Hermite polynomials (:py:class:`~.hermite`) by
1119
+
1120
+ .. math :: He_n(x) = 2^{-n/2} H_n(x/\sqrt{2})
1121
+
1122
+ Examples
1123
+ ========
1124
+
1125
+ >>> from sympy import hermite_prob, diff, I
1126
+ >>> from sympy.abc import x, n
1127
+ >>> hermite_prob(1, x)
1128
+ x
1129
+ >>> hermite_prob(5, x)
1130
+ x**5 - 10*x**3 + 15*x
1131
+ >>> diff(hermite_prob(n,x), x)
1132
+ n*hermite_prob(n - 1, x)
1133
+ >>> hermite_prob(n, -x)
1134
+ (-1)**n*hermite_prob(n, x)
1135
+
1136
+ The sum of absolute values of coefficients of $He_n(x)$ is the number of
1137
+ matchings in the complete graph $K_n$ or telephone number, A000085 in the OEIS:
1138
+
1139
+ >>> [hermite_prob(n,I) / I**n for n in range(11)]
1140
+ [1, 1, 2, 4, 10, 26, 76, 232, 764, 2620, 9496]
1141
+
1142
+ See Also
1143
+ ========
1144
+
1145
+ jacobi, gegenbauer,
1146
+ chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
1147
+ legendre, assoc_legendre,
1148
+ hermite,
1149
+ laguerre, assoc_laguerre,
1150
+ sympy.polys.orthopolys.jacobi_poly
1151
+ sympy.polys.orthopolys.gegenbauer_poly
1152
+ sympy.polys.orthopolys.chebyshevt_poly
1153
+ sympy.polys.orthopolys.chebyshevu_poly
1154
+ sympy.polys.orthopolys.hermite_poly
1155
+ sympy.polys.orthopolys.hermite_prob_poly
1156
+ sympy.polys.orthopolys.legendre_poly
1157
+ sympy.polys.orthopolys.laguerre_poly
1158
+
1159
+ References
1160
+ ==========
1161
+
1162
+ .. [1] https://en.wikipedia.org/wiki/Hermite_polynomial
1163
+ .. [2] https://mathworld.wolfram.com/HermitePolynomial.html
1164
+ """
1165
+
1166
+ _ortho_poly = staticmethod(hermite_prob_poly)
1167
+
1168
+ @classmethod
1169
+ def eval(cls, n, x):
1170
+ if not n.is_Number:
1171
+ if x.could_extract_minus_sign():
1172
+ return S.NegativeOne**n * hermite_prob(n, -x)
1173
+ if x.is_zero:
1174
+ return sqrt(S.Pi) / gamma((S.One-n) / 2)
1175
+ elif x is S.Infinity:
1176
+ return S.Infinity
1177
+ else:
1178
+ if n.is_negative:
1179
+ ValueError("n must be a nonnegative integer, not %r" % n)
1180
+ else:
1181
+ return cls._eval_at_order(n, x)
1182
+
1183
+ def fdiff(self, argindex=2):
1184
+ if argindex == 2:
1185
+ n, x = self.args
1186
+ return n*hermite_prob(n-1, x)
1187
+ else:
1188
+ raise ArgumentIndexError(self, argindex)
1189
+
1190
+ def _eval_rewrite_as_Sum(self, n, x, **kwargs):
1191
+ from sympy.concrete.summations import Sum
1192
+ k = Dummy("k")
1193
+ kern = (-S.Half)**k * x**(n-2*k) / (factorial(k) * factorial(n-2*k))
1194
+ return factorial(n)*Sum(kern, (k, 0, floor(n/2)))
1195
+
1196
+ def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
1197
+ # This function is just kept for backwards compatibility
1198
+ # but should not be used
1199
+ return self._eval_rewrite_as_Sum(n, x, **kwargs)
1200
+
1201
+ def _eval_rewrite_as_hermite(self, n, x, **kwargs):
1202
+ return sqrt(2)**(-n) * hermite(n, x/sqrt(2))
1203
+
1204
+
1205
+ #----------------------------------------------------------------------------
1206
+ # Laguerre polynomials
1207
+ #
1208
+
1209
+
1210
+ class laguerre(OrthogonalPolynomial):
1211
+ r"""
1212
+ Returns the $n$th Laguerre polynomial in $x$, $L_n(x)$.
1213
+
1214
+ Examples
1215
+ ========
1216
+
1217
+ >>> from sympy import laguerre, diff
1218
+ >>> from sympy.abc import x, n
1219
+ >>> laguerre(0, x)
1220
+ 1
1221
+ >>> laguerre(1, x)
1222
+ 1 - x
1223
+ >>> laguerre(2, x)
1224
+ x**2/2 - 2*x + 1
1225
+ >>> laguerre(3, x)
1226
+ -x**3/6 + 3*x**2/2 - 3*x + 1
1227
+
1228
+ >>> laguerre(n, x)
1229
+ laguerre(n, x)
1230
+
1231
+ >>> diff(laguerre(n, x), x)
1232
+ -assoc_laguerre(n - 1, 1, x)
1233
+
1234
+ Parameters
1235
+ ==========
1236
+
1237
+ n : int
1238
+ Degree of Laguerre polynomial. Must be `n \ge 0`.
1239
+
1240
+ See Also
1241
+ ========
1242
+
1243
+ jacobi, gegenbauer,
1244
+ chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
1245
+ legendre, assoc_legendre,
1246
+ hermite, hermite_prob,
1247
+ assoc_laguerre,
1248
+ sympy.polys.orthopolys.jacobi_poly
1249
+ sympy.polys.orthopolys.gegenbauer_poly
1250
+ sympy.polys.orthopolys.chebyshevt_poly
1251
+ sympy.polys.orthopolys.chebyshevu_poly
1252
+ sympy.polys.orthopolys.hermite_poly
1253
+ sympy.polys.orthopolys.hermite_prob_poly
1254
+ sympy.polys.orthopolys.legendre_poly
1255
+ sympy.polys.orthopolys.laguerre_poly
1256
+
1257
+ References
1258
+ ==========
1259
+
1260
+ .. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial
1261
+ .. [2] https://mathworld.wolfram.com/LaguerrePolynomial.html
1262
+ .. [3] https://functions.wolfram.com/Polynomials/LaguerreL/
1263
+ .. [4] https://functions.wolfram.com/Polynomials/LaguerreL3/
1264
+
1265
+ """
1266
+
1267
+ _ortho_poly = staticmethod(laguerre_poly)
1268
+
1269
+ @classmethod
1270
+ def eval(cls, n, x):
1271
+ if n.is_integer is False:
1272
+ raise ValueError("Error: n should be an integer.")
1273
+ if not n.is_Number:
1274
+ # Symbolic result L_n(x)
1275
+ # L_{n}(-x) ---> exp(-x) * L_{-n-1}(x)
1276
+ # L_{-n}(x) ---> exp(x) * L_{n-1}(-x)
1277
+ if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign():
1278
+ return exp(x)*laguerre(-n - 1, -x)
1279
+ # We can evaluate for some special values of x
1280
+ if x.is_zero:
1281
+ return S.One
1282
+ elif x is S.NegativeInfinity:
1283
+ return S.Infinity
1284
+ elif x is S.Infinity:
1285
+ return S.NegativeOne**n * S.Infinity
1286
+ else:
1287
+ if n.is_negative:
1288
+ return exp(x)*laguerre(-n - 1, -x)
1289
+ else:
1290
+ return cls._eval_at_order(n, x)
1291
+
1292
+ def fdiff(self, argindex=2):
1293
+ if argindex == 1:
1294
+ # Diff wrt n
1295
+ raise ArgumentIndexError(self, argindex)
1296
+ elif argindex == 2:
1297
+ # Diff wrt x
1298
+ n, x = self.args
1299
+ return -assoc_laguerre(n - 1, 1, x)
1300
+ else:
1301
+ raise ArgumentIndexError(self, argindex)
1302
+
1303
+ def _eval_rewrite_as_Sum(self, n, x, **kwargs):
1304
+ from sympy.concrete.summations import Sum
1305
+ # Make sure n \in N_0
1306
+ if n.is_negative:
1307
+ return exp(x) * self._eval_rewrite_as_Sum(-n - 1, -x, **kwargs)
1308
+ if n.is_integer is False:
1309
+ raise ValueError("Error: n should be an integer.")
1310
+ k = Dummy("k")
1311
+ kern = RisingFactorial(-n, k) / factorial(k)**2 * x**k
1312
+ return Sum(kern, (k, 0, n))
1313
+
1314
+ def _eval_rewrite_as_polynomial(self, n, x, **kwargs):
1315
+ # This function is just kept for backwards compatibility
1316
+ # but should not be used
1317
+ return self._eval_rewrite_as_Sum(n, x, **kwargs)
1318
+
1319
+
1320
+ class assoc_laguerre(OrthogonalPolynomial):
1321
+ r"""
1322
+ Returns the $n$th generalized Laguerre polynomial in $x$, $L_n(x)$.
1323
+
1324
+ Examples
1325
+ ========
1326
+
1327
+ >>> from sympy import assoc_laguerre, diff
1328
+ >>> from sympy.abc import x, n, a
1329
+ >>> assoc_laguerre(0, a, x)
1330
+ 1
1331
+ >>> assoc_laguerre(1, a, x)
1332
+ a - x + 1
1333
+ >>> assoc_laguerre(2, a, x)
1334
+ a**2/2 + 3*a/2 + x**2/2 + x*(-a - 2) + 1
1335
+ >>> assoc_laguerre(3, a, x)
1336
+ a**3/6 + a**2 + 11*a/6 - x**3/6 + x**2*(a/2 + 3/2) +
1337
+ x*(-a**2/2 - 5*a/2 - 3) + 1
1338
+
1339
+ >>> assoc_laguerre(n, a, 0)
1340
+ binomial(a + n, a)
1341
+
1342
+ >>> assoc_laguerre(n, a, x)
1343
+ assoc_laguerre(n, a, x)
1344
+
1345
+ >>> assoc_laguerre(n, 0, x)
1346
+ laguerre(n, x)
1347
+
1348
+ >>> diff(assoc_laguerre(n, a, x), x)
1349
+ -assoc_laguerre(n - 1, a + 1, x)
1350
+
1351
+ >>> diff(assoc_laguerre(n, a, x), a)
1352
+ Sum(assoc_laguerre(_k, a, x)/(-a + n), (_k, 0, n - 1))
1353
+
1354
+ Parameters
1355
+ ==========
1356
+
1357
+ n : int
1358
+ Degree of Laguerre polynomial. Must be `n \ge 0`.
1359
+
1360
+ alpha : Expr
1361
+ Arbitrary expression. For ``alpha=0`` regular Laguerre
1362
+ polynomials will be generated.
1363
+
1364
+ See Also
1365
+ ========
1366
+
1367
+ jacobi, gegenbauer,
1368
+ chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root,
1369
+ legendre, assoc_legendre,
1370
+ hermite, hermite_prob,
1371
+ laguerre,
1372
+ sympy.polys.orthopolys.jacobi_poly
1373
+ sympy.polys.orthopolys.gegenbauer_poly
1374
+ sympy.polys.orthopolys.chebyshevt_poly
1375
+ sympy.polys.orthopolys.chebyshevu_poly
1376
+ sympy.polys.orthopolys.hermite_poly
1377
+ sympy.polys.orthopolys.hermite_prob_poly
1378
+ sympy.polys.orthopolys.legendre_poly
1379
+ sympy.polys.orthopolys.laguerre_poly
1380
+
1381
+ References
1382
+ ==========
1383
+
1384
+ .. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial#Generalized_Laguerre_polynomials
1385
+ .. [2] https://mathworld.wolfram.com/AssociatedLaguerrePolynomial.html
1386
+ .. [3] https://functions.wolfram.com/Polynomials/LaguerreL/
1387
+ .. [4] https://functions.wolfram.com/Polynomials/LaguerreL3/
1388
+
1389
+ """
1390
+
1391
+ @classmethod
1392
+ def eval(cls, n, alpha, x):
1393
+ # L_{n}^{0}(x) ---> L_{n}(x)
1394
+ if alpha.is_zero:
1395
+ return laguerre(n, x)
1396
+
1397
+ if not n.is_Number:
1398
+ # We can evaluate for some special values of x
1399
+ if x.is_zero:
1400
+ return binomial(n + alpha, alpha)
1401
+ elif x is S.Infinity and n > 0:
1402
+ return S.NegativeOne**n * S.Infinity
1403
+ elif x is S.NegativeInfinity and n > 0:
1404
+ return S.Infinity
1405
+ else:
1406
+ # n is a given fixed integer, evaluate into polynomial
1407
+ if n.is_negative:
1408
+ raise ValueError(
1409
+ "The index n must be nonnegative integer (got %r)" % n)
1410
+ else:
1411
+ return laguerre_poly(n, x, alpha)
1412
+
1413
+ def fdiff(self, argindex=3):
1414
+ from sympy.concrete.summations import Sum
1415
+ if argindex == 1:
1416
+ # Diff wrt n
1417
+ raise ArgumentIndexError(self, argindex)
1418
+ elif argindex == 2:
1419
+ # Diff wrt alpha
1420
+ n, alpha, x = self.args
1421
+ k = Dummy("k")
1422
+ return Sum(assoc_laguerre(k, alpha, x) / (n - alpha), (k, 0, n - 1))
1423
+ elif argindex == 3:
1424
+ # Diff wrt x
1425
+ n, alpha, x = self.args
1426
+ return -assoc_laguerre(n - 1, alpha + 1, x)
1427
+ else:
1428
+ raise ArgumentIndexError(self, argindex)
1429
+
1430
+ def _eval_rewrite_as_Sum(self, n, alpha, x, **kwargs):
1431
+ from sympy.concrete.summations import Sum
1432
+ # Make sure n \in N_0
1433
+ if n.is_negative or n.is_integer is False:
1434
+ raise ValueError("Error: n should be a non-negative integer.")
1435
+ k = Dummy("k")
1436
+ kern = RisingFactorial(
1437
+ -n, k) / (gamma(k + alpha + 1) * factorial(k)) * x**k
1438
+ return gamma(n + alpha + 1) / factorial(n) * Sum(kern, (k, 0, n))
1439
+
1440
+ def _eval_rewrite_as_polynomial(self, n, alpha, x, **kwargs):
1441
+ # This function is just kept for backwards compatibility
1442
+ # but should not be used
1443
+ return self._eval_rewrite_as_Sum(n, alpha, x, **kwargs)
1444
+
1445
+ def _eval_conjugate(self):
1446
+ n, alpha, x = self.args
1447
+ return self.func(n, alpha.conjugate(), x.conjugate())
venv/lib/python3.10/site-packages/sympy/functions/special/singularity_functions.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, oo, diff
2
+ from sympy.core.function import Function, ArgumentIndexError
3
+ from sympy.core.logic import fuzzy_not
4
+ from sympy.core.relational import Eq
5
+ from sympy.functions.elementary.complexes import im
6
+ from sympy.functions.elementary.piecewise import Piecewise
7
+ from sympy.functions.special.delta_functions import Heaviside
8
+
9
+ ###############################################################################
10
+ ############################# SINGULARITY FUNCTION ############################
11
+ ###############################################################################
12
+
13
+
14
+ class SingularityFunction(Function):
15
+ r"""
16
+ Singularity functions are a class of discontinuous functions.
17
+
18
+ Explanation
19
+ ===========
20
+
21
+ Singularity functions take a variable, an offset, and an exponent as
22
+ arguments. These functions are represented using Macaulay brackets as:
23
+
24
+ SingularityFunction(x, a, n) := <x - a>^n
25
+
26
+ The singularity function will automatically evaluate to
27
+ ``Derivative(DiracDelta(x - a), x, -n - 1)`` if ``n < 0``
28
+ and ``(x - a)**n*Heaviside(x - a)`` if ``n >= 0``.
29
+
30
+ Examples
31
+ ========
32
+
33
+ >>> from sympy import SingularityFunction, diff, Piecewise, DiracDelta, Heaviside, Symbol
34
+ >>> from sympy.abc import x, a, n
35
+ >>> SingularityFunction(x, a, n)
36
+ SingularityFunction(x, a, n)
37
+ >>> y = Symbol('y', positive=True)
38
+ >>> n = Symbol('n', nonnegative=True)
39
+ >>> SingularityFunction(y, -10, n)
40
+ (y + 10)**n
41
+ >>> y = Symbol('y', negative=True)
42
+ >>> SingularityFunction(y, 10, n)
43
+ 0
44
+ >>> SingularityFunction(x, 4, -1).subs(x, 4)
45
+ oo
46
+ >>> SingularityFunction(x, 10, -2).subs(x, 10)
47
+ oo
48
+ >>> SingularityFunction(4, 1, 5)
49
+ 243
50
+ >>> diff(SingularityFunction(x, 1, 5) + SingularityFunction(x, 1, 4), x)
51
+ 4*SingularityFunction(x, 1, 3) + 5*SingularityFunction(x, 1, 4)
52
+ >>> diff(SingularityFunction(x, 4, 0), x, 2)
53
+ SingularityFunction(x, 4, -2)
54
+ >>> SingularityFunction(x, 4, 5).rewrite(Piecewise)
55
+ Piecewise(((x - 4)**5, x > 4), (0, True))
56
+ >>> expr = SingularityFunction(x, a, n)
57
+ >>> y = Symbol('y', positive=True)
58
+ >>> n = Symbol('n', nonnegative=True)
59
+ >>> expr.subs({x: y, a: -10, n: n})
60
+ (y + 10)**n
61
+
62
+ The methods ``rewrite(DiracDelta)``, ``rewrite(Heaviside)``, and
63
+ ``rewrite('HeavisideDiracDelta')`` returns the same output. One can use any
64
+ of these methods according to their choice.
65
+
66
+ >>> expr = SingularityFunction(x, 4, 5) + SingularityFunction(x, -3, -1) - SingularityFunction(x, 0, -2)
67
+ >>> expr.rewrite(Heaviside)
68
+ (x - 4)**5*Heaviside(x - 4) + DiracDelta(x + 3) - DiracDelta(x, 1)
69
+ >>> expr.rewrite(DiracDelta)
70
+ (x - 4)**5*Heaviside(x - 4) + DiracDelta(x + 3) - DiracDelta(x, 1)
71
+ >>> expr.rewrite('HeavisideDiracDelta')
72
+ (x - 4)**5*Heaviside(x - 4) + DiracDelta(x + 3) - DiracDelta(x, 1)
73
+
74
+ See Also
75
+ ========
76
+
77
+ DiracDelta, Heaviside
78
+
79
+ References
80
+ ==========
81
+
82
+ .. [1] https://en.wikipedia.org/wiki/Singularity_function
83
+
84
+ """
85
+
86
+ is_real = True
87
+
88
+ def fdiff(self, argindex=1):
89
+ """
90
+ Returns the first derivative of a DiracDelta Function.
91
+
92
+ Explanation
93
+ ===========
94
+
95
+ The difference between ``diff()`` and ``fdiff()`` is: ``diff()`` is the
96
+ user-level function and ``fdiff()`` is an object method. ``fdiff()`` is
97
+ a convenience method available in the ``Function`` class. It returns
98
+ the derivative of the function without considering the chain rule.
99
+ ``diff(function, x)`` calls ``Function._eval_derivative`` which in turn
100
+ calls ``fdiff()`` internally to compute the derivative of the function.
101
+
102
+ """
103
+
104
+ if argindex == 1:
105
+ x, a, n = self.args
106
+ if n in (S.Zero, S.NegativeOne):
107
+ return self.func(x, a, n-1)
108
+ elif n.is_positive:
109
+ return n*self.func(x, a, n-1)
110
+ else:
111
+ raise ArgumentIndexError(self, argindex)
112
+
113
+ @classmethod
114
+ def eval(cls, variable, offset, exponent):
115
+ """
116
+ Returns a simplified form or a value of Singularity Function depending
117
+ on the argument passed by the object.
118
+
119
+ Explanation
120
+ ===========
121
+
122
+ The ``eval()`` method is automatically called when the
123
+ ``SingularityFunction`` class is about to be instantiated and it
124
+ returns either some simplified instance or the unevaluated instance
125
+ depending on the argument passed. In other words, ``eval()`` method is
126
+ not needed to be called explicitly, it is being called and evaluated
127
+ once the object is called.
128
+
129
+ Examples
130
+ ========
131
+
132
+ >>> from sympy import SingularityFunction, Symbol, nan
133
+ >>> from sympy.abc import x, a, n
134
+ >>> SingularityFunction(x, a, n)
135
+ SingularityFunction(x, a, n)
136
+ >>> SingularityFunction(5, 3, 2)
137
+ 4
138
+ >>> SingularityFunction(x, a, nan)
139
+ nan
140
+ >>> SingularityFunction(x, 3, 0).subs(x, 3)
141
+ 1
142
+ >>> SingularityFunction(4, 1, 5)
143
+ 243
144
+ >>> x = Symbol('x', positive = True)
145
+ >>> a = Symbol('a', negative = True)
146
+ >>> n = Symbol('n', nonnegative = True)
147
+ >>> SingularityFunction(x, a, n)
148
+ (-a + x)**n
149
+ >>> x = Symbol('x', negative = True)
150
+ >>> a = Symbol('a', positive = True)
151
+ >>> SingularityFunction(x, a, n)
152
+ 0
153
+
154
+ """
155
+
156
+ x = variable
157
+ a = offset
158
+ n = exponent
159
+ shift = (x - a)
160
+
161
+ if fuzzy_not(im(shift).is_zero):
162
+ raise ValueError("Singularity Functions are defined only for Real Numbers.")
163
+ if fuzzy_not(im(n).is_zero):
164
+ raise ValueError("Singularity Functions are not defined for imaginary exponents.")
165
+ if shift is S.NaN or n is S.NaN:
166
+ return S.NaN
167
+ if (n + 2).is_negative:
168
+ raise ValueError("Singularity Functions are not defined for exponents less than -2.")
169
+ if shift.is_extended_negative:
170
+ return S.Zero
171
+ if n.is_nonnegative and shift.is_extended_nonnegative:
172
+ return (x - a)**n
173
+ if n in (S.NegativeOne, -2):
174
+ if shift.is_negative or shift.is_extended_positive:
175
+ return S.Zero
176
+ if shift.is_zero:
177
+ return oo
178
+
179
+ def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
180
+ '''
181
+ Converts a Singularity Function expression into its Piecewise form.
182
+
183
+ '''
184
+ x, a, n = self.args
185
+
186
+ if n in (S.NegativeOne, S(-2)):
187
+ return Piecewise((oo, Eq((x - a), 0)), (0, True))
188
+ elif n.is_nonnegative:
189
+ return Piecewise(((x - a)**n, (x - a) > 0), (0, True))
190
+
191
+ def _eval_rewrite_as_Heaviside(self, *args, **kwargs):
192
+ '''
193
+ Rewrites a Singularity Function expression using Heavisides and DiracDeltas.
194
+
195
+ '''
196
+ x, a, n = self.args
197
+
198
+ if n == -2:
199
+ return diff(Heaviside(x - a), x.free_symbols.pop(), 2)
200
+ if n == -1:
201
+ return diff(Heaviside(x - a), x.free_symbols.pop(), 1)
202
+ if n.is_nonnegative:
203
+ return (x - a)**n*Heaviside(x - a)
204
+
205
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
206
+ z, a, n = self.args
207
+ shift = (z - a).subs(x, 0)
208
+ if n < 0:
209
+ return S.Zero
210
+ elif n.is_zero and shift.is_zero:
211
+ return S.Zero if cdir == -1 else S.One
212
+ elif shift.is_positive:
213
+ return shift**n
214
+ return S.Zero
215
+
216
+ def _eval_nseries(self, x, n, logx=None, cdir=0):
217
+ z, a, n = self.args
218
+ shift = (z - a).subs(x, 0)
219
+ if n < 0:
220
+ return S.Zero
221
+ elif n.is_zero and shift.is_zero:
222
+ return S.Zero if cdir == -1 else S.One
223
+ elif shift.is_positive:
224
+ return ((z - a)**n)._eval_nseries(x, n, logx=logx, cdir=cdir)
225
+ return S.Zero
226
+
227
+ _eval_rewrite_as_DiracDelta = _eval_rewrite_as_Heaviside
228
+ _eval_rewrite_as_HeavisideDiracDelta = _eval_rewrite_as_Heaviside
venv/lib/python3.10/site-packages/sympy/functions/special/spherical_harmonics.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.expr import Expr
2
+ from sympy.core.function import Function, ArgumentIndexError
3
+ from sympy.core.numbers import I, pi
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import Dummy
6
+ from sympy.functions import assoc_legendre
7
+ from sympy.functions.combinatorial.factorials import factorial
8
+ from sympy.functions.elementary.complexes import Abs, conjugate
9
+ from sympy.functions.elementary.exponential import exp
10
+ from sympy.functions.elementary.miscellaneous import sqrt
11
+ from sympy.functions.elementary.trigonometric import sin, cos, cot
12
+
13
+ _x = Dummy("x")
14
+
15
+ class Ynm(Function):
16
+ r"""
17
+ Spherical harmonics defined as
18
+
19
+ .. math::
20
+ Y_n^m(\theta, \varphi) := \sqrt{\frac{(2n+1)(n-m)!}{4\pi(n+m)!}}
21
+ \exp(i m \varphi)
22
+ \mathrm{P}_n^m\left(\cos(\theta)\right)
23
+
24
+ Explanation
25
+ ===========
26
+
27
+ ``Ynm()`` gives the spherical harmonic function of order $n$ and $m$
28
+ in $\theta$ and $\varphi$, $Y_n^m(\theta, \varphi)$. The four
29
+ parameters are as follows: $n \geq 0$ an integer and $m$ an integer
30
+ such that $-n \leq m \leq n$ holds. The two angles are real-valued
31
+ with $\theta \in [0, \pi]$ and $\varphi \in [0, 2\pi]$.
32
+
33
+ Examples
34
+ ========
35
+
36
+ >>> from sympy import Ynm, Symbol, simplify
37
+ >>> from sympy.abc import n,m
38
+ >>> theta = Symbol("theta")
39
+ >>> phi = Symbol("phi")
40
+
41
+ >>> Ynm(n, m, theta, phi)
42
+ Ynm(n, m, theta, phi)
43
+
44
+ Several symmetries are known, for the order:
45
+
46
+ >>> Ynm(n, -m, theta, phi)
47
+ (-1)**m*exp(-2*I*m*phi)*Ynm(n, m, theta, phi)
48
+
49
+ As well as for the angles:
50
+
51
+ >>> Ynm(n, m, -theta, phi)
52
+ Ynm(n, m, theta, phi)
53
+
54
+ >>> Ynm(n, m, theta, -phi)
55
+ exp(-2*I*m*phi)*Ynm(n, m, theta, phi)
56
+
57
+ For specific integers $n$ and $m$ we can evaluate the harmonics
58
+ to more useful expressions:
59
+
60
+ >>> simplify(Ynm(0, 0, theta, phi).expand(func=True))
61
+ 1/(2*sqrt(pi))
62
+
63
+ >>> simplify(Ynm(1, -1, theta, phi).expand(func=True))
64
+ sqrt(6)*exp(-I*phi)*sin(theta)/(4*sqrt(pi))
65
+
66
+ >>> simplify(Ynm(1, 0, theta, phi).expand(func=True))
67
+ sqrt(3)*cos(theta)/(2*sqrt(pi))
68
+
69
+ >>> simplify(Ynm(1, 1, theta, phi).expand(func=True))
70
+ -sqrt(6)*exp(I*phi)*sin(theta)/(4*sqrt(pi))
71
+
72
+ >>> simplify(Ynm(2, -2, theta, phi).expand(func=True))
73
+ sqrt(30)*exp(-2*I*phi)*sin(theta)**2/(8*sqrt(pi))
74
+
75
+ >>> simplify(Ynm(2, -1, theta, phi).expand(func=True))
76
+ sqrt(30)*exp(-I*phi)*sin(2*theta)/(8*sqrt(pi))
77
+
78
+ >>> simplify(Ynm(2, 0, theta, phi).expand(func=True))
79
+ sqrt(5)*(3*cos(theta)**2 - 1)/(4*sqrt(pi))
80
+
81
+ >>> simplify(Ynm(2, 1, theta, phi).expand(func=True))
82
+ -sqrt(30)*exp(I*phi)*sin(2*theta)/(8*sqrt(pi))
83
+
84
+ >>> simplify(Ynm(2, 2, theta, phi).expand(func=True))
85
+ sqrt(30)*exp(2*I*phi)*sin(theta)**2/(8*sqrt(pi))
86
+
87
+ We can differentiate the functions with respect
88
+ to both angles:
89
+
90
+ >>> from sympy import Ynm, Symbol, diff
91
+ >>> from sympy.abc import n,m
92
+ >>> theta = Symbol("theta")
93
+ >>> phi = Symbol("phi")
94
+
95
+ >>> diff(Ynm(n, m, theta, phi), theta)
96
+ m*cot(theta)*Ynm(n, m, theta, phi) + sqrt((-m + n)*(m + n + 1))*exp(-I*phi)*Ynm(n, m + 1, theta, phi)
97
+
98
+ >>> diff(Ynm(n, m, theta, phi), phi)
99
+ I*m*Ynm(n, m, theta, phi)
100
+
101
+ Further we can compute the complex conjugation:
102
+
103
+ >>> from sympy import Ynm, Symbol, conjugate
104
+ >>> from sympy.abc import n,m
105
+ >>> theta = Symbol("theta")
106
+ >>> phi = Symbol("phi")
107
+
108
+ >>> conjugate(Ynm(n, m, theta, phi))
109
+ (-1)**(2*m)*exp(-2*I*m*phi)*Ynm(n, m, theta, phi)
110
+
111
+ To get back the well known expressions in spherical
112
+ coordinates, we use full expansion:
113
+
114
+ >>> from sympy import Ynm, Symbol, expand_func
115
+ >>> from sympy.abc import n,m
116
+ >>> theta = Symbol("theta")
117
+ >>> phi = Symbol("phi")
118
+
119
+ >>> expand_func(Ynm(n, m, theta, phi))
120
+ sqrt((2*n + 1)*factorial(-m + n)/factorial(m + n))*exp(I*m*phi)*assoc_legendre(n, m, cos(theta))/(2*sqrt(pi))
121
+
122
+ See Also
123
+ ========
124
+
125
+ Ynm_c, Znm
126
+
127
+ References
128
+ ==========
129
+
130
+ .. [1] https://en.wikipedia.org/wiki/Spherical_harmonics
131
+ .. [2] https://mathworld.wolfram.com/SphericalHarmonic.html
132
+ .. [3] https://functions.wolfram.com/Polynomials/SphericalHarmonicY/
133
+ .. [4] https://dlmf.nist.gov/14.30
134
+
135
+ """
136
+
137
+ @classmethod
138
+ def eval(cls, n, m, theta, phi):
139
+ # Handle negative index m and arguments theta, phi
140
+ if m.could_extract_minus_sign():
141
+ m = -m
142
+ return S.NegativeOne**m * exp(-2*I*m*phi) * Ynm(n, m, theta, phi)
143
+ if theta.could_extract_minus_sign():
144
+ theta = -theta
145
+ return Ynm(n, m, theta, phi)
146
+ if phi.could_extract_minus_sign():
147
+ phi = -phi
148
+ return exp(-2*I*m*phi) * Ynm(n, m, theta, phi)
149
+
150
+ # TODO Add more simplififcation here
151
+
152
+ def _eval_expand_func(self, **hints):
153
+ n, m, theta, phi = self.args
154
+ rv = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) *
155
+ exp(I*m*phi) * assoc_legendre(n, m, cos(theta)))
156
+ # We can do this because of the range of theta
157
+ return rv.subs(sqrt(-cos(theta)**2 + 1), sin(theta))
158
+
159
+ def fdiff(self, argindex=4):
160
+ if argindex == 1:
161
+ # Diff wrt n
162
+ raise ArgumentIndexError(self, argindex)
163
+ elif argindex == 2:
164
+ # Diff wrt m
165
+ raise ArgumentIndexError(self, argindex)
166
+ elif argindex == 3:
167
+ # Diff wrt theta
168
+ n, m, theta, phi = self.args
169
+ return (m * cot(theta) * Ynm(n, m, theta, phi) +
170
+ sqrt((n - m)*(n + m + 1)) * exp(-I*phi) * Ynm(n, m + 1, theta, phi))
171
+ elif argindex == 4:
172
+ # Diff wrt phi
173
+ n, m, theta, phi = self.args
174
+ return I * m * Ynm(n, m, theta, phi)
175
+ else:
176
+ raise ArgumentIndexError(self, argindex)
177
+
178
+ def _eval_rewrite_as_polynomial(self, n, m, theta, phi, **kwargs):
179
+ # TODO: Make sure n \in N
180
+ # TODO: Assert |m| <= n ortherwise we should return 0
181
+ return self.expand(func=True)
182
+
183
+ def _eval_rewrite_as_sin(self, n, m, theta, phi, **kwargs):
184
+ return self.rewrite(cos)
185
+
186
+ def _eval_rewrite_as_cos(self, n, m, theta, phi, **kwargs):
187
+ # This method can be expensive due to extensive use of simplification!
188
+ from sympy.simplify import simplify, trigsimp
189
+ # TODO: Make sure n \in N
190
+ # TODO: Assert |m| <= n ortherwise we should return 0
191
+ term = simplify(self.expand(func=True))
192
+ # We can do this because of the range of theta
193
+ term = term.xreplace({Abs(sin(theta)):sin(theta)})
194
+ return simplify(trigsimp(term))
195
+
196
+ def _eval_conjugate(self):
197
+ # TODO: Make sure theta \in R and phi \in R
198
+ n, m, theta, phi = self.args
199
+ return S.NegativeOne**m * self.func(n, -m, theta, phi)
200
+
201
+ def as_real_imag(self, deep=True, **hints):
202
+ # TODO: Handle deep and hints
203
+ n, m, theta, phi = self.args
204
+ re = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) *
205
+ cos(m*phi) * assoc_legendre(n, m, cos(theta)))
206
+ im = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) *
207
+ sin(m*phi) * assoc_legendre(n, m, cos(theta)))
208
+ return (re, im)
209
+
210
+ def _eval_evalf(self, prec):
211
+ # Note: works without this function by just calling
212
+ # mpmath for Legendre polynomials. But using
213
+ # the dedicated function directly is cleaner.
214
+ from mpmath import mp, workprec
215
+ n = self.args[0]._to_mpmath(prec)
216
+ m = self.args[1]._to_mpmath(prec)
217
+ theta = self.args[2]._to_mpmath(prec)
218
+ phi = self.args[3]._to_mpmath(prec)
219
+ with workprec(prec):
220
+ res = mp.spherharm(n, m, theta, phi)
221
+ return Expr._from_mpmath(res, prec)
222
+
223
+
224
+ def Ynm_c(n, m, theta, phi):
225
+ r"""
226
+ Conjugate spherical harmonics defined as
227
+
228
+ .. math::
229
+ \overline{Y_n^m(\theta, \varphi)} := (-1)^m Y_n^{-m}(\theta, \varphi).
230
+
231
+ Examples
232
+ ========
233
+
234
+ >>> from sympy import Ynm_c, Symbol, simplify
235
+ >>> from sympy.abc import n,m
236
+ >>> theta = Symbol("theta")
237
+ >>> phi = Symbol("phi")
238
+ >>> Ynm_c(n, m, theta, phi)
239
+ (-1)**(2*m)*exp(-2*I*m*phi)*Ynm(n, m, theta, phi)
240
+ >>> Ynm_c(n, m, -theta, phi)
241
+ (-1)**(2*m)*exp(-2*I*m*phi)*Ynm(n, m, theta, phi)
242
+
243
+ For specific integers $n$ and $m$ we can evaluate the harmonics
244
+ to more useful expressions:
245
+
246
+ >>> simplify(Ynm_c(0, 0, theta, phi).expand(func=True))
247
+ 1/(2*sqrt(pi))
248
+ >>> simplify(Ynm_c(1, -1, theta, phi).expand(func=True))
249
+ sqrt(6)*exp(I*(-phi + 2*conjugate(phi)))*sin(theta)/(4*sqrt(pi))
250
+
251
+ See Also
252
+ ========
253
+
254
+ Ynm, Znm
255
+
256
+ References
257
+ ==========
258
+
259
+ .. [1] https://en.wikipedia.org/wiki/Spherical_harmonics
260
+ .. [2] https://mathworld.wolfram.com/SphericalHarmonic.html
261
+ .. [3] https://functions.wolfram.com/Polynomials/SphericalHarmonicY/
262
+
263
+ """
264
+ return conjugate(Ynm(n, m, theta, phi))
265
+
266
+
267
+ class Znm(Function):
268
+ r"""
269
+ Real spherical harmonics defined as
270
+
271
+ .. math::
272
+
273
+ Z_n^m(\theta, \varphi) :=
274
+ \begin{cases}
275
+ \frac{Y_n^m(\theta, \varphi) + \overline{Y_n^m(\theta, \varphi)}}{\sqrt{2}} &\quad m > 0 \\
276
+ Y_n^m(\theta, \varphi) &\quad m = 0 \\
277
+ \frac{Y_n^m(\theta, \varphi) - \overline{Y_n^m(\theta, \varphi)}}{i \sqrt{2}} &\quad m < 0 \\
278
+ \end{cases}
279
+
280
+ which gives in simplified form
281
+
282
+ .. math::
283
+
284
+ Z_n^m(\theta, \varphi) =
285
+ \begin{cases}
286
+ \frac{Y_n^m(\theta, \varphi) + (-1)^m Y_n^{-m}(\theta, \varphi)}{\sqrt{2}} &\quad m > 0 \\
287
+ Y_n^m(\theta, \varphi) &\quad m = 0 \\
288
+ \frac{Y_n^m(\theta, \varphi) - (-1)^m Y_n^{-m}(\theta, \varphi)}{i \sqrt{2}} &\quad m < 0 \\
289
+ \end{cases}
290
+
291
+ Examples
292
+ ========
293
+
294
+ >>> from sympy import Znm, Symbol, simplify
295
+ >>> from sympy.abc import n, m
296
+ >>> theta = Symbol("theta")
297
+ >>> phi = Symbol("phi")
298
+ >>> Znm(n, m, theta, phi)
299
+ Znm(n, m, theta, phi)
300
+
301
+ For specific integers n and m we can evaluate the harmonics
302
+ to more useful expressions:
303
+
304
+ >>> simplify(Znm(0, 0, theta, phi).expand(func=True))
305
+ 1/(2*sqrt(pi))
306
+ >>> simplify(Znm(1, 1, theta, phi).expand(func=True))
307
+ -sqrt(3)*sin(theta)*cos(phi)/(2*sqrt(pi))
308
+ >>> simplify(Znm(2, 1, theta, phi).expand(func=True))
309
+ -sqrt(15)*sin(2*theta)*cos(phi)/(4*sqrt(pi))
310
+
311
+ See Also
312
+ ========
313
+
314
+ Ynm, Ynm_c
315
+
316
+ References
317
+ ==========
318
+
319
+ .. [1] https://en.wikipedia.org/wiki/Spherical_harmonics
320
+ .. [2] https://mathworld.wolfram.com/SphericalHarmonic.html
321
+ .. [3] https://functions.wolfram.com/Polynomials/SphericalHarmonicY/
322
+
323
+ """
324
+
325
+ @classmethod
326
+ def eval(cls, n, m, theta, phi):
327
+ if m.is_positive:
328
+ zz = (Ynm(n, m, theta, phi) + Ynm_c(n, m, theta, phi)) / sqrt(2)
329
+ return zz
330
+ elif m.is_zero:
331
+ return Ynm(n, m, theta, phi)
332
+ elif m.is_negative:
333
+ zz = (Ynm(n, m, theta, phi) - Ynm_c(n, m, theta, phi)) / (sqrt(2)*I)
334
+ return zz
venv/lib/python3.10/site-packages/sympy/functions/special/tensor_functions.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import prod
2
+
3
+ from sympy.core import S, Integer
4
+ from sympy.core.function import Function
5
+ from sympy.core.logic import fuzzy_not
6
+ from sympy.core.relational import Ne
7
+ from sympy.core.sorting import default_sort_key
8
+ from sympy.external.gmpy import SYMPY_INTS
9
+ from sympy.functions.combinatorial.factorials import factorial
10
+ from sympy.functions.elementary.piecewise import Piecewise
11
+ from sympy.utilities.iterables import has_dups
12
+
13
+ ###############################################################################
14
+ ###################### Kronecker Delta, Levi-Civita etc. ######################
15
+ ###############################################################################
16
+
17
+
18
+ def Eijk(*args, **kwargs):
19
+ """
20
+ Represent the Levi-Civita symbol.
21
+
22
+ This is a compatibility wrapper to ``LeviCivita()``.
23
+
24
+ See Also
25
+ ========
26
+
27
+ LeviCivita
28
+
29
+ """
30
+ return LeviCivita(*args, **kwargs)
31
+
32
+
33
+ def eval_levicivita(*args):
34
+ """Evaluate Levi-Civita symbol."""
35
+ n = len(args)
36
+ return prod(
37
+ prod(args[j] - args[i] for j in range(i + 1, n))
38
+ / factorial(i) for i in range(n))
39
+ # converting factorial(i) to int is slightly faster
40
+
41
+
42
+ class LeviCivita(Function):
43
+ """
44
+ Represent the Levi-Civita symbol.
45
+
46
+ Explanation
47
+ ===========
48
+
49
+ For even permutations of indices it returns 1, for odd permutations -1, and
50
+ for everything else (a repeated index) it returns 0.
51
+
52
+ Thus it represents an alternating pseudotensor.
53
+
54
+ Examples
55
+ ========
56
+
57
+ >>> from sympy import LeviCivita
58
+ >>> from sympy.abc import i, j, k
59
+ >>> LeviCivita(1, 2, 3)
60
+ 1
61
+ >>> LeviCivita(1, 3, 2)
62
+ -1
63
+ >>> LeviCivita(1, 2, 2)
64
+ 0
65
+ >>> LeviCivita(i, j, k)
66
+ LeviCivita(i, j, k)
67
+ >>> LeviCivita(i, j, i)
68
+ 0
69
+
70
+ See Also
71
+ ========
72
+
73
+ Eijk
74
+
75
+ """
76
+
77
+ is_integer = True
78
+
79
+ @classmethod
80
+ def eval(cls, *args):
81
+ if all(isinstance(a, (SYMPY_INTS, Integer)) for a in args):
82
+ return eval_levicivita(*args)
83
+ if has_dups(args):
84
+ return S.Zero
85
+
86
+ def doit(self, **hints):
87
+ return eval_levicivita(*self.args)
88
+
89
+
90
+ class KroneckerDelta(Function):
91
+ """
92
+ The discrete, or Kronecker, delta function.
93
+
94
+ Explanation
95
+ ===========
96
+
97
+ A function that takes in two integers $i$ and $j$. It returns $0$ if $i$
98
+ and $j$ are not equal, or it returns $1$ if $i$ and $j$ are equal.
99
+
100
+ Examples
101
+ ========
102
+
103
+ An example with integer indices:
104
+
105
+ >>> from sympy import KroneckerDelta
106
+ >>> KroneckerDelta(1, 2)
107
+ 0
108
+ >>> KroneckerDelta(3, 3)
109
+ 1
110
+
111
+ Symbolic indices:
112
+
113
+ >>> from sympy.abc import i, j, k
114
+ >>> KroneckerDelta(i, j)
115
+ KroneckerDelta(i, j)
116
+ >>> KroneckerDelta(i, i)
117
+ 1
118
+ >>> KroneckerDelta(i, i + 1)
119
+ 0
120
+ >>> KroneckerDelta(i, i + 1 + k)
121
+ KroneckerDelta(i, i + k + 1)
122
+
123
+ Parameters
124
+ ==========
125
+
126
+ i : Number, Symbol
127
+ The first index of the delta function.
128
+ j : Number, Symbol
129
+ The second index of the delta function.
130
+
131
+ See Also
132
+ ========
133
+
134
+ eval
135
+ DiracDelta
136
+
137
+ References
138
+ ==========
139
+
140
+ .. [1] https://en.wikipedia.org/wiki/Kronecker_delta
141
+
142
+ """
143
+
144
+ is_integer = True
145
+
146
+ @classmethod
147
+ def eval(cls, i, j, delta_range=None):
148
+ """
149
+ Evaluates the discrete delta function.
150
+
151
+ Examples
152
+ ========
153
+
154
+ >>> from sympy import KroneckerDelta
155
+ >>> from sympy.abc import i, j, k
156
+
157
+ >>> KroneckerDelta(i, j)
158
+ KroneckerDelta(i, j)
159
+ >>> KroneckerDelta(i, i)
160
+ 1
161
+ >>> KroneckerDelta(i, i + 1)
162
+ 0
163
+ >>> KroneckerDelta(i, i + 1 + k)
164
+ KroneckerDelta(i, i + k + 1)
165
+
166
+ # indirect doctest
167
+
168
+ """
169
+
170
+ if delta_range is not None:
171
+ dinf, dsup = delta_range
172
+ if (dinf - i > 0) == True:
173
+ return S.Zero
174
+ if (dinf - j > 0) == True:
175
+ return S.Zero
176
+ if (dsup - i < 0) == True:
177
+ return S.Zero
178
+ if (dsup - j < 0) == True:
179
+ return S.Zero
180
+
181
+ diff = i - j
182
+ if diff.is_zero:
183
+ return S.One
184
+ elif fuzzy_not(diff.is_zero):
185
+ return S.Zero
186
+
187
+ if i.assumptions0.get("below_fermi") and \
188
+ j.assumptions0.get("above_fermi"):
189
+ return S.Zero
190
+ if j.assumptions0.get("below_fermi") and \
191
+ i.assumptions0.get("above_fermi"):
192
+ return S.Zero
193
+ # to make KroneckerDelta canonical
194
+ # following lines will check if inputs are in order
195
+ # if not, will return KroneckerDelta with correct order
196
+ if i != min(i, j, key=default_sort_key):
197
+ if delta_range:
198
+ return cls(j, i, delta_range)
199
+ else:
200
+ return cls(j, i)
201
+
202
+ @property
203
+ def delta_range(self):
204
+ if len(self.args) > 2:
205
+ return self.args[2]
206
+
207
+ def _eval_power(self, expt):
208
+ if expt.is_positive:
209
+ return self
210
+ if expt.is_negative and expt is not S.NegativeOne:
211
+ return 1/self
212
+
213
+ @property
214
+ def is_above_fermi(self):
215
+ """
216
+ True if Delta can be non-zero above fermi.
217
+
218
+ Examples
219
+ ========
220
+
221
+ >>> from sympy import KroneckerDelta, Symbol
222
+ >>> a = Symbol('a', above_fermi=True)
223
+ >>> i = Symbol('i', below_fermi=True)
224
+ >>> p = Symbol('p')
225
+ >>> q = Symbol('q')
226
+ >>> KroneckerDelta(p, a).is_above_fermi
227
+ True
228
+ >>> KroneckerDelta(p, i).is_above_fermi
229
+ False
230
+ >>> KroneckerDelta(p, q).is_above_fermi
231
+ True
232
+
233
+ See Also
234
+ ========
235
+
236
+ is_below_fermi, is_only_below_fermi, is_only_above_fermi
237
+
238
+ """
239
+ if self.args[0].assumptions0.get("below_fermi"):
240
+ return False
241
+ if self.args[1].assumptions0.get("below_fermi"):
242
+ return False
243
+ return True
244
+
245
+ @property
246
+ def is_below_fermi(self):
247
+ """
248
+ True if Delta can be non-zero below fermi.
249
+
250
+ Examples
251
+ ========
252
+
253
+ >>> from sympy import KroneckerDelta, Symbol
254
+ >>> a = Symbol('a', above_fermi=True)
255
+ >>> i = Symbol('i', below_fermi=True)
256
+ >>> p = Symbol('p')
257
+ >>> q = Symbol('q')
258
+ >>> KroneckerDelta(p, a).is_below_fermi
259
+ False
260
+ >>> KroneckerDelta(p, i).is_below_fermi
261
+ True
262
+ >>> KroneckerDelta(p, q).is_below_fermi
263
+ True
264
+
265
+ See Also
266
+ ========
267
+
268
+ is_above_fermi, is_only_above_fermi, is_only_below_fermi
269
+
270
+ """
271
+ if self.args[0].assumptions0.get("above_fermi"):
272
+ return False
273
+ if self.args[1].assumptions0.get("above_fermi"):
274
+ return False
275
+ return True
276
+
277
+ @property
278
+ def is_only_above_fermi(self):
279
+ """
280
+ True if Delta is restricted to above fermi.
281
+
282
+ Examples
283
+ ========
284
+
285
+ >>> from sympy import KroneckerDelta, Symbol
286
+ >>> a = Symbol('a', above_fermi=True)
287
+ >>> i = Symbol('i', below_fermi=True)
288
+ >>> p = Symbol('p')
289
+ >>> q = Symbol('q')
290
+ >>> KroneckerDelta(p, a).is_only_above_fermi
291
+ True
292
+ >>> KroneckerDelta(p, q).is_only_above_fermi
293
+ False
294
+ >>> KroneckerDelta(p, i).is_only_above_fermi
295
+ False
296
+
297
+ See Also
298
+ ========
299
+
300
+ is_above_fermi, is_below_fermi, is_only_below_fermi
301
+
302
+ """
303
+ return ( self.args[0].assumptions0.get("above_fermi")
304
+ or
305
+ self.args[1].assumptions0.get("above_fermi")
306
+ ) or False
307
+
308
+ @property
309
+ def is_only_below_fermi(self):
310
+ """
311
+ True if Delta is restricted to below fermi.
312
+
313
+ Examples
314
+ ========
315
+
316
+ >>> from sympy import KroneckerDelta, Symbol
317
+ >>> a = Symbol('a', above_fermi=True)
318
+ >>> i = Symbol('i', below_fermi=True)
319
+ >>> p = Symbol('p')
320
+ >>> q = Symbol('q')
321
+ >>> KroneckerDelta(p, i).is_only_below_fermi
322
+ True
323
+ >>> KroneckerDelta(p, q).is_only_below_fermi
324
+ False
325
+ >>> KroneckerDelta(p, a).is_only_below_fermi
326
+ False
327
+
328
+ See Also
329
+ ========
330
+
331
+ is_above_fermi, is_below_fermi, is_only_above_fermi
332
+
333
+ """
334
+ return ( self.args[0].assumptions0.get("below_fermi")
335
+ or
336
+ self.args[1].assumptions0.get("below_fermi")
337
+ ) or False
338
+
339
+ @property
340
+ def indices_contain_equal_information(self):
341
+ """
342
+ Returns True if indices are either both above or below fermi.
343
+
344
+ Examples
345
+ ========
346
+
347
+ >>> from sympy import KroneckerDelta, Symbol
348
+ >>> a = Symbol('a', above_fermi=True)
349
+ >>> i = Symbol('i', below_fermi=True)
350
+ >>> p = Symbol('p')
351
+ >>> q = Symbol('q')
352
+ >>> KroneckerDelta(p, q).indices_contain_equal_information
353
+ True
354
+ >>> KroneckerDelta(p, q+1).indices_contain_equal_information
355
+ True
356
+ >>> KroneckerDelta(i, p).indices_contain_equal_information
357
+ False
358
+
359
+ """
360
+ if (self.args[0].assumptions0.get("below_fermi") and
361
+ self.args[1].assumptions0.get("below_fermi")):
362
+ return True
363
+ if (self.args[0].assumptions0.get("above_fermi")
364
+ and self.args[1].assumptions0.get("above_fermi")):
365
+ return True
366
+
367
+ # if both indices are general we are True, else false
368
+ return self.is_below_fermi and self.is_above_fermi
369
+
370
+ @property
371
+ def preferred_index(self):
372
+ """
373
+ Returns the index which is preferred to keep in the final expression.
374
+
375
+ Explanation
376
+ ===========
377
+
378
+ The preferred index is the index with more information regarding fermi
379
+ level. If indices contain the same information, 'a' is preferred before
380
+ 'b'.
381
+
382
+ Examples
383
+ ========
384
+
385
+ >>> from sympy import KroneckerDelta, Symbol
386
+ >>> a = Symbol('a', above_fermi=True)
387
+ >>> i = Symbol('i', below_fermi=True)
388
+ >>> j = Symbol('j', below_fermi=True)
389
+ >>> p = Symbol('p')
390
+ >>> KroneckerDelta(p, i).preferred_index
391
+ i
392
+ >>> KroneckerDelta(p, a).preferred_index
393
+ a
394
+ >>> KroneckerDelta(i, j).preferred_index
395
+ i
396
+
397
+ See Also
398
+ ========
399
+
400
+ killable_index
401
+
402
+ """
403
+ if self._get_preferred_index():
404
+ return self.args[1]
405
+ else:
406
+ return self.args[0]
407
+
408
+ @property
409
+ def killable_index(self):
410
+ """
411
+ Returns the index which is preferred to substitute in the final
412
+ expression.
413
+
414
+ Explanation
415
+ ===========
416
+
417
+ The index to substitute is the index with less information regarding
418
+ fermi level. If indices contain the same information, 'a' is preferred
419
+ before 'b'.
420
+
421
+ Examples
422
+ ========
423
+
424
+ >>> from sympy import KroneckerDelta, Symbol
425
+ >>> a = Symbol('a', above_fermi=True)
426
+ >>> i = Symbol('i', below_fermi=True)
427
+ >>> j = Symbol('j', below_fermi=True)
428
+ >>> p = Symbol('p')
429
+ >>> KroneckerDelta(p, i).killable_index
430
+ p
431
+ >>> KroneckerDelta(p, a).killable_index
432
+ p
433
+ >>> KroneckerDelta(i, j).killable_index
434
+ j
435
+
436
+ See Also
437
+ ========
438
+
439
+ preferred_index
440
+
441
+ """
442
+ if self._get_preferred_index():
443
+ return self.args[0]
444
+ else:
445
+ return self.args[1]
446
+
447
+ def _get_preferred_index(self):
448
+ """
449
+ Returns the index which is preferred to keep in the final expression.
450
+
451
+ The preferred index is the index with more information regarding fermi
452
+ level. If indices contain the same information, index 0 is returned.
453
+
454
+ """
455
+ if not self.is_above_fermi:
456
+ if self.args[0].assumptions0.get("below_fermi"):
457
+ return 0
458
+ else:
459
+ return 1
460
+ elif not self.is_below_fermi:
461
+ if self.args[0].assumptions0.get("above_fermi"):
462
+ return 0
463
+ else:
464
+ return 1
465
+ else:
466
+ return 0
467
+
468
+ @property
469
+ def indices(self):
470
+ return self.args[0:2]
471
+
472
+ def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
473
+ i, j = args
474
+ return Piecewise((0, Ne(i, j)), (1, True))
venv/lib/python3.10/site-packages/sympy/functions/special/tests/__init__.py ADDED
File without changes