applied-ai-018 commited on
Commit
0f7fe19
·
verified ·
1 Parent(s): d6e9cbc

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. llmeval-env/lib/python3.10/site-packages/sympy/functions/__pycache__/__init__.cpython-310.pyc +0 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/__init__.py +1 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/__init__.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/factorials.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/numbers.cpython-310.pyc +0 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/factorials.py +1102 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/numbers.py +2563 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__init__.py +0 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_factorials.cpython-310.pyc +0 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_numbers.cpython-310.pyc +0 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/test_comb_factorials.py +650 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/test_comb_numbers.py +852 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/complexes.cpython-310.pyc +0 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/exponential.cpython-310.pyc +0 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/integers.cpython-310.pyc +0 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__init__.py +0 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__pycache__/bench_exp.cpython-310.pyc +0 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/bench_exp.py +11 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__init__.py +0 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_complexes.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_exponential.cpython-310.pyc +0 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_hyperbolic.cpython-310.pyc +0 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_integers.cpython-310.pyc +0 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_interface.cpython-310.pyc +0 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_miscellaneous.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_piecewise.cpython-310.pyc +0 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_trigonometric.cpython-310.pyc +0 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_complexes.py +1018 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_exponential.py +806 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_hyperbolic.py +1460 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_integers.py +632 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_interface.py +72 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_miscellaneous.py +504 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_piecewise.py +1606 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_trigonometric.py +2162 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__init__.py +1 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/bessel.py +2089 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/beta_functions.py +389 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/bsplines.py +351 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/delta_functions.py +664 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/elliptic_integrals.py +445 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/error_functions.py +2741 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/gamma_functions.py +1344 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/hyper.py +1152 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/mathieu_functions.py +269 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/polynomials.py +1447 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/functions/special/singularity_functions.py +228 -0
llmeval-env/lib/python3.10/site-packages/sympy/functions/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (5.54 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Stub __init__.py for sympy.functions.combinatorial
llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (202 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/factorials.cpython-310.pyc ADDED
Binary file (30.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/numbers.cpython-310.pyc ADDED
Binary file (77 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/factorials.py ADDED
@@ -0,0 +1,1102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from functools import reduce
3
+
4
+ from sympy.core import S, sympify, Dummy, Mod
5
+ from sympy.core.cache import cacheit
6
+ from sympy.core.function import Function, ArgumentIndexError, PoleError
7
+ from sympy.core.logic import fuzzy_and
8
+ from sympy.core.numbers import Integer, pi, I
9
+ from sympy.core.relational import Eq
10
+ from sympy.external.gmpy import HAS_GMPY, gmpy
11
+ from sympy.ntheory import sieve
12
+ from sympy.polys.polytools import Poly
13
+
14
+ from math import factorial as _factorial, prod, sqrt as _sqrt
15
+
16
+ class CombinatorialFunction(Function):
17
+ """Base class for combinatorial functions. """
18
+
19
+ def _eval_simplify(self, **kwargs):
20
+ from sympy.simplify.combsimp import combsimp
21
+ # combinatorial function with non-integer arguments is
22
+ # automatically passed to gammasimp
23
+ expr = combsimp(self)
24
+ measure = kwargs['measure']
25
+ if measure(expr) <= kwargs['ratio']*measure(self):
26
+ return expr
27
+ return self
28
+
29
+
30
+ ###############################################################################
31
+ ######################## FACTORIAL and MULTI-FACTORIAL ########################
32
+ ###############################################################################
33
+
34
+
35
+ class factorial(CombinatorialFunction):
36
+ r"""Implementation of factorial function over nonnegative integers.
37
+ By convention (consistent with the gamma function and the binomial
38
+ coefficients), factorial of a negative integer is complex infinity.
39
+
40
+ The factorial is very important in combinatorics where it gives
41
+ the number of ways in which `n` objects can be permuted. It also
42
+ arises in calculus, probability, number theory, etc.
43
+
44
+ There is strict relation of factorial with gamma function. In
45
+ fact `n! = gamma(n+1)` for nonnegative integers. Rewrite of this
46
+ kind is very useful in case of combinatorial simplification.
47
+
48
+ Computation of the factorial is done using two algorithms. For
49
+ small arguments a precomputed look up table is used. However for bigger
50
+ input algorithm Prime-Swing is used. It is the fastest algorithm
51
+ known and computes `n!` via prime factorization of special class
52
+ of numbers, called here the 'Swing Numbers'.
53
+
54
+ Examples
55
+ ========
56
+
57
+ >>> from sympy import Symbol, factorial, S
58
+ >>> n = Symbol('n', integer=True)
59
+
60
+ >>> factorial(0)
61
+ 1
62
+
63
+ >>> factorial(7)
64
+ 5040
65
+
66
+ >>> factorial(-2)
67
+ zoo
68
+
69
+ >>> factorial(n)
70
+ factorial(n)
71
+
72
+ >>> factorial(2*n)
73
+ factorial(2*n)
74
+
75
+ >>> factorial(S(1)/2)
76
+ factorial(1/2)
77
+
78
+ See Also
79
+ ========
80
+
81
+ factorial2, RisingFactorial, FallingFactorial
82
+ """
83
+
84
+ def fdiff(self, argindex=1):
85
+ from sympy.functions.special.gamma_functions import (gamma, polygamma)
86
+ if argindex == 1:
87
+ return gamma(self.args[0] + 1)*polygamma(0, self.args[0] + 1)
88
+ else:
89
+ raise ArgumentIndexError(self, argindex)
90
+
91
+ _small_swing = [
92
+ 1, 1, 1, 3, 3, 15, 5, 35, 35, 315, 63, 693, 231, 3003, 429, 6435, 6435, 109395,
93
+ 12155, 230945, 46189, 969969, 88179, 2028117, 676039, 16900975, 1300075,
94
+ 35102025, 5014575, 145422675, 9694845, 300540195, 300540195
95
+ ]
96
+
97
+ _small_factorials: list[int] = []
98
+
99
+ @classmethod
100
+ def _swing(cls, n):
101
+ if n < 33:
102
+ return cls._small_swing[n]
103
+ else:
104
+ N, primes = int(_sqrt(n)), []
105
+
106
+ for prime in sieve.primerange(3, N + 1):
107
+ p, q = 1, n
108
+
109
+ while True:
110
+ q //= prime
111
+
112
+ if q > 0:
113
+ if q & 1 == 1:
114
+ p *= prime
115
+ else:
116
+ break
117
+
118
+ if p > 1:
119
+ primes.append(p)
120
+
121
+ for prime in sieve.primerange(N + 1, n//3 + 1):
122
+ if (n // prime) & 1 == 1:
123
+ primes.append(prime)
124
+
125
+ L_product = prod(sieve.primerange(n//2 + 1, n + 1))
126
+ R_product = prod(primes)
127
+
128
+ return L_product*R_product
129
+
130
+ @classmethod
131
+ def _recursive(cls, n):
132
+ if n < 2:
133
+ return 1
134
+ else:
135
+ return (cls._recursive(n//2)**2)*cls._swing(n)
136
+
137
+ @classmethod
138
+ def eval(cls, n):
139
+ n = sympify(n)
140
+
141
+ if n.is_Number:
142
+ if n.is_zero:
143
+ return S.One
144
+ elif n is S.Infinity:
145
+ return S.Infinity
146
+ elif n.is_Integer:
147
+ if n.is_negative:
148
+ return S.ComplexInfinity
149
+ else:
150
+ n = n.p
151
+
152
+ if n < 20:
153
+ if not cls._small_factorials:
154
+ result = 1
155
+ for i in range(1, 20):
156
+ result *= i
157
+ cls._small_factorials.append(result)
158
+ result = cls._small_factorials[n-1]
159
+
160
+ # GMPY factorial is faster, use it when available
161
+ elif HAS_GMPY:
162
+ result = gmpy.fac(n)
163
+
164
+ else:
165
+ bits = bin(n).count('1')
166
+ result = cls._recursive(n)*2**(n - bits)
167
+
168
+ return Integer(result)
169
+
170
+ def _facmod(self, n, q):
171
+ res, N = 1, int(_sqrt(n))
172
+
173
+ # Exponent of prime p in n! is e_p(n) = [n/p] + [n/p**2] + ...
174
+ # for p > sqrt(n), e_p(n) < sqrt(n), the primes with [n/p] = m,
175
+ # occur consecutively and are grouped together in pw[m] for
176
+ # simultaneous exponentiation at a later stage
177
+ pw = [1]*N
178
+
179
+ m = 2 # to initialize the if condition below
180
+ for prime in sieve.primerange(2, n + 1):
181
+ if m > 1:
182
+ m, y = 0, n // prime
183
+ while y:
184
+ m += y
185
+ y //= prime
186
+ if m < N:
187
+ pw[m] = pw[m]*prime % q
188
+ else:
189
+ res = res*pow(prime, m, q) % q
190
+
191
+ for ex, bs in enumerate(pw):
192
+ if ex == 0 or bs == 1:
193
+ continue
194
+ if bs == 0:
195
+ return 0
196
+ res = res*pow(bs, ex, q) % q
197
+
198
+ return res
199
+
200
+ def _eval_Mod(self, q):
201
+ n = self.args[0]
202
+ if n.is_integer and n.is_nonnegative and q.is_integer:
203
+ aq = abs(q)
204
+ d = aq - n
205
+ if d.is_nonpositive:
206
+ return S.Zero
207
+ else:
208
+ isprime = aq.is_prime
209
+ if d == 1:
210
+ # Apply Wilson's theorem (if a natural number n > 1
211
+ # is a prime number, then (n-1)! = -1 mod n) and
212
+ # its inverse (if n > 4 is a composite number, then
213
+ # (n-1)! = 0 mod n)
214
+ if isprime:
215
+ return -1 % q
216
+ elif isprime is False and (aq - 6).is_nonnegative:
217
+ return S.Zero
218
+ elif n.is_Integer and q.is_Integer:
219
+ n, d, aq = map(int, (n, d, aq))
220
+ if isprime and (d - 1 < n):
221
+ fc = self._facmod(d - 1, aq)
222
+ fc = pow(fc, aq - 2, aq)
223
+ if d%2:
224
+ fc = -fc
225
+ else:
226
+ fc = self._facmod(n, aq)
227
+
228
+ return fc % q
229
+
230
+ def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
231
+ from sympy.functions.special.gamma_functions import gamma
232
+ return gamma(n + 1)
233
+
234
+ def _eval_rewrite_as_Product(self, n, **kwargs):
235
+ from sympy.concrete.products import Product
236
+ if n.is_nonnegative and n.is_integer:
237
+ i = Dummy('i', integer=True)
238
+ return Product(i, (i, 1, n))
239
+
240
+ def _eval_is_integer(self):
241
+ if self.args[0].is_integer and self.args[0].is_nonnegative:
242
+ return True
243
+
244
+ def _eval_is_positive(self):
245
+ if self.args[0].is_integer and self.args[0].is_nonnegative:
246
+ return True
247
+
248
+ def _eval_is_even(self):
249
+ x = self.args[0]
250
+ if x.is_integer and x.is_nonnegative:
251
+ return (x - 2).is_nonnegative
252
+
253
+ def _eval_is_composite(self):
254
+ x = self.args[0]
255
+ if x.is_integer and x.is_nonnegative:
256
+ return (x - 3).is_nonnegative
257
+
258
+ def _eval_is_real(self):
259
+ x = self.args[0]
260
+ if x.is_nonnegative or x.is_noninteger:
261
+ return True
262
+
263
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
264
+ arg = self.args[0].as_leading_term(x)
265
+ arg0 = arg.subs(x, 0)
266
+ if arg0.is_zero:
267
+ return S.One
268
+ elif not arg0.is_infinite:
269
+ return self.func(arg)
270
+ raise PoleError("Cannot expand %s around 0" % (self))
271
+
272
+ class MultiFactorial(CombinatorialFunction):
273
+ pass
274
+
275
+
276
+ class subfactorial(CombinatorialFunction):
277
+ r"""The subfactorial counts the derangements of $n$ items and is
278
+ defined for non-negative integers as:
279
+
280
+ .. math:: !n = \begin{cases} 1 & n = 0 \\ 0 & n = 1 \\
281
+ (n-1)(!(n-1) + !(n-2)) & n > 1 \end{cases}
282
+
283
+ It can also be written as ``int(round(n!/exp(1)))`` but the
284
+ recursive definition with caching is implemented for this function.
285
+
286
+ An interesting analytic expression is the following [2]_
287
+
288
+ .. math:: !x = \Gamma(x + 1, -1)/e
289
+
290
+ which is valid for non-negative integers `x`. The above formula
291
+ is not very useful in case of non-integers. `\Gamma(x + 1, -1)` is
292
+ single-valued only for integral arguments `x`, elsewhere on the positive
293
+ real axis it has an infinite number of branches none of which are real.
294
+
295
+ References
296
+ ==========
297
+
298
+ .. [1] https://en.wikipedia.org/wiki/Subfactorial
299
+ .. [2] https://mathworld.wolfram.com/Subfactorial.html
300
+
301
+ Examples
302
+ ========
303
+
304
+ >>> from sympy import subfactorial
305
+ >>> from sympy.abc import n
306
+ >>> subfactorial(n + 1)
307
+ subfactorial(n + 1)
308
+ >>> subfactorial(5)
309
+ 44
310
+
311
+ See Also
312
+ ========
313
+
314
+ factorial, uppergamma,
315
+ sympy.utilities.iterables.generate_derangements
316
+ """
317
+
318
+ @classmethod
319
+ @cacheit
320
+ def _eval(self, n):
321
+ if not n:
322
+ return S.One
323
+ elif n == 1:
324
+ return S.Zero
325
+ else:
326
+ z1, z2 = 1, 0
327
+ for i in range(2, n + 1):
328
+ z1, z2 = z2, (i - 1)*(z2 + z1)
329
+ return z2
330
+
331
+ @classmethod
332
+ def eval(cls, arg):
333
+ if arg.is_Number:
334
+ if arg.is_Integer and arg.is_nonnegative:
335
+ return cls._eval(arg)
336
+ elif arg is S.NaN:
337
+ return S.NaN
338
+ elif arg is S.Infinity:
339
+ return S.Infinity
340
+
341
+ def _eval_is_even(self):
342
+ if self.args[0].is_odd and self.args[0].is_nonnegative:
343
+ return True
344
+
345
+ def _eval_is_integer(self):
346
+ if self.args[0].is_integer and self.args[0].is_nonnegative:
347
+ return True
348
+
349
+ def _eval_rewrite_as_factorial(self, arg, **kwargs):
350
+ from sympy.concrete.summations import summation
351
+ i = Dummy('i')
352
+ f = S.NegativeOne**i / factorial(i)
353
+ return factorial(arg) * summation(f, (i, 0, arg))
354
+
355
+ def _eval_rewrite_as_gamma(self, arg, piecewise=True, **kwargs):
356
+ from sympy.functions.elementary.exponential import exp
357
+ from sympy.functions.special.gamma_functions import (gamma, lowergamma)
358
+ return (S.NegativeOne**(arg + 1)*exp(-I*pi*arg)*lowergamma(arg + 1, -1)
359
+ + gamma(arg + 1))*exp(-1)
360
+
361
+ def _eval_rewrite_as_uppergamma(self, arg, **kwargs):
362
+ from sympy.functions.special.gamma_functions import uppergamma
363
+ return uppergamma(arg + 1, -1)/S.Exp1
364
+
365
+ def _eval_is_nonnegative(self):
366
+ if self.args[0].is_integer and self.args[0].is_nonnegative:
367
+ return True
368
+
369
+ def _eval_is_odd(self):
370
+ if self.args[0].is_even and self.args[0].is_nonnegative:
371
+ return True
372
+
373
+
374
+ class factorial2(CombinatorialFunction):
375
+ r"""The double factorial `n!!`, not to be confused with `(n!)!`
376
+
377
+ The double factorial is defined for nonnegative integers and for odd
378
+ negative integers as:
379
+
380
+ .. math:: n!! = \begin{cases} 1 & n = 0 \\
381
+ n(n-2)(n-4) \cdots 1 & n\ \text{positive odd} \\
382
+ n(n-2)(n-4) \cdots 2 & n\ \text{positive even} \\
383
+ (n+2)!!/(n+2) & n\ \text{negative odd} \end{cases}
384
+
385
+ References
386
+ ==========
387
+
388
+ .. [1] https://en.wikipedia.org/wiki/Double_factorial
389
+
390
+ Examples
391
+ ========
392
+
393
+ >>> from sympy import factorial2, var
394
+ >>> n = var('n')
395
+ >>> n
396
+ n
397
+ >>> factorial2(n + 1)
398
+ factorial2(n + 1)
399
+ >>> factorial2(5)
400
+ 15
401
+ >>> factorial2(-1)
402
+ 1
403
+ >>> factorial2(-5)
404
+ 1/3
405
+
406
+ See Also
407
+ ========
408
+
409
+ factorial, RisingFactorial, FallingFactorial
410
+ """
411
+
412
+ @classmethod
413
+ def eval(cls, arg):
414
+ # TODO: extend this to complex numbers?
415
+
416
+ if arg.is_Number:
417
+ if not arg.is_Integer:
418
+ raise ValueError("argument must be nonnegative integer "
419
+ "or negative odd integer")
420
+
421
+ # This implementation is faster than the recursive one
422
+ # It also avoids "maximum recursion depth exceeded" runtime error
423
+ if arg.is_nonnegative:
424
+ if arg.is_even:
425
+ k = arg / 2
426
+ return 2**k * factorial(k)
427
+ return factorial(arg) / factorial2(arg - 1)
428
+
429
+
430
+ if arg.is_odd:
431
+ return arg*(S.NegativeOne)**((1 - arg)/2) / factorial2(-arg)
432
+ raise ValueError("argument must be nonnegative integer "
433
+ "or negative odd integer")
434
+
435
+
436
+ def _eval_is_even(self):
437
+ # Double factorial is even for every positive even input
438
+ n = self.args[0]
439
+ if n.is_integer:
440
+ if n.is_odd:
441
+ return False
442
+ if n.is_even:
443
+ if n.is_positive:
444
+ return True
445
+ if n.is_zero:
446
+ return False
447
+
448
+ def _eval_is_integer(self):
449
+ # Double factorial is an integer for every nonnegative input, and for
450
+ # -1 and -3
451
+ n = self.args[0]
452
+ if n.is_integer:
453
+ if (n + 1).is_nonnegative:
454
+ return True
455
+ if n.is_odd:
456
+ return (n + 3).is_nonnegative
457
+
458
+ def _eval_is_odd(self):
459
+ # Double factorial is odd for every odd input not smaller than -3, and
460
+ # for 0
461
+ n = self.args[0]
462
+ if n.is_odd:
463
+ return (n + 3).is_nonnegative
464
+ if n.is_even:
465
+ if n.is_positive:
466
+ return False
467
+ if n.is_zero:
468
+ return True
469
+
470
+ def _eval_is_positive(self):
471
+ # Double factorial is positive for every nonnegative input, and for
472
+ # every odd negative input which is of the form -1-4k for an
473
+ # nonnegative integer k
474
+ n = self.args[0]
475
+ if n.is_integer:
476
+ if (n + 1).is_nonnegative:
477
+ return True
478
+ if n.is_odd:
479
+ return ((n + 1) / 2).is_even
480
+
481
+ def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
482
+ from sympy.functions.elementary.miscellaneous import sqrt
483
+ from sympy.functions.elementary.piecewise import Piecewise
484
+ from sympy.functions.special.gamma_functions import gamma
485
+ return 2**(n/2)*gamma(n/2 + 1) * Piecewise((1, Eq(Mod(n, 2), 0)),
486
+ (sqrt(2/pi), Eq(Mod(n, 2), 1)))
487
+
488
+
489
+ ###############################################################################
490
+ ######################## RISING and FALLING FACTORIALS ########################
491
+ ###############################################################################
492
+
493
+
494
+ class RisingFactorial(CombinatorialFunction):
495
+ r"""
496
+ Rising factorial (also called Pochhammer symbol [1]_) is a double valued
497
+ function arising in concrete mathematics, hypergeometric functions
498
+ and series expansions. It is defined by:
499
+
500
+ .. math:: \texttt{rf(y, k)} = (x)^k = x \cdot (x+1) \cdots (x+k-1)
501
+
502
+ where `x` can be arbitrary expression and `k` is an integer. For
503
+ more information check "Concrete mathematics" by Graham, pp. 66
504
+ or visit https://mathworld.wolfram.com/RisingFactorial.html page.
505
+
506
+ When `x` is a `~.Poly` instance of degree $\ge 1$ with a single variable,
507
+ `(x)^k = x(y) \cdot x(y+1) \cdots x(y+k-1)`, where `y` is the
508
+ variable of `x`. This is as described in [2]_.
509
+
510
+ Examples
511
+ ========
512
+
513
+ >>> from sympy import rf, Poly
514
+ >>> from sympy.abc import x
515
+ >>> rf(x, 0)
516
+ 1
517
+ >>> rf(1, 5)
518
+ 120
519
+ >>> rf(x, 5) == x*(1 + x)*(2 + x)*(3 + x)*(4 + x)
520
+ True
521
+ >>> rf(Poly(x**3, x), 2)
522
+ Poly(x**6 + 3*x**5 + 3*x**4 + x**3, x, domain='ZZ')
523
+
524
+ Rewriting is complicated unless the relationship between
525
+ the arguments is known, but rising factorial can
526
+ be rewritten in terms of gamma, factorial, binomial,
527
+ and falling factorial.
528
+
529
+ >>> from sympy import Symbol, factorial, ff, binomial, gamma
530
+ >>> n = Symbol('n', integer=True, positive=True)
531
+ >>> R = rf(n, n + 2)
532
+ >>> for i in (rf, ff, factorial, binomial, gamma):
533
+ ... R.rewrite(i)
534
+ ...
535
+ RisingFactorial(n, n + 2)
536
+ FallingFactorial(2*n + 1, n + 2)
537
+ factorial(2*n + 1)/factorial(n - 1)
538
+ binomial(2*n + 1, n + 2)*factorial(n + 2)
539
+ gamma(2*n + 2)/gamma(n)
540
+
541
+ See Also
542
+ ========
543
+
544
+ factorial, factorial2, FallingFactorial
545
+
546
+ References
547
+ ==========
548
+
549
+ .. [1] https://en.wikipedia.org/wiki/Pochhammer_symbol
550
+ .. [2] Peter Paule, "Greatest Factorial Factorization and Symbolic
551
+ Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268,
552
+ 1995.
553
+
554
+ """
555
+
556
+ @classmethod
557
+ def eval(cls, x, k):
558
+ x = sympify(x)
559
+ k = sympify(k)
560
+
561
+ if x is S.NaN or k is S.NaN:
562
+ return S.NaN
563
+ elif x is S.One:
564
+ return factorial(k)
565
+ elif k.is_Integer:
566
+ if k.is_zero:
567
+ return S.One
568
+ else:
569
+ if k.is_positive:
570
+ if x is S.Infinity:
571
+ return S.Infinity
572
+ elif x is S.NegativeInfinity:
573
+ if k.is_odd:
574
+ return S.NegativeInfinity
575
+ else:
576
+ return S.Infinity
577
+ else:
578
+ if isinstance(x, Poly):
579
+ gens = x.gens
580
+ if len(gens)!= 1:
581
+ raise ValueError("rf only defined for "
582
+ "polynomials on one generator")
583
+ else:
584
+ return reduce(lambda r, i:
585
+ r*(x.shift(i)),
586
+ range(int(k)), 1)
587
+ else:
588
+ return reduce(lambda r, i: r*(x + i),
589
+ range(int(k)), 1)
590
+
591
+ else:
592
+ if x is S.Infinity:
593
+ return S.Infinity
594
+ elif x is S.NegativeInfinity:
595
+ return S.Infinity
596
+ else:
597
+ if isinstance(x, Poly):
598
+ gens = x.gens
599
+ if len(gens)!= 1:
600
+ raise ValueError("rf only defined for "
601
+ "polynomials on one generator")
602
+ else:
603
+ return 1/reduce(lambda r, i:
604
+ r*(x.shift(-i)),
605
+ range(1, abs(int(k)) + 1), 1)
606
+ else:
607
+ return 1/reduce(lambda r, i:
608
+ r*(x - i),
609
+ range(1, abs(int(k)) + 1), 1)
610
+
611
+ if k.is_integer == False:
612
+ if x.is_integer and x.is_negative:
613
+ return S.Zero
614
+
615
+ def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs):
616
+ from sympy.functions.elementary.piecewise import Piecewise
617
+ from sympy.functions.special.gamma_functions import gamma
618
+ if not piecewise:
619
+ if (x <= 0) == True:
620
+ return S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1)
621
+ return gamma(x + k) / gamma(x)
622
+ return Piecewise(
623
+ (gamma(x + k) / gamma(x), x > 0),
624
+ (S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1), True))
625
+
626
+ def _eval_rewrite_as_FallingFactorial(self, x, k, **kwargs):
627
+ return FallingFactorial(x + k - 1, k)
628
+
629
+ def _eval_rewrite_as_factorial(self, x, k, **kwargs):
630
+ from sympy.functions.elementary.piecewise import Piecewise
631
+ if x.is_integer and k.is_integer:
632
+ return Piecewise(
633
+ (factorial(k + x - 1)/factorial(x - 1), x > 0),
634
+ (S.NegativeOne**k*factorial(-x)/factorial(-k - x), True))
635
+
636
+ def _eval_rewrite_as_binomial(self, x, k, **kwargs):
637
+ if k.is_integer:
638
+ return factorial(k) * binomial(x + k - 1, k)
639
+
640
+ def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs):
641
+ from sympy.functions.special.gamma_functions import gamma
642
+ if limitvar:
643
+ k_lim = k.subs(limitvar, S.Infinity)
644
+ if k_lim is S.Infinity:
645
+ return (gamma(x + k).rewrite('tractable', deep=True) / gamma(x))
646
+ elif k_lim is S.NegativeInfinity:
647
+ return (S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1).rewrite('tractable', deep=True))
648
+ return self.rewrite(gamma).rewrite('tractable', deep=True)
649
+
650
+ def _eval_is_integer(self):
651
+ return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer,
652
+ self.args[1].is_nonnegative))
653
+
654
+
655
+ class FallingFactorial(CombinatorialFunction):
656
+ r"""
657
+ Falling factorial (related to rising factorial) is a double valued
658
+ function arising in concrete mathematics, hypergeometric functions
659
+ and series expansions. It is defined by
660
+
661
+ .. math:: \texttt{ff(x, k)} = (x)_k = x \cdot (x-1) \cdots (x-k+1)
662
+
663
+ where `x` can be arbitrary expression and `k` is an integer. For
664
+ more information check "Concrete mathematics" by Graham, pp. 66
665
+ or [1]_.
666
+
667
+ When `x` is a `~.Poly` instance of degree $\ge 1$ with single variable,
668
+ `(x)_k = x(y) \cdot x(y-1) \cdots x(y-k+1)`, where `y` is the
669
+ variable of `x`. This is as described in
670
+
671
+ >>> from sympy import ff, Poly, Symbol
672
+ >>> from sympy.abc import x
673
+ >>> n = Symbol('n', integer=True)
674
+
675
+ >>> ff(x, 0)
676
+ 1
677
+ >>> ff(5, 5)
678
+ 120
679
+ >>> ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4)
680
+ True
681
+ >>> ff(Poly(x**2, x), 2)
682
+ Poly(x**4 - 2*x**3 + x**2, x, domain='ZZ')
683
+ >>> ff(n, n)
684
+ factorial(n)
685
+
686
+ Rewriting is complicated unless the relationship between
687
+ the arguments is known, but falling factorial can
688
+ be rewritten in terms of gamma, factorial and binomial
689
+ and rising factorial.
690
+
691
+ >>> from sympy import factorial, rf, gamma, binomial, Symbol
692
+ >>> n = Symbol('n', integer=True, positive=True)
693
+ >>> F = ff(n, n - 2)
694
+ >>> for i in (rf, ff, factorial, binomial, gamma):
695
+ ... F.rewrite(i)
696
+ ...
697
+ RisingFactorial(3, n - 2)
698
+ FallingFactorial(n, n - 2)
699
+ factorial(n)/2
700
+ binomial(n, n - 2)*factorial(n - 2)
701
+ gamma(n + 1)/2
702
+
703
+ See Also
704
+ ========
705
+
706
+ factorial, factorial2, RisingFactorial
707
+
708
+ References
709
+ ==========
710
+
711
+ .. [1] https://mathworld.wolfram.com/FallingFactorial.html
712
+ .. [2] Peter Paule, "Greatest Factorial Factorization and Symbolic
713
+ Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268,
714
+ 1995.
715
+
716
+ """
717
+
718
+ @classmethod
719
+ def eval(cls, x, k):
720
+ x = sympify(x)
721
+ k = sympify(k)
722
+
723
+ if x is S.NaN or k is S.NaN:
724
+ return S.NaN
725
+ elif k.is_integer and x == k:
726
+ return factorial(x)
727
+ elif k.is_Integer:
728
+ if k.is_zero:
729
+ return S.One
730
+ else:
731
+ if k.is_positive:
732
+ if x is S.Infinity:
733
+ return S.Infinity
734
+ elif x is S.NegativeInfinity:
735
+ if k.is_odd:
736
+ return S.NegativeInfinity
737
+ else:
738
+ return S.Infinity
739
+ else:
740
+ if isinstance(x, Poly):
741
+ gens = x.gens
742
+ if len(gens)!= 1:
743
+ raise ValueError("ff only defined for "
744
+ "polynomials on one generator")
745
+ else:
746
+ return reduce(lambda r, i:
747
+ r*(x.shift(-i)),
748
+ range(int(k)), 1)
749
+ else:
750
+ return reduce(lambda r, i: r*(x - i),
751
+ range(int(k)), 1)
752
+ else:
753
+ if x is S.Infinity:
754
+ return S.Infinity
755
+ elif x is S.NegativeInfinity:
756
+ return S.Infinity
757
+ else:
758
+ if isinstance(x, Poly):
759
+ gens = x.gens
760
+ if len(gens)!= 1:
761
+ raise ValueError("rf only defined for "
762
+ "polynomials on one generator")
763
+ else:
764
+ return 1/reduce(lambda r, i:
765
+ r*(x.shift(i)),
766
+ range(1, abs(int(k)) + 1), 1)
767
+ else:
768
+ return 1/reduce(lambda r, i: r*(x + i),
769
+ range(1, abs(int(k)) + 1), 1)
770
+
771
+ def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs):
772
+ from sympy.functions.elementary.piecewise import Piecewise
773
+ from sympy.functions.special.gamma_functions import gamma
774
+ if not piecewise:
775
+ if (x < 0) == True:
776
+ return S.NegativeOne**k*gamma(k - x) / gamma(-x)
777
+ return gamma(x + 1) / gamma(x - k + 1)
778
+ return Piecewise(
779
+ (gamma(x + 1) / gamma(x - k + 1), x >= 0),
780
+ (S.NegativeOne**k*gamma(k - x) / gamma(-x), True))
781
+
782
+ def _eval_rewrite_as_RisingFactorial(self, x, k, **kwargs):
783
+ return rf(x - k + 1, k)
784
+
785
+ def _eval_rewrite_as_binomial(self, x, k, **kwargs):
786
+ if k.is_integer:
787
+ return factorial(k) * binomial(x, k)
788
+
789
+ def _eval_rewrite_as_factorial(self, x, k, **kwargs):
790
+ from sympy.functions.elementary.piecewise import Piecewise
791
+ if x.is_integer and k.is_integer:
792
+ return Piecewise(
793
+ (factorial(x)/factorial(-k + x), x >= 0),
794
+ (S.NegativeOne**k*factorial(k - x - 1)/factorial(-x - 1), True))
795
+
796
+ def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs):
797
+ from sympy.functions.special.gamma_functions import gamma
798
+ if limitvar:
799
+ k_lim = k.subs(limitvar, S.Infinity)
800
+ if k_lim is S.Infinity:
801
+ return (S.NegativeOne**k*gamma(k - x).rewrite('tractable', deep=True) / gamma(-x))
802
+ elif k_lim is S.NegativeInfinity:
803
+ return (gamma(x + 1) / gamma(x - k + 1).rewrite('tractable', deep=True))
804
+ return self.rewrite(gamma).rewrite('tractable', deep=True)
805
+
806
+ def _eval_is_integer(self):
807
+ return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer,
808
+ self.args[1].is_nonnegative))
809
+
810
+
811
+ rf = RisingFactorial
812
+ ff = FallingFactorial
813
+
814
+ ###############################################################################
815
+ ########################### BINOMIAL COEFFICIENTS #############################
816
+ ###############################################################################
817
+
818
+
819
+ class binomial(CombinatorialFunction):
820
+ r"""Implementation of the binomial coefficient. It can be defined
821
+ in two ways depending on its desired interpretation:
822
+
823
+ .. math:: \binom{n}{k} = \frac{n!}{k!(n-k)!}\ \text{or}\
824
+ \binom{n}{k} = \frac{(n)_k}{k!}
825
+
826
+ First, in a strict combinatorial sense it defines the
827
+ number of ways we can choose `k` elements from a set of
828
+ `n` elements. In this case both arguments are nonnegative
829
+ integers and binomial is computed using an efficient
830
+ algorithm based on prime factorization.
831
+
832
+ The other definition is generalization for arbitrary `n`,
833
+ however `k` must also be nonnegative. This case is very
834
+ useful when evaluating summations.
835
+
836
+ For the sake of convenience, for negative integer `k` this function
837
+ will return zero no matter the other argument.
838
+
839
+ To expand the binomial when `n` is a symbol, use either
840
+ ``expand_func()`` or ``expand(func=True)``. The former will keep
841
+ the polynomial in factored form while the latter will expand the
842
+ polynomial itself. See examples for details.
843
+
844
+ Examples
845
+ ========
846
+
847
+ >>> from sympy import Symbol, Rational, binomial, expand_func
848
+ >>> n = Symbol('n', integer=True, positive=True)
849
+
850
+ >>> binomial(15, 8)
851
+ 6435
852
+
853
+ >>> binomial(n, -1)
854
+ 0
855
+
856
+ Rows of Pascal's triangle can be generated with the binomial function:
857
+
858
+ >>> for N in range(8):
859
+ ... print([binomial(N, i) for i in range(N + 1)])
860
+ ...
861
+ [1]
862
+ [1, 1]
863
+ [1, 2, 1]
864
+ [1, 3, 3, 1]
865
+ [1, 4, 6, 4, 1]
866
+ [1, 5, 10, 10, 5, 1]
867
+ [1, 6, 15, 20, 15, 6, 1]
868
+ [1, 7, 21, 35, 35, 21, 7, 1]
869
+
870
+ As can a given diagonal, e.g. the 4th diagonal:
871
+
872
+ >>> N = -4
873
+ >>> [binomial(N, i) for i in range(1 - N)]
874
+ [1, -4, 10, -20, 35]
875
+
876
+ >>> binomial(Rational(5, 4), 3)
877
+ -5/128
878
+ >>> binomial(Rational(-5, 4), 3)
879
+ -195/128
880
+
881
+ >>> binomial(n, 3)
882
+ binomial(n, 3)
883
+
884
+ >>> binomial(n, 3).expand(func=True)
885
+ n**3/6 - n**2/2 + n/3
886
+
887
+ >>> expand_func(binomial(n, 3))
888
+ n*(n - 2)*(n - 1)/6
889
+
890
+ References
891
+ ==========
892
+
893
+ .. [1] https://www.johndcook.com/blog/binomial_coefficients/
894
+
895
+ """
896
+
897
+ def fdiff(self, argindex=1):
898
+ from sympy.functions.special.gamma_functions import polygamma
899
+ if argindex == 1:
900
+ # https://functions.wolfram.com/GammaBetaErf/Binomial/20/01/01/
901
+ n, k = self.args
902
+ return binomial(n, k)*(polygamma(0, n + 1) - \
903
+ polygamma(0, n - k + 1))
904
+ elif argindex == 2:
905
+ # https://functions.wolfram.com/GammaBetaErf/Binomial/20/01/02/
906
+ n, k = self.args
907
+ return binomial(n, k)*(polygamma(0, n - k + 1) - \
908
+ polygamma(0, k + 1))
909
+ else:
910
+ raise ArgumentIndexError(self, argindex)
911
+
912
+ @classmethod
913
+ def _eval(self, n, k):
914
+ # n.is_Number and k.is_Integer and k != 1 and n != k
915
+
916
+ if k.is_Integer:
917
+ if n.is_Integer and n >= 0:
918
+ n, k = int(n), int(k)
919
+
920
+ if k > n:
921
+ return S.Zero
922
+ elif k > n // 2:
923
+ k = n - k
924
+
925
+ if HAS_GMPY:
926
+ return Integer(gmpy.bincoef(n, k))
927
+
928
+ d, result = n - k, 1
929
+ for i in range(1, k + 1):
930
+ d += 1
931
+ result = result * d // i
932
+ return Integer(result)
933
+ else:
934
+ d, result = n - k, 1
935
+ for i in range(1, k + 1):
936
+ d += 1
937
+ result *= d
938
+ return result / _factorial(k)
939
+
940
+ @classmethod
941
+ def eval(cls, n, k):
942
+ n, k = map(sympify, (n, k))
943
+ d = n - k
944
+ n_nonneg, n_isint = n.is_nonnegative, n.is_integer
945
+ if k.is_zero or ((n_nonneg or n_isint is False)
946
+ and d.is_zero):
947
+ return S.One
948
+ if (k - 1).is_zero or ((n_nonneg or n_isint is False)
949
+ and (d - 1).is_zero):
950
+ return n
951
+ if k.is_integer:
952
+ if k.is_negative or (n_nonneg and n_isint and d.is_negative):
953
+ return S.Zero
954
+ elif n.is_number:
955
+ res = cls._eval(n, k)
956
+ return res.expand(basic=True) if res else res
957
+ elif n_nonneg is False and n_isint:
958
+ # a special case when binomial evaluates to complex infinity
959
+ return S.ComplexInfinity
960
+ elif k.is_number:
961
+ from sympy.functions.special.gamma_functions import gamma
962
+ return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
963
+
964
+ def _eval_Mod(self, q):
965
+ n, k = self.args
966
+
967
+ if any(x.is_integer is False for x in (n, k, q)):
968
+ raise ValueError("Integers expected for binomial Mod")
969
+
970
+ if all(x.is_Integer for x in (n, k, q)):
971
+ n, k = map(int, (n, k))
972
+ aq, res = abs(q), 1
973
+
974
+ # handle negative integers k or n
975
+ if k < 0:
976
+ return S.Zero
977
+ if n < 0:
978
+ n = -n + k - 1
979
+ res = -1 if k%2 else 1
980
+
981
+ # non negative integers k and n
982
+ if k > n:
983
+ return S.Zero
984
+
985
+ isprime = aq.is_prime
986
+ aq = int(aq)
987
+ if isprime:
988
+ if aq < n:
989
+ # use Lucas Theorem
990
+ N, K = n, k
991
+ while N or K:
992
+ res = res*binomial(N % aq, K % aq) % aq
993
+ N, K = N // aq, K // aq
994
+
995
+ else:
996
+ # use Factorial Modulo
997
+ d = n - k
998
+ if k > d:
999
+ k, d = d, k
1000
+ kf = 1
1001
+ for i in range(2, k + 1):
1002
+ kf = kf*i % aq
1003
+ df = kf
1004
+ for i in range(k + 1, d + 1):
1005
+ df = df*i % aq
1006
+ res *= df
1007
+ for i in range(d + 1, n + 1):
1008
+ res = res*i % aq
1009
+
1010
+ res *= pow(kf*df % aq, aq - 2, aq)
1011
+ res %= aq
1012
+
1013
+ else:
1014
+ # Binomial Factorization is performed by calculating the
1015
+ # exponents of primes <= n in `n! /(k! (n - k)!)`,
1016
+ # for non-negative integers n and k. As the exponent of
1017
+ # prime in n! is e_p(n) = [n/p] + [n/p**2] + ...
1018
+ # the exponent of prime in binomial(n, k) would be
1019
+ # e_p(n) - e_p(k) - e_p(n - k)
1020
+ M = int(_sqrt(n))
1021
+ for prime in sieve.primerange(2, n + 1):
1022
+ if prime > n - k:
1023
+ res = res*prime % aq
1024
+ elif prime > n // 2:
1025
+ continue
1026
+ elif prime > M:
1027
+ if n % prime < k % prime:
1028
+ res = res*prime % aq
1029
+ else:
1030
+ N, K = n, k
1031
+ exp = a = 0
1032
+
1033
+ while N > 0:
1034
+ a = int((N % prime) < (K % prime + a))
1035
+ N, K = N // prime, K // prime
1036
+ exp += a
1037
+
1038
+ if exp > 0:
1039
+ res *= pow(prime, exp, aq)
1040
+ res %= aq
1041
+
1042
+ return S(res % q)
1043
+
1044
+ def _eval_expand_func(self, **hints):
1045
+ """
1046
+ Function to expand binomial(n, k) when m is positive integer
1047
+ Also,
1048
+ n is self.args[0] and k is self.args[1] while using binomial(n, k)
1049
+ """
1050
+ n = self.args[0]
1051
+ if n.is_Number:
1052
+ return binomial(*self.args)
1053
+
1054
+ k = self.args[1]
1055
+ if (n-k).is_Integer:
1056
+ k = n - k
1057
+
1058
+ if k.is_Integer:
1059
+ if k.is_zero:
1060
+ return S.One
1061
+ elif k.is_negative:
1062
+ return S.Zero
1063
+ else:
1064
+ n, result = self.args[0], 1
1065
+ for i in range(1, k + 1):
1066
+ result *= n - k + i
1067
+ return result / _factorial(k)
1068
+ else:
1069
+ return binomial(*self.args)
1070
+
1071
+ def _eval_rewrite_as_factorial(self, n, k, **kwargs):
1072
+ return factorial(n)/(factorial(k)*factorial(n - k))
1073
+
1074
+ def _eval_rewrite_as_gamma(self, n, k, piecewise=True, **kwargs):
1075
+ from sympy.functions.special.gamma_functions import gamma
1076
+ return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
1077
+
1078
+ def _eval_rewrite_as_tractable(self, n, k, limitvar=None, **kwargs):
1079
+ return self._eval_rewrite_as_gamma(n, k).rewrite('tractable')
1080
+
1081
+ def _eval_rewrite_as_FallingFactorial(self, n, k, **kwargs):
1082
+ if k.is_integer:
1083
+ return ff(n, k) / factorial(k)
1084
+
1085
+ def _eval_is_integer(self):
1086
+ n, k = self.args
1087
+ if n.is_integer and k.is_integer:
1088
+ return True
1089
+ elif k.is_integer is False:
1090
+ return False
1091
+
1092
+ def _eval_is_nonnegative(self):
1093
+ n, k = self.args
1094
+ if n.is_integer and k.is_integer:
1095
+ if n.is_nonnegative or k.is_negative or k.is_even:
1096
+ return True
1097
+ elif k.is_even is False:
1098
+ return False
1099
+
1100
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
1101
+ from sympy.functions.special.gamma_functions import gamma
1102
+ return self.rewrite(gamma)._eval_as_leading_term(x, logx=logx, cdir=cdir)
llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/numbers.py ADDED
@@ -0,0 +1,2563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module implements some special functions that commonly appear in
3
+ combinatorial contexts (e.g. in power series); in particular,
4
+ sequences of rational numbers such as Bernoulli and Fibonacci numbers.
5
+
6
+ Factorials, binomial coefficients and related functions are located in
7
+ the separate 'factorials' module.
8
+ """
9
+ from math import prod
10
+ from collections import defaultdict
11
+ from typing import Tuple as tTuple
12
+
13
+ from sympy.core import S, Symbol, Add, Dummy
14
+ from sympy.core.cache import cacheit
15
+ from sympy.core.expr import Expr
16
+ from sympy.core.function import ArgumentIndexError, Function, expand_mul
17
+ from sympy.core.logic import fuzzy_not
18
+ from sympy.core.mul import Mul
19
+ from sympy.core.numbers import E, I, pi, oo, Rational, Integer
20
+ from sympy.core.relational import Eq, is_le, is_gt
21
+ from sympy.external.gmpy import SYMPY_INTS
22
+ from sympy.functions.combinatorial.factorials import (binomial,
23
+ factorial, subfactorial)
24
+ from sympy.functions.elementary.exponential import log
25
+ from sympy.functions.elementary.piecewise import Piecewise
26
+ from sympy.ntheory.primetest import isprime, is_square
27
+ from sympy.polys.appellseqs import bernoulli_poly, euler_poly, genocchi_poly
28
+ from sympy.utilities.enumerative import MultisetPartitionTraverser
29
+ from sympy.utilities.exceptions import sympy_deprecation_warning
30
+ from sympy.utilities.iterables import multiset, multiset_derangements, iterable
31
+ from sympy.utilities.memoization import recurrence_memo
32
+ from sympy.utilities.misc import as_int
33
+
34
+ from mpmath import mp, workprec
35
+ from mpmath.libmp import ifib as _ifib
36
+
37
+
38
+ def _product(a, b):
39
+ return prod(range(a, b + 1))
40
+
41
+
42
+ # Dummy symbol used for computing polynomial sequences
43
+ _sym = Symbol('x')
44
+
45
+
46
+ #----------------------------------------------------------------------------#
47
+ # #
48
+ # Carmichael numbers #
49
+ # #
50
+ #----------------------------------------------------------------------------#
51
+
52
+ def _divides(p, n):
53
+ return n % p == 0
54
+
55
+ class carmichael(Function):
56
+ r"""
57
+ Carmichael Numbers:
58
+
59
+ Certain cryptographic algorithms make use of big prime numbers.
60
+ However, checking whether a big number is prime is not so easy.
61
+ Randomized prime number checking tests exist that offer a high degree of
62
+ confidence of accurate determination at low cost, such as the Fermat test.
63
+
64
+ Let 'a' be a random number between $2$ and $n - 1$, where $n$ is the
65
+ number whose primality we are testing. Then, $n$ is probably prime if it
66
+ satisfies the modular arithmetic congruence relation:
67
+
68
+ .. math :: a^{n-1} = 1 \pmod{n}
69
+
70
+ (where mod refers to the modulo operation)
71
+
72
+ If a number passes the Fermat test several times, then it is prime with a
73
+ high probability.
74
+
75
+ Unfortunately, certain composite numbers (non-primes) still pass the Fermat
76
+ test with every number smaller than themselves.
77
+ These numbers are called Carmichael numbers.
78
+
79
+ A Carmichael number will pass a Fermat primality test to every base $b$
80
+ relatively prime to the number, even though it is not actually prime.
81
+ This makes tests based on Fermat's Little Theorem less effective than
82
+ strong probable prime tests such as the Baillie-PSW primality test and
83
+ the Miller-Rabin primality test.
84
+
85
+ Examples
86
+ ========
87
+
88
+ >>> from sympy import carmichael
89
+ >>> carmichael.find_first_n_carmichaels(5)
90
+ [561, 1105, 1729, 2465, 2821]
91
+ >>> carmichael.find_carmichael_numbers_in_range(0, 562)
92
+ [561]
93
+ >>> carmichael.find_carmichael_numbers_in_range(0,1000)
94
+ [561]
95
+ >>> carmichael.find_carmichael_numbers_in_range(0,2000)
96
+ [561, 1105, 1729]
97
+
98
+ References
99
+ ==========
100
+
101
+ .. [1] https://en.wikipedia.org/wiki/Carmichael_number
102
+ .. [2] https://en.wikipedia.org/wiki/Fermat_primality_test
103
+ .. [3] https://www.jstor.org/stable/23248683?seq=1#metadata_info_tab_contents
104
+ """
105
+
106
+ @staticmethod
107
+ def is_perfect_square(n):
108
+ sympy_deprecation_warning(
109
+ """
110
+ is_perfect_square is just a wrapper around sympy.ntheory.primetest.is_square
111
+ so use that directly instead.
112
+ """,
113
+ deprecated_since_version="1.11",
114
+ active_deprecations_target='deprecated-carmichael-static-methods',
115
+ )
116
+ return is_square(n)
117
+
118
+ @staticmethod
119
+ def divides(p, n):
120
+ sympy_deprecation_warning(
121
+ """
122
+ divides can be replaced by directly testing n % p == 0.
123
+ """,
124
+ deprecated_since_version="1.11",
125
+ active_deprecations_target='deprecated-carmichael-static-methods',
126
+ )
127
+ return n % p == 0
128
+
129
+ @staticmethod
130
+ def is_prime(n):
131
+ sympy_deprecation_warning(
132
+ """
133
+ is_prime is just a wrapper around sympy.ntheory.primetest.isprime so use that
134
+ directly instead.
135
+ """,
136
+ deprecated_since_version="1.11",
137
+ active_deprecations_target='deprecated-carmichael-static-methods',
138
+ )
139
+ return isprime(n)
140
+
141
+ @staticmethod
142
+ def is_carmichael(n):
143
+ if n >= 0:
144
+ if (n == 1) or isprime(n) or (n % 2 == 0):
145
+ return False
146
+
147
+ divisors = [1, n]
148
+
149
+ # get divisors
150
+ divisors.extend([i for i in range(3, n // 2 + 1, 2) if n % i == 0])
151
+
152
+ for i in divisors:
153
+ if is_square(i) and i != 1:
154
+ return False
155
+ if isprime(i):
156
+ if not _divides(i - 1, n - 1):
157
+ return False
158
+
159
+ return True
160
+
161
+ else:
162
+ raise ValueError('The provided number must be greater than or equal to 0')
163
+
164
+ @staticmethod
165
+ def find_carmichael_numbers_in_range(x, y):
166
+ if 0 <= x <= y:
167
+ if x % 2 == 0:
168
+ return [i for i in range(x + 1, y, 2) if carmichael.is_carmichael(i)]
169
+ else:
170
+ return [i for i in range(x, y, 2) if carmichael.is_carmichael(i)]
171
+
172
+ else:
173
+ raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y')
174
+
175
+ @staticmethod
176
+ def find_first_n_carmichaels(n):
177
+ i = 1
178
+ carmichaels = []
179
+
180
+ while len(carmichaels) < n:
181
+ if carmichael.is_carmichael(i):
182
+ carmichaels.append(i)
183
+ i += 2
184
+
185
+ return carmichaels
186
+
187
+
188
+ #----------------------------------------------------------------------------#
189
+ # #
190
+ # Fibonacci numbers #
191
+ # #
192
+ #----------------------------------------------------------------------------#
193
+
194
+
195
+ class fibonacci(Function):
196
+ r"""
197
+ Fibonacci numbers / Fibonacci polynomials
198
+
199
+ The Fibonacci numbers are the integer sequence defined by the
200
+ initial terms `F_0 = 0`, `F_1 = 1` and the two-term recurrence
201
+ relation `F_n = F_{n-1} + F_{n-2}`. This definition
202
+ extended to arbitrary real and complex arguments using
203
+ the formula
204
+
205
+ .. math :: F_z = \frac{\phi^z - \cos(\pi z) \phi^{-z}}{\sqrt 5}
206
+
207
+ The Fibonacci polynomials are defined by `F_1(x) = 1`,
208
+ `F_2(x) = x`, and `F_n(x) = x*F_{n-1}(x) + F_{n-2}(x)` for `n > 2`.
209
+ For all positive integers `n`, `F_n(1) = F_n`.
210
+
211
+ * ``fibonacci(n)`` gives the `n^{th}` Fibonacci number, `F_n`
212
+ * ``fibonacci(n, x)`` gives the `n^{th}` Fibonacci polynomial in `x`, `F_n(x)`
213
+
214
+ Examples
215
+ ========
216
+
217
+ >>> from sympy import fibonacci, Symbol
218
+
219
+ >>> [fibonacci(x) for x in range(11)]
220
+ [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
221
+ >>> fibonacci(5, Symbol('t'))
222
+ t**4 + 3*t**2 + 1
223
+
224
+ See Also
225
+ ========
226
+
227
+ bell, bernoulli, catalan, euler, harmonic, lucas, genocchi, partition, tribonacci
228
+
229
+ References
230
+ ==========
231
+
232
+ .. [1] https://en.wikipedia.org/wiki/Fibonacci_number
233
+ .. [2] https://mathworld.wolfram.com/FibonacciNumber.html
234
+
235
+ """
236
+
237
+ @staticmethod
238
+ def _fib(n):
239
+ return _ifib(n)
240
+
241
+ @staticmethod
242
+ @recurrence_memo([None, S.One, _sym])
243
+ def _fibpoly(n, prev):
244
+ return (prev[-2] + _sym*prev[-1]).expand()
245
+
246
+ @classmethod
247
+ def eval(cls, n, sym=None):
248
+ if n is S.Infinity:
249
+ return S.Infinity
250
+
251
+ if n.is_Integer:
252
+ if sym is None:
253
+ n = int(n)
254
+ if n < 0:
255
+ return S.NegativeOne**(n + 1) * fibonacci(-n)
256
+ else:
257
+ return Integer(cls._fib(n))
258
+ else:
259
+ if n < 1:
260
+ raise ValueError("Fibonacci polynomials are defined "
261
+ "only for positive integer indices.")
262
+ return cls._fibpoly(n).subs(_sym, sym)
263
+
264
+ def _eval_rewrite_as_sqrt(self, n, **kwargs):
265
+ from sympy.functions.elementary.miscellaneous import sqrt
266
+ return 2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5
267
+
268
+ def _eval_rewrite_as_GoldenRatio(self,n, **kwargs):
269
+ return (S.GoldenRatio**n - 1/(-S.GoldenRatio)**n)/(2*S.GoldenRatio-1)
270
+
271
+
272
+ #----------------------------------------------------------------------------#
273
+ # #
274
+ # Lucas numbers #
275
+ # #
276
+ #----------------------------------------------------------------------------#
277
+
278
+
279
+ class lucas(Function):
280
+ """
281
+ Lucas numbers
282
+
283
+ Lucas numbers satisfy a recurrence relation similar to that of
284
+ the Fibonacci sequence, in which each term is the sum of the
285
+ preceding two. They are generated by choosing the initial
286
+ values `L_0 = 2` and `L_1 = 1`.
287
+
288
+ * ``lucas(n)`` gives the `n^{th}` Lucas number
289
+
290
+ Examples
291
+ ========
292
+
293
+ >>> from sympy import lucas
294
+
295
+ >>> [lucas(x) for x in range(11)]
296
+ [2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123]
297
+
298
+ See Also
299
+ ========
300
+
301
+ bell, bernoulli, catalan, euler, fibonacci, harmonic, genocchi, partition, tribonacci
302
+
303
+ References
304
+ ==========
305
+
306
+ .. [1] https://en.wikipedia.org/wiki/Lucas_number
307
+ .. [2] https://mathworld.wolfram.com/LucasNumber.html
308
+
309
+ """
310
+
311
+ @classmethod
312
+ def eval(cls, n):
313
+ if n is S.Infinity:
314
+ return S.Infinity
315
+
316
+ if n.is_Integer:
317
+ return fibonacci(n + 1) + fibonacci(n - 1)
318
+
319
+ def _eval_rewrite_as_sqrt(self, n, **kwargs):
320
+ from sympy.functions.elementary.miscellaneous import sqrt
321
+ return 2**(-n)*((1 + sqrt(5))**n + (-sqrt(5) + 1)**n)
322
+
323
+
324
+ #----------------------------------------------------------------------------#
325
+ # #
326
+ # Tribonacci numbers #
327
+ # #
328
+ #----------------------------------------------------------------------------#
329
+
330
+
331
+ class tribonacci(Function):
332
+ r"""
333
+ Tribonacci numbers / Tribonacci polynomials
334
+
335
+ The Tribonacci numbers are the integer sequence defined by the
336
+ initial terms `T_0 = 0`, `T_1 = 1`, `T_2 = 1` and the three-term
337
+ recurrence relation `T_n = T_{n-1} + T_{n-2} + T_{n-3}`.
338
+
339
+ The Tribonacci polynomials are defined by `T_0(x) = 0`, `T_1(x) = 1`,
340
+ `T_2(x) = x^2`, and `T_n(x) = x^2 T_{n-1}(x) + x T_{n-2}(x) + T_{n-3}(x)`
341
+ for `n > 2`. For all positive integers `n`, `T_n(1) = T_n`.
342
+
343
+ * ``tribonacci(n)`` gives the `n^{th}` Tribonacci number, `T_n`
344
+ * ``tribonacci(n, x)`` gives the `n^{th}` Tribonacci polynomial in `x`, `T_n(x)`
345
+
346
+ Examples
347
+ ========
348
+
349
+ >>> from sympy import tribonacci, Symbol
350
+
351
+ >>> [tribonacci(x) for x in range(11)]
352
+ [0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149]
353
+ >>> tribonacci(5, Symbol('t'))
354
+ t**8 + 3*t**5 + 3*t**2
355
+
356
+ See Also
357
+ ========
358
+
359
+ bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition
360
+
361
+ References
362
+ ==========
363
+
364
+ .. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers
365
+ .. [2] https://mathworld.wolfram.com/TribonacciNumber.html
366
+ .. [3] https://oeis.org/A000073
367
+
368
+ """
369
+
370
+ @staticmethod
371
+ @recurrence_memo([S.Zero, S.One, S.One])
372
+ def _trib(n, prev):
373
+ return (prev[-3] + prev[-2] + prev[-1])
374
+
375
+ @staticmethod
376
+ @recurrence_memo([S.Zero, S.One, _sym**2])
377
+ def _tribpoly(n, prev):
378
+ return (prev[-3] + _sym*prev[-2] + _sym**2*prev[-1]).expand()
379
+
380
+ @classmethod
381
+ def eval(cls, n, sym=None):
382
+ if n is S.Infinity:
383
+ return S.Infinity
384
+
385
+ if n.is_Integer:
386
+ n = int(n)
387
+ if n < 0:
388
+ raise ValueError("Tribonacci polynomials are defined "
389
+ "only for non-negative integer indices.")
390
+ if sym is None:
391
+ return Integer(cls._trib(n))
392
+ else:
393
+ return cls._tribpoly(n).subs(_sym, sym)
394
+
395
+ def _eval_rewrite_as_sqrt(self, n, **kwargs):
396
+ from sympy.functions.elementary.miscellaneous import cbrt, sqrt
397
+ w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2
398
+ a = (1 + cbrt(19 + 3*sqrt(33)) + cbrt(19 - 3*sqrt(33))) / 3
399
+ b = (1 + w*cbrt(19 + 3*sqrt(33)) + w**2*cbrt(19 - 3*sqrt(33))) / 3
400
+ c = (1 + w**2*cbrt(19 + 3*sqrt(33)) + w*cbrt(19 - 3*sqrt(33))) / 3
401
+ Tn = (a**(n + 1)/((a - b)*(a - c))
402
+ + b**(n + 1)/((b - a)*(b - c))
403
+ + c**(n + 1)/((c - a)*(c - b)))
404
+ return Tn
405
+
406
+ def _eval_rewrite_as_TribonacciConstant(self, n, **kwargs):
407
+ from sympy.functions.elementary.integers import floor
408
+ from sympy.functions.elementary.miscellaneous import cbrt, sqrt
409
+ b = cbrt(586 + 102*sqrt(33))
410
+ Tn = 3 * b * S.TribonacciConstant**n / (b**2 - 2*b + 4)
411
+ return floor(Tn + S.Half)
412
+
413
+
414
+ #----------------------------------------------------------------------------#
415
+ # #
416
+ # Bernoulli numbers #
417
+ # #
418
+ #----------------------------------------------------------------------------#
419
+
420
+
421
+ class bernoulli(Function):
422
+ r"""
423
+ Bernoulli numbers / Bernoulli polynomials / Bernoulli function
424
+
425
+ The Bernoulli numbers are a sequence of rational numbers
426
+ defined by `B_0 = 1` and the recursive relation (`n > 0`):
427
+
428
+ .. math :: n+1 = \sum_{k=0}^n \binom{n+1}{k} B_k
429
+
430
+ They are also commonly defined by their exponential generating
431
+ function, which is `\frac{x}{1 - e^{-x}}`. For odd indices > 1,
432
+ the Bernoulli numbers are zero.
433
+
434
+ The Bernoulli polynomials satisfy the analogous formula:
435
+
436
+ .. math :: B_n(x) = \sum_{k=0}^n (-1)^k \binom{n}{k} B_k x^{n-k}
437
+
438
+ Bernoulli numbers and Bernoulli polynomials are related as
439
+ `B_n(1) = B_n`.
440
+
441
+ The generalized Bernoulli function `\operatorname{B}(s, a)`
442
+ is defined for any complex `s` and `a`, except where `a` is a
443
+ nonpositive integer and `s` is not a nonnegative integer. It is
444
+ an entire function of `s` for fixed `a`, related to the Hurwitz
445
+ zeta function by
446
+
447
+ .. math:: \operatorname{B}(s, a) = \begin{cases}
448
+ -s \zeta(1-s, a) & s \ne 0 \\ 1 & s = 0 \end{cases}
449
+
450
+ When `s` is a nonnegative integer this function reduces to the
451
+ Bernoulli polynomials: `\operatorname{B}(n, x) = B_n(x)`. When
452
+ `a` is omitted it is assumed to be 1, yielding the (ordinary)
453
+ Bernoulli function which interpolates the Bernoulli numbers and is
454
+ related to the Riemann zeta function.
455
+
456
+ We compute Bernoulli numbers using Ramanujan's formula:
457
+
458
+ .. math :: B_n = \frac{A(n) - S(n)}{\binom{n+3}{n}}
459
+
460
+ where:
461
+
462
+ .. math :: A(n) = \begin{cases} \frac{n+3}{3} &
463
+ n \equiv 0\ \text{or}\ 2 \pmod{6} \\
464
+ -\frac{n+3}{6} & n \equiv 4 \pmod{6} \end{cases}
465
+
466
+ and:
467
+
468
+ .. math :: S(n) = \sum_{k=1}^{[n/6]} \binom{n+3}{n-6k} B_{n-6k}
469
+
470
+ This formula is similar to the sum given in the definition, but
471
+ cuts `\frac{2}{3}` of the terms. For Bernoulli polynomials, we use
472
+ Appell sequences.
473
+
474
+ For `n` a nonnegative integer and `s`, `a`, `x` arbitrary complex numbers,
475
+
476
+ * ``bernoulli(n)`` gives the nth Bernoulli number, `B_n`
477
+ * ``bernoulli(s)`` gives the Bernoulli function `\operatorname{B}(s)`
478
+ * ``bernoulli(n, x)`` gives the nth Bernoulli polynomial in `x`, `B_n(x)`
479
+ * ``bernoulli(s, a)`` gives the generalized Bernoulli function
480
+ `\operatorname{B}(s, a)`
481
+
482
+ .. versionchanged:: 1.12
483
+ ``bernoulli(1)`` gives `+\frac{1}{2}` instead of `-\frac{1}{2}`.
484
+ This choice of value confers several theoretical advantages [5]_,
485
+ including the extension to complex parameters described above
486
+ which this function now implements. The previous behavior, defined
487
+ only for nonnegative integers `n`, can be obtained with
488
+ ``(-1)**n*bernoulli(n)``.
489
+
490
+ Examples
491
+ ========
492
+
493
+ >>> from sympy import bernoulli
494
+ >>> from sympy.abc import x
495
+ >>> [bernoulli(n) for n in range(11)]
496
+ [1, 1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
497
+ >>> bernoulli(1000001)
498
+ 0
499
+ >>> bernoulli(3, x)
500
+ x**3 - 3*x**2/2 + x/2
501
+
502
+ See Also
503
+ ========
504
+
505
+ andre, bell, catalan, euler, fibonacci, harmonic, lucas, genocchi,
506
+ partition, tribonacci, sympy.polys.appellseqs.bernoulli_poly
507
+
508
+ References
509
+ ==========
510
+
511
+ .. [1] https://en.wikipedia.org/wiki/Bernoulli_number
512
+ .. [2] https://en.wikipedia.org/wiki/Bernoulli_polynomial
513
+ .. [3] https://mathworld.wolfram.com/BernoulliNumber.html
514
+ .. [4] https://mathworld.wolfram.com/BernoulliPolynomial.html
515
+ .. [5] Peter Luschny, "The Bernoulli Manifesto",
516
+ https://luschny.de/math/zeta/The-Bernoulli-Manifesto.html
517
+ .. [6] Peter Luschny, "An introduction to the Bernoulli function",
518
+ https://arxiv.org/abs/2009.06743
519
+
520
+ """
521
+
522
+ args: tTuple[Integer]
523
+
524
+ # Calculates B_n for positive even n
525
+ @staticmethod
526
+ def _calc_bernoulli(n):
527
+ s = 0
528
+ a = int(binomial(n + 3, n - 6))
529
+ for j in range(1, n//6 + 1):
530
+ s += a * bernoulli(n - 6*j)
531
+ # Avoid computing each binomial coefficient from scratch
532
+ a *= _product(n - 6 - 6*j + 1, n - 6*j)
533
+ a //= _product(6*j + 4, 6*j + 9)
534
+ if n % 6 == 4:
535
+ s = -Rational(n + 3, 6) - s
536
+ else:
537
+ s = Rational(n + 3, 3) - s
538
+ return s / binomial(n + 3, n)
539
+
540
+ # We implement a specialized memoization scheme to handle each
541
+ # case modulo 6 separately
542
+ _cache = {0: S.One, 2: Rational(1, 6), 4: Rational(-1, 30)}
543
+ _highest = {0: 0, 2: 2, 4: 4}
544
+
545
+ @classmethod
546
+ def eval(cls, n, x=None):
547
+ if x is S.One:
548
+ return cls(n)
549
+ elif n.is_zero:
550
+ return S.One
551
+ elif n.is_integer is False or n.is_nonnegative is False:
552
+ if x is not None and x.is_Integer and x.is_nonpositive:
553
+ return S.NaN
554
+ return
555
+ # Bernoulli numbers
556
+ elif x is None:
557
+ if n is S.One:
558
+ return S.Half
559
+ elif n.is_odd and (n-1).is_positive:
560
+ return S.Zero
561
+ elif n.is_Number:
562
+ n = int(n)
563
+ # Use mpmath for enormous Bernoulli numbers
564
+ if n > 500:
565
+ p, q = mp.bernfrac(n)
566
+ return Rational(int(p), int(q))
567
+ case = n % 6
568
+ highest_cached = cls._highest[case]
569
+ if n <= highest_cached:
570
+ return cls._cache[n]
571
+ # To avoid excessive recursion when, say, bernoulli(1000) is
572
+ # requested, calculate and cache the entire sequence ... B_988,
573
+ # B_994, B_1000 in increasing order
574
+ for i in range(highest_cached + 6, n + 6, 6):
575
+ b = cls._calc_bernoulli(i)
576
+ cls._cache[i] = b
577
+ cls._highest[case] = i
578
+ return b
579
+ # Bernoulli polynomials
580
+ elif n.is_Number:
581
+ return bernoulli_poly(n, x)
582
+
583
+ def _eval_rewrite_as_zeta(self, n, x=1, **kwargs):
584
+ from sympy.functions.special.zeta_functions import zeta
585
+ return Piecewise((1, Eq(n, 0)), (-n * zeta(1-n, x), True))
586
+
587
+ def _eval_evalf(self, prec):
588
+ if not all(x.is_number for x in self.args):
589
+ return
590
+ n = self.args[0]._to_mpmath(prec)
591
+ x = (self.args[1] if len(self.args) > 1 else S.One)._to_mpmath(prec)
592
+ with workprec(prec):
593
+ if n == 0:
594
+ res = mp.mpf(1)
595
+ elif n == 1:
596
+ res = x - mp.mpf(0.5)
597
+ elif mp.isint(n) and n >= 0:
598
+ res = mp.bernoulli(n) if x == 1 else mp.bernpoly(n, x)
599
+ else:
600
+ res = -n * mp.zeta(1-n, x)
601
+ return Expr._from_mpmath(res, prec)
602
+
603
+
604
+ #----------------------------------------------------------------------------#
605
+ # #
606
+ # Bell numbers #
607
+ # #
608
+ #----------------------------------------------------------------------------#
609
+
610
+
611
+ class bell(Function):
612
+ r"""
613
+ Bell numbers / Bell polynomials
614
+
615
+ The Bell numbers satisfy `B_0 = 1` and
616
+
617
+ .. math:: B_n = \sum_{k=0}^{n-1} \binom{n-1}{k} B_k.
618
+
619
+ They are also given by:
620
+
621
+ .. math:: B_n = \frac{1}{e} \sum_{k=0}^{\infty} \frac{k^n}{k!}.
622
+
623
+ The Bell polynomials are given by `B_0(x) = 1` and
624
+
625
+ .. math:: B_n(x) = x \sum_{k=1}^{n-1} \binom{n-1}{k-1} B_{k-1}(x).
626
+
627
+ The second kind of Bell polynomials (are sometimes called "partial" Bell
628
+ polynomials or incomplete Bell polynomials) are defined as
629
+
630
+ .. math:: B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) =
631
+ \sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n}
632
+ \frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!}
633
+ \left(\frac{x_1}{1!} \right)^{j_1}
634
+ \left(\frac{x_2}{2!} \right)^{j_2} \dotsb
635
+ \left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}.
636
+
637
+ * ``bell(n)`` gives the `n^{th}` Bell number, `B_n`.
638
+ * ``bell(n, x)`` gives the `n^{th}` Bell polynomial, `B_n(x)`.
639
+ * ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind,
640
+ `B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`.
641
+
642
+ Notes
643
+ =====
644
+
645
+ Not to be confused with Bernoulli numbers and Bernoulli polynomials,
646
+ which use the same notation.
647
+
648
+ Examples
649
+ ========
650
+
651
+ >>> from sympy import bell, Symbol, symbols
652
+
653
+ >>> [bell(n) for n in range(11)]
654
+ [1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975]
655
+ >>> bell(30)
656
+ 846749014511809332450147
657
+ >>> bell(4, Symbol('t'))
658
+ t**4 + 6*t**3 + 7*t**2 + t
659
+ >>> bell(6, 2, symbols('x:6')[1:])
660
+ 6*x1*x5 + 15*x2*x4 + 10*x3**2
661
+
662
+ See Also
663
+ ========
664
+
665
+ bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci
666
+
667
+ References
668
+ ==========
669
+
670
+ .. [1] https://en.wikipedia.org/wiki/Bell_number
671
+ .. [2] https://mathworld.wolfram.com/BellNumber.html
672
+ .. [3] https://mathworld.wolfram.com/BellPolynomial.html
673
+
674
+ """
675
+
676
+ @staticmethod
677
+ @recurrence_memo([1, 1])
678
+ def _bell(n, prev):
679
+ s = 1
680
+ a = 1
681
+ for k in range(1, n):
682
+ a = a * (n - k) // k
683
+ s += a * prev[k]
684
+ return s
685
+
686
+ @staticmethod
687
+ @recurrence_memo([S.One, _sym])
688
+ def _bell_poly(n, prev):
689
+ s = 1
690
+ a = 1
691
+ for k in range(2, n + 1):
692
+ a = a * (n - k + 1) // (k - 1)
693
+ s += a * prev[k - 1]
694
+ return expand_mul(_sym * s)
695
+
696
+ @staticmethod
697
+ def _bell_incomplete_poly(n, k, symbols):
698
+ r"""
699
+ The second kind of Bell polynomials (incomplete Bell polynomials).
700
+
701
+ Calculated by recurrence formula:
702
+
703
+ .. math:: B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1}) =
704
+ \sum_{m=1}^{n-k+1}
705
+ \x_m \binom{n-1}{m-1} B_{n-m,k-1}(x_1, x_2, \dotsc, x_{n-m-k})
706
+
707
+ where
708
+ `B_{0,0} = 1;`
709
+ `B_{n,0} = 0; for n \ge 1`
710
+ `B_{0,k} = 0; for k \ge 1`
711
+
712
+ """
713
+ if (n == 0) and (k == 0):
714
+ return S.One
715
+ elif (n == 0) or (k == 0):
716
+ return S.Zero
717
+ s = S.Zero
718
+ a = S.One
719
+ for m in range(1, n - k + 2):
720
+ s += a * bell._bell_incomplete_poly(
721
+ n - m, k - 1, symbols) * symbols[m - 1]
722
+ a = a * (n - m) / m
723
+ return expand_mul(s)
724
+
725
+ @classmethod
726
+ def eval(cls, n, k_sym=None, symbols=None):
727
+ if n is S.Infinity:
728
+ if k_sym is None:
729
+ return S.Infinity
730
+ else:
731
+ raise ValueError("Bell polynomial is not defined")
732
+
733
+ if n.is_negative or n.is_integer is False:
734
+ raise ValueError("a non-negative integer expected")
735
+
736
+ if n.is_Integer and n.is_nonnegative:
737
+ if k_sym is None:
738
+ return Integer(cls._bell(int(n)))
739
+ elif symbols is None:
740
+ return cls._bell_poly(int(n)).subs(_sym, k_sym)
741
+ else:
742
+ r = cls._bell_incomplete_poly(int(n), int(k_sym), symbols)
743
+ return r
744
+
745
+ def _eval_rewrite_as_Sum(self, n, k_sym=None, symbols=None, **kwargs):
746
+ from sympy.concrete.summations import Sum
747
+ if (k_sym is not None) or (symbols is not None):
748
+ return self
749
+
750
+ # Dobinski's formula
751
+ if not n.is_nonnegative:
752
+ return self
753
+ k = Dummy('k', integer=True, nonnegative=True)
754
+ return 1 / E * Sum(k**n / factorial(k), (k, 0, S.Infinity))
755
+
756
+
757
+ #----------------------------------------------------------------------------#
758
+ # #
759
+ # Harmonic numbers #
760
+ # #
761
+ #----------------------------------------------------------------------------#
762
+
763
+
764
+ class harmonic(Function):
765
+ r"""
766
+ Harmonic numbers
767
+
768
+ The nth harmonic number is given by `\operatorname{H}_{n} =
769
+ 1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}`.
770
+
771
+ More generally:
772
+
773
+ .. math:: \operatorname{H}_{n,m} = \sum_{k=1}^{n} \frac{1}{k^m}
774
+
775
+ As `n \rightarrow \infty`, `\operatorname{H}_{n,m} \rightarrow \zeta(m)`,
776
+ the Riemann zeta function.
777
+
778
+ * ``harmonic(n)`` gives the nth harmonic number, `\operatorname{H}_n`
779
+
780
+ * ``harmonic(n, m)`` gives the nth generalized harmonic number
781
+ of order `m`, `\operatorname{H}_{n,m}`, where
782
+ ``harmonic(n) == harmonic(n, 1)``
783
+
784
+ This function can be extended to complex `n` and `m` where `n` is not a
785
+ negative integer or `m` is a nonpositive integer as
786
+
787
+ .. math:: \operatorname{H}_{n,m} = \begin{cases} \zeta(m) - \zeta(m, n+1)
788
+ & m \ne 1 \\ \psi(n+1) + \gamma & m = 1 \end{cases}
789
+
790
+ Examples
791
+ ========
792
+
793
+ >>> from sympy import harmonic, oo
794
+
795
+ >>> [harmonic(n) for n in range(6)]
796
+ [0, 1, 3/2, 11/6, 25/12, 137/60]
797
+ >>> [harmonic(n, 2) for n in range(6)]
798
+ [0, 1, 5/4, 49/36, 205/144, 5269/3600]
799
+ >>> harmonic(oo, 2)
800
+ pi**2/6
801
+
802
+ >>> from sympy import Symbol, Sum
803
+ >>> n = Symbol("n")
804
+
805
+ >>> harmonic(n).rewrite(Sum)
806
+ Sum(1/_k, (_k, 1, n))
807
+
808
+ We can evaluate harmonic numbers for all integral and positive
809
+ rational arguments:
810
+
811
+ >>> from sympy import S, expand_func, simplify
812
+ >>> harmonic(8)
813
+ 761/280
814
+ >>> harmonic(11)
815
+ 83711/27720
816
+
817
+ >>> H = harmonic(1/S(3))
818
+ >>> H
819
+ harmonic(1/3)
820
+ >>> He = expand_func(H)
821
+ >>> He
822
+ -log(6) - sqrt(3)*pi/6 + 2*Sum(log(sin(_k*pi/3))*cos(2*_k*pi/3), (_k, 1, 1))
823
+ + 3*Sum(1/(3*_k + 1), (_k, 0, 0))
824
+ >>> He.doit()
825
+ -log(6) - sqrt(3)*pi/6 - log(sqrt(3)/2) + 3
826
+ >>> H = harmonic(25/S(7))
827
+ >>> He = simplify(expand_func(H).doit())
828
+ >>> He
829
+ log(sin(2*pi/7)**(2*cos(16*pi/7))/(14*sin(pi/7)**(2*cos(pi/7))*cos(pi/14)**(2*sin(pi/14)))) + pi*tan(pi/14)/2 + 30247/9900
830
+ >>> He.n(40)
831
+ 1.983697455232980674869851942390639915940
832
+ >>> harmonic(25/S(7)).n(40)
833
+ 1.983697455232980674869851942390639915940
834
+
835
+ We can rewrite harmonic numbers in terms of polygamma functions:
836
+
837
+ >>> from sympy import digamma, polygamma
838
+ >>> m = Symbol("m", integer=True, positive=True)
839
+
840
+ >>> harmonic(n).rewrite(digamma)
841
+ polygamma(0, n + 1) + EulerGamma
842
+
843
+ >>> harmonic(n).rewrite(polygamma)
844
+ polygamma(0, n + 1) + EulerGamma
845
+
846
+ >>> harmonic(n,3).rewrite(polygamma)
847
+ polygamma(2, n + 1)/2 + zeta(3)
848
+
849
+ >>> simplify(harmonic(n,m).rewrite(polygamma))
850
+ Piecewise((polygamma(0, n + 1) + EulerGamma, Eq(m, 1)),
851
+ (-(-1)**m*polygamma(m - 1, n + 1)/factorial(m - 1) + zeta(m), True))
852
+
853
+ Integer offsets in the argument can be pulled out:
854
+
855
+ >>> from sympy import expand_func
856
+
857
+ >>> expand_func(harmonic(n+4))
858
+ harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)
859
+
860
+ >>> expand_func(harmonic(n-4))
861
+ harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n
862
+
863
+ Some limits can be computed as well:
864
+
865
+ >>> from sympy import limit, oo
866
+
867
+ >>> limit(harmonic(n), n, oo)
868
+ oo
869
+
870
+ >>> limit(harmonic(n, 2), n, oo)
871
+ pi**2/6
872
+
873
+ >>> limit(harmonic(n, 3), n, oo)
874
+ zeta(3)
875
+
876
+ For `m > 1`, `H_{n,m}` tends to `\zeta(m)` in the limit of infinite `n`:
877
+
878
+ >>> m = Symbol("m", positive=True)
879
+ >>> limit(harmonic(n, m+1), n, oo)
880
+ zeta(m + 1)
881
+
882
+ See Also
883
+ ========
884
+
885
+ bell, bernoulli, catalan, euler, fibonacci, lucas, genocchi, partition, tribonacci
886
+
887
+ References
888
+ ==========
889
+
890
+ .. [1] https://en.wikipedia.org/wiki/Harmonic_number
891
+ .. [2] https://functions.wolfram.com/GammaBetaErf/HarmonicNumber/
892
+ .. [3] https://functions.wolfram.com/GammaBetaErf/HarmonicNumber2/
893
+
894
+ """
895
+
896
+ @classmethod
897
+ def eval(cls, n, m=None):
898
+ from sympy.functions.special.zeta_functions import zeta
899
+ if m is S.One:
900
+ return cls(n)
901
+ if m is None:
902
+ m = S.One
903
+ if n.is_zero:
904
+ return S.Zero
905
+ elif m.is_zero:
906
+ return n
907
+ elif n is S.Infinity:
908
+ if m.is_negative:
909
+ return S.NaN
910
+ elif is_le(m, S.One):
911
+ return S.Infinity
912
+ elif is_gt(m, S.One):
913
+ return zeta(m)
914
+ elif m.is_Integer and m.is_nonpositive:
915
+ return (bernoulli(1-m, n+1) - bernoulli(1-m)) / (1-m)
916
+ elif n.is_Integer:
917
+ if n.is_negative and (m.is_integer is False or m.is_nonpositive is False):
918
+ return S.ComplexInfinity if m is S.One else S.NaN
919
+ if n.is_nonnegative:
920
+ return Add(*(k**(-m) for k in range(1, int(n)+1)))
921
+
922
+ def _eval_rewrite_as_polygamma(self, n, m=S.One, **kwargs):
923
+ from sympy.functions.special.gamma_functions import gamma, polygamma
924
+ if m.is_integer and m.is_positive:
925
+ return Piecewise((polygamma(0, n+1) + S.EulerGamma, Eq(m, 1)),
926
+ (S.NegativeOne**m * (polygamma(m-1, 1) - polygamma(m-1, n+1)) /
927
+ gamma(m), True))
928
+
929
+ def _eval_rewrite_as_digamma(self, n, m=1, **kwargs):
930
+ from sympy.functions.special.gamma_functions import polygamma
931
+ return self.rewrite(polygamma)
932
+
933
+ def _eval_rewrite_as_trigamma(self, n, m=1, **kwargs):
934
+ from sympy.functions.special.gamma_functions import polygamma
935
+ return self.rewrite(polygamma)
936
+
937
+ def _eval_rewrite_as_Sum(self, n, m=None, **kwargs):
938
+ from sympy.concrete.summations import Sum
939
+ k = Dummy("k", integer=True)
940
+ if m is None:
941
+ m = S.One
942
+ return Sum(k**(-m), (k, 1, n))
943
+
944
+ def _eval_rewrite_as_zeta(self, n, m=S.One, **kwargs):
945
+ from sympy.functions.special.zeta_functions import zeta
946
+ from sympy.functions.special.gamma_functions import digamma
947
+ return Piecewise((digamma(n + 1) + S.EulerGamma, Eq(m, 1)),
948
+ (zeta(m) - zeta(m, n+1), True))
949
+
950
+ def _eval_expand_func(self, **hints):
951
+ from sympy.concrete.summations import Sum
952
+ n = self.args[0]
953
+ m = self.args[1] if len(self.args) == 2 else 1
954
+
955
+ if m == S.One:
956
+ if n.is_Add:
957
+ off = n.args[0]
958
+ nnew = n - off
959
+ if off.is_Integer and off.is_positive:
960
+ result = [S.One/(nnew + i) for i in range(off, 0, -1)] + [harmonic(nnew)]
961
+ return Add(*result)
962
+ elif off.is_Integer and off.is_negative:
963
+ result = [-S.One/(nnew + i) for i in range(0, off, -1)] + [harmonic(nnew)]
964
+ return Add(*result)
965
+
966
+ if n.is_Rational:
967
+ # Expansions for harmonic numbers at general rational arguments (u + p/q)
968
+ # Split n as u + p/q with p < q
969
+ p, q = n.as_numer_denom()
970
+ u = p // q
971
+ p = p - u * q
972
+ if u.is_nonnegative and p.is_positive and q.is_positive and p < q:
973
+ from sympy.functions.elementary.exponential import log
974
+ from sympy.functions.elementary.integers import floor
975
+ from sympy.functions.elementary.trigonometric import sin, cos, cot
976
+ k = Dummy("k")
977
+ t1 = q * Sum(1 / (q * k + p), (k, 0, u))
978
+ t2 = 2 * Sum(cos((2 * pi * p * k) / S(q)) *
979
+ log(sin((pi * k) / S(q))),
980
+ (k, 1, floor((q - 1) / S(2))))
981
+ t3 = (pi / 2) * cot((pi * p) / q) + log(2 * q)
982
+ return t1 + t2 - t3
983
+
984
+ return self
985
+
986
+ def _eval_rewrite_as_tractable(self, n, m=1, limitvar=None, **kwargs):
987
+ from sympy.functions.special.zeta_functions import zeta
988
+ from sympy.functions.special.gamma_functions import polygamma
989
+ pg = self.rewrite(polygamma)
990
+ if not isinstance(pg, harmonic):
991
+ return pg.rewrite("tractable", deep=True)
992
+ arg = m - S.One
993
+ if arg.is_nonzero:
994
+ return (zeta(m) - zeta(m, n+1)).rewrite("tractable", deep=True)
995
+
996
+ def _eval_evalf(self, prec):
997
+ if not all(x.is_number for x in self.args):
998
+ return
999
+ n = self.args[0]._to_mpmath(prec)
1000
+ m = (self.args[1] if len(self.args) > 1 else S.One)._to_mpmath(prec)
1001
+ if mp.isint(n) and n < 0:
1002
+ return S.NaN
1003
+ with workprec(prec):
1004
+ if m == 1:
1005
+ res = mp.harmonic(n)
1006
+ else:
1007
+ res = mp.zeta(m) - mp.zeta(m, n+1)
1008
+ return Expr._from_mpmath(res, prec)
1009
+
1010
+ def fdiff(self, argindex=1):
1011
+ from sympy.functions.special.zeta_functions import zeta
1012
+ if len(self.args) == 2:
1013
+ n, m = self.args
1014
+ else:
1015
+ n, m = self.args + (1,)
1016
+ if argindex == 1:
1017
+ return m * zeta(m+1, n+1)
1018
+ else:
1019
+ raise ArgumentIndexError
1020
+
1021
+
1022
+ #----------------------------------------------------------------------------#
1023
+ # #
1024
+ # Euler numbers #
1025
+ # #
1026
+ #----------------------------------------------------------------------------#
1027
+
1028
+
1029
+ class euler(Function):
1030
+ r"""
1031
+ Euler numbers / Euler polynomials / Euler function
1032
+
1033
+ The Euler numbers are given by:
1034
+
1035
+ .. math:: E_{2n} = I \sum_{k=1}^{2n+1} \sum_{j=0}^k \binom{k}{j}
1036
+ \frac{(-1)^j (k-2j)^{2n+1}}{2^k I^k k}
1037
+
1038
+ .. math:: E_{2n+1} = 0
1039
+
1040
+ Euler numbers and Euler polynomials are related by
1041
+
1042
+ .. math:: E_n = 2^n E_n\left(\frac{1}{2}\right).
1043
+
1044
+ We compute symbolic Euler polynomials using Appell sequences,
1045
+ but numerical evaluation of the Euler polynomial is computed
1046
+ more efficiently (and more accurately) using the mpmath library.
1047
+
1048
+ The Euler polynomials are special cases of the generalized Euler function,
1049
+ related to the Genocchi function as
1050
+
1051
+ .. math:: \operatorname{E}(s, a) = -\frac{\operatorname{G}(s+1, a)}{s+1}
1052
+
1053
+ with the limit of `\psi\left(\frac{a+1}{2}\right) - \psi\left(\frac{a}{2}\right)`
1054
+ being taken when `s = -1`. The (ordinary) Euler function interpolating
1055
+ the Euler numbers is then obtained as
1056
+ `\operatorname{E}(s) = 2^s \operatorname{E}\left(s, \frac{1}{2}\right)`.
1057
+
1058
+ * ``euler(n)`` gives the nth Euler number `E_n`.
1059
+ * ``euler(s)`` gives the Euler function `\operatorname{E}(s)`.
1060
+ * ``euler(n, x)`` gives the nth Euler polynomial `E_n(x)`.
1061
+ * ``euler(s, a)`` gives the generalized Euler function `\operatorname{E}(s, a)`.
1062
+
1063
+ Examples
1064
+ ========
1065
+
1066
+ >>> from sympy import euler, Symbol, S
1067
+ >>> [euler(n) for n in range(10)]
1068
+ [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0]
1069
+ >>> [2**n*euler(n,1) for n in range(10)]
1070
+ [1, 1, 0, -2, 0, 16, 0, -272, 0, 7936]
1071
+ >>> n = Symbol("n")
1072
+ >>> euler(n + 2*n)
1073
+ euler(3*n)
1074
+
1075
+ >>> x = Symbol("x")
1076
+ >>> euler(n, x)
1077
+ euler(n, x)
1078
+
1079
+ >>> euler(0, x)
1080
+ 1
1081
+ >>> euler(1, x)
1082
+ x - 1/2
1083
+ >>> euler(2, x)
1084
+ x**2 - x
1085
+ >>> euler(3, x)
1086
+ x**3 - 3*x**2/2 + 1/4
1087
+ >>> euler(4, x)
1088
+ x**4 - 2*x**3 + x
1089
+
1090
+ >>> euler(12, S.Half)
1091
+ 2702765/4096
1092
+ >>> euler(12)
1093
+ 2702765
1094
+
1095
+ See Also
1096
+ ========
1097
+
1098
+ andre, bell, bernoulli, catalan, fibonacci, harmonic, lucas, genocchi,
1099
+ partition, tribonacci, sympy.polys.appellseqs.euler_poly
1100
+
1101
+ References
1102
+ ==========
1103
+
1104
+ .. [1] https://en.wikipedia.org/wiki/Euler_numbers
1105
+ .. [2] https://mathworld.wolfram.com/EulerNumber.html
1106
+ .. [3] https://en.wikipedia.org/wiki/Alternating_permutation
1107
+ .. [4] https://mathworld.wolfram.com/AlternatingPermutation.html
1108
+
1109
+ """
1110
+
1111
+ @classmethod
1112
+ def eval(cls, n, x=None):
1113
+ if n.is_zero:
1114
+ return S.One
1115
+ elif n is S.NegativeOne:
1116
+ if x is None:
1117
+ return S.Pi/2
1118
+ from sympy.functions.special.gamma_functions import digamma
1119
+ return digamma((x+1)/2) - digamma(x/2)
1120
+ elif n.is_integer is False or n.is_nonnegative is False:
1121
+ return
1122
+ # Euler numbers
1123
+ elif x is None:
1124
+ if n.is_odd and n.is_positive:
1125
+ return S.Zero
1126
+ elif n.is_Number:
1127
+ from mpmath import mp
1128
+ n = n._to_mpmath(mp.prec)
1129
+ res = mp.eulernum(n, exact=True)
1130
+ return Integer(res)
1131
+ # Euler polynomials
1132
+ elif n.is_Number:
1133
+ return euler_poly(n, x)
1134
+
1135
+ def _eval_rewrite_as_Sum(self, n, x=None, **kwargs):
1136
+ from sympy.concrete.summations import Sum
1137
+ if x is None and n.is_even:
1138
+ k = Dummy("k", integer=True)
1139
+ j = Dummy("j", integer=True)
1140
+ n = n / 2
1141
+ Em = (S.ImaginaryUnit * Sum(Sum(binomial(k, j) * (S.NegativeOne**j *
1142
+ (k - 2*j)**(2*n + 1)) /
1143
+ (2**k*S.ImaginaryUnit**k * k), (j, 0, k)), (k, 1, 2*n + 1)))
1144
+ return Em
1145
+ if x:
1146
+ k = Dummy("k", integer=True)
1147
+ return Sum(binomial(n, k)*euler(k)/2**k*(x - S.Half)**(n - k), (k, 0, n))
1148
+
1149
+ def _eval_rewrite_as_genocchi(self, n, x=None, **kwargs):
1150
+ if x is None:
1151
+ return Piecewise((S.Pi/2, Eq(n, -1)),
1152
+ (-2**n * genocchi(n+1, S.Half) / (n+1), True))
1153
+ from sympy.functions.special.gamma_functions import digamma
1154
+ return Piecewise((digamma((x+1)/2) - digamma(x/2), Eq(n, -1)),
1155
+ (-genocchi(n+1, x) / (n+1), True))
1156
+
1157
+ def _eval_evalf(self, prec):
1158
+ if not all(i.is_number for i in self.args):
1159
+ return
1160
+ from mpmath import mp
1161
+ m, x = (self.args[0], None) if len(self.args) == 1 else self.args
1162
+ m = m._to_mpmath(prec)
1163
+ if x is not None:
1164
+ x = x._to_mpmath(prec)
1165
+ with workprec(prec):
1166
+ if mp.isint(m) and m >= 0:
1167
+ res = mp.eulernum(m) if x is None else mp.eulerpoly(m, x)
1168
+ else:
1169
+ if m == -1:
1170
+ res = mp.pi if x is None else mp.digamma((x+1)/2) - mp.digamma(x/2)
1171
+ else:
1172
+ y = 0.5 if x is None else x
1173
+ res = 2 * (mp.zeta(-m, y) - 2**(m+1) * mp.zeta(-m, (y+1)/2))
1174
+ if x is None:
1175
+ res *= 2**m
1176
+ return Expr._from_mpmath(res, prec)
1177
+
1178
+
1179
+ #----------------------------------------------------------------------------#
1180
+ # #
1181
+ # Catalan numbers #
1182
+ # #
1183
+ #----------------------------------------------------------------------------#
1184
+
1185
+
1186
+ class catalan(Function):
1187
+ r"""
1188
+ Catalan numbers
1189
+
1190
+ The `n^{th}` catalan number is given by:
1191
+
1192
+ .. math :: C_n = \frac{1}{n+1} \binom{2n}{n}
1193
+
1194
+ * ``catalan(n)`` gives the `n^{th}` Catalan number, `C_n`
1195
+
1196
+ Examples
1197
+ ========
1198
+
1199
+ >>> from sympy import (Symbol, binomial, gamma, hyper,
1200
+ ... catalan, diff, combsimp, Rational, I)
1201
+
1202
+ >>> [catalan(i) for i in range(1,10)]
1203
+ [1, 2, 5, 14, 42, 132, 429, 1430, 4862]
1204
+
1205
+ >>> n = Symbol("n", integer=True)
1206
+
1207
+ >>> catalan(n)
1208
+ catalan(n)
1209
+
1210
+ Catalan numbers can be transformed into several other, identical
1211
+ expressions involving other mathematical functions
1212
+
1213
+ >>> catalan(n).rewrite(binomial)
1214
+ binomial(2*n, n)/(n + 1)
1215
+
1216
+ >>> catalan(n).rewrite(gamma)
1217
+ 4**n*gamma(n + 1/2)/(sqrt(pi)*gamma(n + 2))
1218
+
1219
+ >>> catalan(n).rewrite(hyper)
1220
+ hyper((1 - n, -n), (2,), 1)
1221
+
1222
+ For some non-integer values of n we can get closed form
1223
+ expressions by rewriting in terms of gamma functions:
1224
+
1225
+ >>> catalan(Rational(1, 2)).rewrite(gamma)
1226
+ 8/(3*pi)
1227
+
1228
+ We can differentiate the Catalan numbers C(n) interpreted as a
1229
+ continuous real function in n:
1230
+
1231
+ >>> diff(catalan(n), n)
1232
+ (polygamma(0, n + 1/2) - polygamma(0, n + 2) + log(4))*catalan(n)
1233
+
1234
+ As a more advanced example consider the following ratio
1235
+ between consecutive numbers:
1236
+
1237
+ >>> combsimp((catalan(n + 1)/catalan(n)).rewrite(binomial))
1238
+ 2*(2*n + 1)/(n + 2)
1239
+
1240
+ The Catalan numbers can be generalized to complex numbers:
1241
+
1242
+ >>> catalan(I).rewrite(gamma)
1243
+ 4**I*gamma(1/2 + I)/(sqrt(pi)*gamma(2 + I))
1244
+
1245
+ and evaluated with arbitrary precision:
1246
+
1247
+ >>> catalan(I).evalf(20)
1248
+ 0.39764993382373624267 - 0.020884341620842555705*I
1249
+
1250
+ See Also
1251
+ ========
1252
+
1253
+ andre, bell, bernoulli, euler, fibonacci, harmonic, lucas, genocchi,
1254
+ partition, tribonacci, sympy.functions.combinatorial.factorials.binomial
1255
+
1256
+ References
1257
+ ==========
1258
+
1259
+ .. [1] https://en.wikipedia.org/wiki/Catalan_number
1260
+ .. [2] https://mathworld.wolfram.com/CatalanNumber.html
1261
+ .. [3] https://functions.wolfram.com/GammaBetaErf/CatalanNumber/
1262
+ .. [4] http://geometer.org/mathcircles/catalan.pdf
1263
+
1264
+ """
1265
+
1266
+ @classmethod
1267
+ def eval(cls, n):
1268
+ from sympy.functions.special.gamma_functions import gamma
1269
+ if (n.is_Integer and n.is_nonnegative) or \
1270
+ (n.is_noninteger and n.is_negative):
1271
+ return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
1272
+
1273
+ if (n.is_integer and n.is_negative):
1274
+ if (n + 1).is_negative:
1275
+ return S.Zero
1276
+ if (n + 1).is_zero:
1277
+ return Rational(-1, 2)
1278
+
1279
+ def fdiff(self, argindex=1):
1280
+ from sympy.functions.elementary.exponential import log
1281
+ from sympy.functions.special.gamma_functions import polygamma
1282
+ n = self.args[0]
1283
+ return catalan(n)*(polygamma(0, n + S.Half) - polygamma(0, n + 2) + log(4))
1284
+
1285
+ def _eval_rewrite_as_binomial(self, n, **kwargs):
1286
+ return binomial(2*n, n)/(n + 1)
1287
+
1288
+ def _eval_rewrite_as_factorial(self, n, **kwargs):
1289
+ return factorial(2*n) / (factorial(n+1) * factorial(n))
1290
+
1291
+ def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
1292
+ from sympy.functions.special.gamma_functions import gamma
1293
+ # The gamma function allows to generalize Catalan numbers to complex n
1294
+ return 4**n*gamma(n + S.Half)/(gamma(S.Half)*gamma(n + 2))
1295
+
1296
+ def _eval_rewrite_as_hyper(self, n, **kwargs):
1297
+ from sympy.functions.special.hyper import hyper
1298
+ return hyper([1 - n, -n], [2], 1)
1299
+
1300
+ def _eval_rewrite_as_Product(self, n, **kwargs):
1301
+ from sympy.concrete.products import Product
1302
+ if not (n.is_integer and n.is_nonnegative):
1303
+ return self
1304
+ k = Dummy('k', integer=True, positive=True)
1305
+ return Product((n + k) / k, (k, 2, n))
1306
+
1307
+ def _eval_is_integer(self):
1308
+ if self.args[0].is_integer and self.args[0].is_nonnegative:
1309
+ return True
1310
+
1311
+ def _eval_is_positive(self):
1312
+ if self.args[0].is_nonnegative:
1313
+ return True
1314
+
1315
+ def _eval_is_composite(self):
1316
+ if self.args[0].is_integer and (self.args[0] - 3).is_positive:
1317
+ return True
1318
+
1319
+ def _eval_evalf(self, prec):
1320
+ from sympy.functions.special.gamma_functions import gamma
1321
+ if self.args[0].is_number:
1322
+ return self.rewrite(gamma)._eval_evalf(prec)
1323
+
1324
+
1325
+ #----------------------------------------------------------------------------#
1326
+ # #
1327
+ # Genocchi numbers #
1328
+ # #
1329
+ #----------------------------------------------------------------------------#
1330
+
1331
+
1332
+ class genocchi(Function):
1333
+ r"""
1334
+ Genocchi numbers / Genocchi polynomials / Genocchi function
1335
+
1336
+ The Genocchi numbers are a sequence of integers `G_n` that satisfy the
1337
+ relation:
1338
+
1339
+ .. math:: \frac{-2t}{1 + e^{-t}} = \sum_{n=0}^\infty \frac{G_n t^n}{n!}
1340
+
1341
+ They are related to the Bernoulli numbers by
1342
+
1343
+ .. math:: G_n = 2 (1 - 2^n) B_n
1344
+
1345
+ and generalize like the Bernoulli numbers to the Genocchi polynomials and
1346
+ function as
1347
+
1348
+ .. math:: \operatorname{G}(s, a) = 2 \left(\operatorname{B}(s, a) -
1349
+ 2^s \operatorname{B}\left(s, \frac{a+1}{2}\right)\right)
1350
+
1351
+ .. versionchanged:: 1.12
1352
+ ``genocchi(1)`` gives `-1` instead of `1`.
1353
+
1354
+ Examples
1355
+ ========
1356
+
1357
+ >>> from sympy import genocchi, Symbol
1358
+ >>> [genocchi(n) for n in range(9)]
1359
+ [0, -1, -1, 0, 1, 0, -3, 0, 17]
1360
+ >>> n = Symbol('n', integer=True, positive=True)
1361
+ >>> genocchi(2*n + 1)
1362
+ 0
1363
+ >>> x = Symbol('x')
1364
+ >>> genocchi(4, x)
1365
+ -4*x**3 + 6*x**2 - 1
1366
+
1367
+ See Also
1368
+ ========
1369
+
1370
+ bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, partition, tribonacci
1371
+ sympy.polys.appellseqs.genocchi_poly
1372
+
1373
+ References
1374
+ ==========
1375
+
1376
+ .. [1] https://en.wikipedia.org/wiki/Genocchi_number
1377
+ .. [2] https://mathworld.wolfram.com/GenocchiNumber.html
1378
+ .. [3] Peter Luschny, "An introduction to the Bernoulli function",
1379
+ https://arxiv.org/abs/2009.06743
1380
+
1381
+ """
1382
+
1383
+ @classmethod
1384
+ def eval(cls, n, x=None):
1385
+ if x is S.One:
1386
+ return cls(n)
1387
+ elif n.is_integer is False or n.is_nonnegative is False:
1388
+ return
1389
+ # Genocchi numbers
1390
+ elif x is None:
1391
+ if n.is_odd and (n-1).is_positive:
1392
+ return S.Zero
1393
+ elif n.is_Number:
1394
+ return 2 * (1-S(2)**n) * bernoulli(n)
1395
+ # Genocchi polynomials
1396
+ elif n.is_Number:
1397
+ return genocchi_poly(n, x)
1398
+
1399
+ def _eval_rewrite_as_bernoulli(self, n, x=1, **kwargs):
1400
+ if x == 1 and n.is_integer and n.is_nonnegative:
1401
+ return 2 * (1-S(2)**n) * bernoulli(n)
1402
+ return 2 * (bernoulli(n, x) - 2**n * bernoulli(n, (x+1) / 2))
1403
+
1404
+ def _eval_rewrite_as_dirichlet_eta(self, n, x=1, **kwargs):
1405
+ from sympy.functions.special.zeta_functions import dirichlet_eta
1406
+ return -2*n * dirichlet_eta(1-n, x)
1407
+
1408
+ def _eval_is_integer(self):
1409
+ if len(self.args) > 1 and self.args[1] != 1:
1410
+ return
1411
+ n = self.args[0]
1412
+ if n.is_integer and n.is_nonnegative:
1413
+ return True
1414
+
1415
+ def _eval_is_negative(self):
1416
+ if len(self.args) > 1 and self.args[1] != 1:
1417
+ return
1418
+ n = self.args[0]
1419
+ if n.is_integer and n.is_nonnegative:
1420
+ if n.is_odd:
1421
+ return fuzzy_not((n-1).is_positive)
1422
+ return (n/2).is_odd
1423
+
1424
+ def _eval_is_positive(self):
1425
+ if len(self.args) > 1 and self.args[1] != 1:
1426
+ return
1427
+ n = self.args[0]
1428
+ if n.is_integer and n.is_nonnegative:
1429
+ if n.is_zero or n.is_odd:
1430
+ return False
1431
+ return (n/2).is_even
1432
+
1433
+ def _eval_is_even(self):
1434
+ if len(self.args) > 1 and self.args[1] != 1:
1435
+ return
1436
+ n = self.args[0]
1437
+ if n.is_integer and n.is_nonnegative:
1438
+ if n.is_even:
1439
+ return n.is_zero
1440
+ return (n-1).is_positive
1441
+
1442
+ def _eval_is_odd(self):
1443
+ if len(self.args) > 1 and self.args[1] != 1:
1444
+ return
1445
+ n = self.args[0]
1446
+ if n.is_integer and n.is_nonnegative:
1447
+ if n.is_even:
1448
+ return fuzzy_not(n.is_zero)
1449
+ return fuzzy_not((n-1).is_positive)
1450
+
1451
+ def _eval_is_prime(self):
1452
+ if len(self.args) > 1 and self.args[1] != 1:
1453
+ return
1454
+ n = self.args[0]
1455
+ # only G_6 = -3 and G_8 = 17 are prime,
1456
+ # but SymPy does not consider negatives as prime
1457
+ # so only n=8 is tested
1458
+ return (n-8).is_zero
1459
+
1460
+ def _eval_evalf(self, prec):
1461
+ if all(i.is_number for i in self.args):
1462
+ return self.rewrite(bernoulli)._eval_evalf(prec)
1463
+
1464
+
1465
+ #----------------------------------------------------------------------------#
1466
+ # #
1467
+ # Andre numbers #
1468
+ # #
1469
+ #----------------------------------------------------------------------------#
1470
+
1471
+
1472
+ class andre(Function):
1473
+ r"""
1474
+ Andre numbers / Andre function
1475
+
1476
+ The Andre number `\mathcal{A}_n` is Luschny's name for half the number of
1477
+ *alternating permutations* on `n` elements, where a permutation is alternating
1478
+ if adjacent elements alternately compare "greater" and "smaller" going from
1479
+ left to right. For example, `2 < 3 > 1 < 4` is an alternating permutation.
1480
+
1481
+ This sequence is A000111 in the OEIS, which assigns the names *up/down numbers*
1482
+ and *Euler zigzag numbers*. It satisfies a recurrence relation similar to that
1483
+ for the Catalan numbers, with `\mathcal{A}_0 = 1` and
1484
+
1485
+ .. math:: 2 \mathcal{A}_{n+1} = \sum_{k=0}^n \binom{n}{k} \mathcal{A}_k \mathcal{A}_{n-k}
1486
+
1487
+ The Bernoulli and Euler numbers are signed transformations of the odd- and
1488
+ even-indexed elements of this sequence respectively:
1489
+
1490
+ .. math :: \operatorname{B}_{2k} = \frac{2k \mathcal{A}_{2k-1}}{(-4)^k - (-16)^k}
1491
+
1492
+ .. math :: \operatorname{E}_{2k} = (-1)^k \mathcal{A}_{2k}
1493
+
1494
+ Like the Bernoulli and Euler numbers, the Andre numbers are interpolated by the
1495
+ entire Andre function:
1496
+
1497
+ .. math :: \mathcal{A}(s) = (-i)^{s+1} \operatorname{Li}_{-s}(i) +
1498
+ i^{s+1} \operatorname{Li}_{-s}(-i) = \\ \frac{2 \Gamma(s+1)}{(2\pi)^{s+1}}
1499
+ (\zeta(s+1, 1/4) - \zeta(s+1, 3/4) \cos{\pi s})
1500
+
1501
+ Examples
1502
+ ========
1503
+
1504
+ >>> from sympy import andre, euler, bernoulli
1505
+ >>> [andre(n) for n in range(11)]
1506
+ [1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]
1507
+ >>> [(-1)**k * andre(2*k) for k in range(7)]
1508
+ [1, -1, 5, -61, 1385, -50521, 2702765]
1509
+ >>> [euler(2*k) for k in range(7)]
1510
+ [1, -1, 5, -61, 1385, -50521, 2702765]
1511
+ >>> [andre(2*k-1) * (2*k) / ((-4)**k - (-16)**k) for k in range(1, 8)]
1512
+ [1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6]
1513
+ >>> [bernoulli(2*k) for k in range(1, 8)]
1514
+ [1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6]
1515
+
1516
+ See Also
1517
+ ========
1518
+
1519
+ bernoulli, catalan, euler, sympy.polys.appellseqs.andre_poly
1520
+
1521
+ References
1522
+ ==========
1523
+
1524
+ .. [1] https://en.wikipedia.org/wiki/Alternating_permutation
1525
+ .. [2] https://mathworld.wolfram.com/EulerZigzagNumber.html
1526
+ .. [3] Peter Luschny, "An introduction to the Bernoulli function",
1527
+ https://arxiv.org/abs/2009.06743
1528
+ """
1529
+
1530
+ @classmethod
1531
+ def eval(cls, n):
1532
+ if n is S.NaN:
1533
+ return S.NaN
1534
+ elif n is S.Infinity:
1535
+ return S.Infinity
1536
+ if n.is_zero:
1537
+ return S.One
1538
+ elif n == -1:
1539
+ return -log(2)
1540
+ elif n == -2:
1541
+ return -2*S.Catalan
1542
+ elif n.is_Integer:
1543
+ if n.is_nonnegative and n.is_even:
1544
+ return abs(euler(n))
1545
+ elif n.is_odd:
1546
+ from sympy.functions.special.zeta_functions import zeta
1547
+ m = -n-1
1548
+ return I**m * Rational(1-2**m, 4**m) * zeta(-n)
1549
+
1550
+ def _eval_rewrite_as_zeta(self, s, **kwargs):
1551
+ from sympy.functions.elementary.trigonometric import cos
1552
+ from sympy.functions.special.gamma_functions import gamma
1553
+ from sympy.functions.special.zeta_functions import zeta
1554
+ return 2 * gamma(s+1) / (2*pi)**(s+1) * \
1555
+ (zeta(s+1, S.One/4) - cos(pi*s) * zeta(s+1, S(3)/4))
1556
+
1557
+ def _eval_rewrite_as_polylog(self, s, **kwargs):
1558
+ from sympy.functions.special.zeta_functions import polylog
1559
+ return (-I)**(s+1) * polylog(-s, I) + I**(s+1) * polylog(-s, -I)
1560
+
1561
+ def _eval_is_integer(self):
1562
+ n = self.args[0]
1563
+ if n.is_integer and n.is_nonnegative:
1564
+ return True
1565
+
1566
+ def _eval_is_positive(self):
1567
+ if self.args[0].is_nonnegative:
1568
+ return True
1569
+
1570
+ def _eval_evalf(self, prec):
1571
+ if not self.args[0].is_number:
1572
+ return
1573
+ s = self.args[0]._to_mpmath(prec+12)
1574
+ with workprec(prec+12):
1575
+ sp, cp = mp.sinpi(s/2), mp.cospi(s/2)
1576
+ res = 2*mp.dirichlet(-s, (-sp, cp, sp, -cp))
1577
+ return Expr._from_mpmath(res, prec)
1578
+
1579
+
1580
+ #----------------------------------------------------------------------------#
1581
+ # #
1582
+ # Partition numbers #
1583
+ # #
1584
+ #----------------------------------------------------------------------------#
1585
+
1586
+ _npartition = [1, 1]
1587
+ class partition(Function):
1588
+ r"""
1589
+ Partition numbers
1590
+
1591
+ The Partition numbers are a sequence of integers `p_n` that represent the
1592
+ number of distinct ways of representing `n` as a sum of natural numbers
1593
+ (with order irrelevant). The generating function for `p_n` is given by:
1594
+
1595
+ .. math:: \sum_{n=0}^\infty p_n x^n = \prod_{k=1}^\infty (1 - x^k)^{-1}
1596
+
1597
+ Examples
1598
+ ========
1599
+
1600
+ >>> from sympy import partition, Symbol
1601
+ >>> [partition(n) for n in range(9)]
1602
+ [1, 1, 2, 3, 5, 7, 11, 15, 22]
1603
+ >>> n = Symbol('n', integer=True, negative=True)
1604
+ >>> partition(n)
1605
+ 0
1606
+
1607
+ See Also
1608
+ ========
1609
+
1610
+ bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, tribonacci
1611
+
1612
+ References
1613
+ ==========
1614
+
1615
+ .. [1] https://en.wikipedia.org/wiki/Partition_(number_theory%29
1616
+ .. [2] https://en.wikipedia.org/wiki/Pentagonal_number_theorem
1617
+
1618
+ """
1619
+
1620
+ @staticmethod
1621
+ def _partition(n):
1622
+ L = len(_npartition)
1623
+ if n < L:
1624
+ return _npartition[n]
1625
+ # lengthen cache
1626
+ for _n in range(L, n + 1):
1627
+ v, p, i = 0, 0, 0
1628
+ while 1:
1629
+ s = 0
1630
+ p += 3*i + 1 # p = pentagonal number: 1, 5, 12, ...
1631
+ if _n >= p:
1632
+ s += _npartition[_n - p]
1633
+ i += 1
1634
+ gp = p + i # gp = generalized pentagonal: 2, 7, 15, ...
1635
+ if _n >= gp:
1636
+ s += _npartition[_n - gp]
1637
+ if s == 0:
1638
+ break
1639
+ else:
1640
+ v += s if i%2 == 1 else -s
1641
+ _npartition.append(v)
1642
+ return v
1643
+
1644
+ @classmethod
1645
+ def eval(cls, n):
1646
+ is_int = n.is_integer
1647
+ if is_int == False:
1648
+ raise ValueError("Partition numbers are defined only for "
1649
+ "integers")
1650
+ elif is_int:
1651
+ if n.is_negative:
1652
+ return S.Zero
1653
+
1654
+ if n.is_zero or (n - 1).is_zero:
1655
+ return S.One
1656
+
1657
+ if n.is_Integer:
1658
+ return Integer(cls._partition(n))
1659
+
1660
+
1661
+ def _eval_is_integer(self):
1662
+ if self.args[0].is_integer:
1663
+ return True
1664
+
1665
+ def _eval_is_negative(self):
1666
+ if self.args[0].is_integer:
1667
+ return False
1668
+
1669
+ def _eval_is_positive(self):
1670
+ n = self.args[0]
1671
+ if n.is_nonnegative and n.is_integer:
1672
+ return True
1673
+
1674
+
1675
+ #######################################################################
1676
+ ###
1677
+ ### Functions for enumerating partitions, permutations and combinations
1678
+ ###
1679
+ #######################################################################
1680
+
1681
+
1682
+ class _MultisetHistogram(tuple):
1683
+ pass
1684
+
1685
+
1686
+ _N = -1
1687
+ _ITEMS = -2
1688
+ _M = slice(None, _ITEMS)
1689
+
1690
+
1691
+ def _multiset_histogram(n):
1692
+ """Return tuple used in permutation and combination counting. Input
1693
+ is a dictionary giving items with counts as values or a sequence of
1694
+ items (which need not be sorted).
1695
+
1696
+ The data is stored in a class deriving from tuple so it is easily
1697
+ recognized and so it can be converted easily to a list.
1698
+ """
1699
+ if isinstance(n, dict): # item: count
1700
+ if not all(isinstance(v, int) and v >= 0 for v in n.values()):
1701
+ raise ValueError
1702
+ tot = sum(n.values())
1703
+ items = sum(1 for k in n if n[k] > 0)
1704
+ return _MultisetHistogram([n[k] for k in n if n[k] > 0] + [items, tot])
1705
+ else:
1706
+ n = list(n)
1707
+ s = set(n)
1708
+ lens = len(s)
1709
+ lenn = len(n)
1710
+ if lens == lenn:
1711
+ n = [1]*lenn + [lenn, lenn]
1712
+ return _MultisetHistogram(n)
1713
+ m = dict(zip(s, range(lens)))
1714
+ d = dict(zip(range(lens), (0,)*lens))
1715
+ for i in n:
1716
+ d[m[i]] += 1
1717
+ return _multiset_histogram(d)
1718
+
1719
+
1720
+ def nP(n, k=None, replacement=False):
1721
+ """Return the number of permutations of ``n`` items taken ``k`` at a time.
1722
+
1723
+ Possible values for ``n``:
1724
+
1725
+ integer - set of length ``n``
1726
+
1727
+ sequence - converted to a multiset internally
1728
+
1729
+ multiset - {element: multiplicity}
1730
+
1731
+ If ``k`` is None then the total of all permutations of length 0
1732
+ through the number of items represented by ``n`` will be returned.
1733
+
1734
+ If ``replacement`` is True then a given item can appear more than once
1735
+ in the ``k`` items. (For example, for 'ab' permutations of 2 would
1736
+ include 'aa', 'ab', 'ba' and 'bb'.) The multiplicity of elements in
1737
+ ``n`` is ignored when ``replacement`` is True but the total number
1738
+ of elements is considered since no element can appear more times than
1739
+ the number of elements in ``n``.
1740
+
1741
+ Examples
1742
+ ========
1743
+
1744
+ >>> from sympy.functions.combinatorial.numbers import nP
1745
+ >>> from sympy.utilities.iterables import multiset_permutations, multiset
1746
+ >>> nP(3, 2)
1747
+ 6
1748
+ >>> nP('abc', 2) == nP(multiset('abc'), 2) == 6
1749
+ True
1750
+ >>> nP('aab', 2)
1751
+ 3
1752
+ >>> nP([1, 2, 2], 2)
1753
+ 3
1754
+ >>> [nP(3, i) for i in range(4)]
1755
+ [1, 3, 6, 6]
1756
+ >>> nP(3) == sum(_)
1757
+ True
1758
+
1759
+ When ``replacement`` is True, each item can have multiplicity
1760
+ equal to the length represented by ``n``:
1761
+
1762
+ >>> nP('aabc', replacement=True)
1763
+ 121
1764
+ >>> [len(list(multiset_permutations('aaaabbbbcccc', i))) for i in range(5)]
1765
+ [1, 3, 9, 27, 81]
1766
+ >>> sum(_)
1767
+ 121
1768
+
1769
+ See Also
1770
+ ========
1771
+ sympy.utilities.iterables.multiset_permutations
1772
+
1773
+ References
1774
+ ==========
1775
+
1776
+ .. [1] https://en.wikipedia.org/wiki/Permutation
1777
+
1778
+ """
1779
+ try:
1780
+ n = as_int(n)
1781
+ except ValueError:
1782
+ return Integer(_nP(_multiset_histogram(n), k, replacement))
1783
+ return Integer(_nP(n, k, replacement))
1784
+
1785
+
1786
+ @cacheit
1787
+ def _nP(n, k=None, replacement=False):
1788
+
1789
+ if k == 0:
1790
+ return 1
1791
+ if isinstance(n, SYMPY_INTS): # n different items
1792
+ # assert n >= 0
1793
+ if k is None:
1794
+ return sum(_nP(n, i, replacement) for i in range(n + 1))
1795
+ elif replacement:
1796
+ return n**k
1797
+ elif k > n:
1798
+ return 0
1799
+ elif k == n:
1800
+ return factorial(k)
1801
+ elif k == 1:
1802
+ return n
1803
+ else:
1804
+ # assert k >= 0
1805
+ return _product(n - k + 1, n)
1806
+ elif isinstance(n, _MultisetHistogram):
1807
+ if k is None:
1808
+ return sum(_nP(n, i, replacement) for i in range(n[_N] + 1))
1809
+ elif replacement:
1810
+ return n[_ITEMS]**k
1811
+ elif k == n[_N]:
1812
+ return factorial(k)/prod([factorial(i) for i in n[_M] if i > 1])
1813
+ elif k > n[_N]:
1814
+ return 0
1815
+ elif k == 1:
1816
+ return n[_ITEMS]
1817
+ else:
1818
+ # assert k >= 0
1819
+ tot = 0
1820
+ n = list(n)
1821
+ for i in range(len(n[_M])):
1822
+ if not n[i]:
1823
+ continue
1824
+ n[_N] -= 1
1825
+ if n[i] == 1:
1826
+ n[i] = 0
1827
+ n[_ITEMS] -= 1
1828
+ tot += _nP(_MultisetHistogram(n), k - 1)
1829
+ n[_ITEMS] += 1
1830
+ n[i] = 1
1831
+ else:
1832
+ n[i] -= 1
1833
+ tot += _nP(_MultisetHistogram(n), k - 1)
1834
+ n[i] += 1
1835
+ n[_N] += 1
1836
+ return tot
1837
+
1838
+
1839
+ @cacheit
1840
+ def _AOP_product(n):
1841
+ """for n = (m1, m2, .., mk) return the coefficients of the polynomial,
1842
+ prod(sum(x**i for i in range(nj + 1)) for nj in n); i.e. the coefficients
1843
+ of the product of AOPs (all-one polynomials) or order given in n. The
1844
+ resulting coefficient corresponding to x**r is the number of r-length
1845
+ combinations of sum(n) elements with multiplicities given in n.
1846
+ The coefficients are given as a default dictionary (so if a query is made
1847
+ for a key that is not present, 0 will be returned).
1848
+
1849
+ Examples
1850
+ ========
1851
+
1852
+ >>> from sympy.functions.combinatorial.numbers import _AOP_product
1853
+ >>> from sympy.abc import x
1854
+ >>> n = (2, 2, 3) # e.g. aabbccc
1855
+ >>> prod = ((x**2 + x + 1)*(x**2 + x + 1)*(x**3 + x**2 + x + 1)).expand()
1856
+ >>> c = _AOP_product(n); dict(c)
1857
+ {0: 1, 1: 3, 2: 6, 3: 8, 4: 8, 5: 6, 6: 3, 7: 1}
1858
+ >>> [c[i] for i in range(8)] == [prod.coeff(x, i) for i in range(8)]
1859
+ True
1860
+
1861
+ The generating poly used here is the same as that listed in
1862
+ https://tinyurl.com/cep849r, but in a refactored form.
1863
+
1864
+ """
1865
+
1866
+ n = list(n)
1867
+ ord = sum(n)
1868
+ need = (ord + 2)//2
1869
+ rv = [1]*(n.pop() + 1)
1870
+ rv.extend((0,) * (need - len(rv)))
1871
+ rv = rv[:need]
1872
+ while n:
1873
+ ni = n.pop()
1874
+ N = ni + 1
1875
+ was = rv[:]
1876
+ for i in range(1, min(N, len(rv))):
1877
+ rv[i] += rv[i - 1]
1878
+ for i in range(N, need):
1879
+ rv[i] += rv[i - 1] - was[i - N]
1880
+ rev = list(reversed(rv))
1881
+ if ord % 2:
1882
+ rv = rv + rev
1883
+ else:
1884
+ rv[-1:] = rev
1885
+ d = defaultdict(int)
1886
+ for i, r in enumerate(rv):
1887
+ d[i] = r
1888
+ return d
1889
+
1890
+
1891
+ def nC(n, k=None, replacement=False):
1892
+ """Return the number of combinations of ``n`` items taken ``k`` at a time.
1893
+
1894
+ Possible values for ``n``:
1895
+
1896
+ integer - set of length ``n``
1897
+
1898
+ sequence - converted to a multiset internally
1899
+
1900
+ multiset - {element: multiplicity}
1901
+
1902
+ If ``k`` is None then the total of all combinations of length 0
1903
+ through the number of items represented in ``n`` will be returned.
1904
+
1905
+ If ``replacement`` is True then a given item can appear more than once
1906
+ in the ``k`` items. (For example, for 'ab' sets of 2 would include 'aa',
1907
+ 'ab', and 'bb'.) The multiplicity of elements in ``n`` is ignored when
1908
+ ``replacement`` is True but the total number of elements is considered
1909
+ since no element can appear more times than the number of elements in
1910
+ ``n``.
1911
+
1912
+ Examples
1913
+ ========
1914
+
1915
+ >>> from sympy.functions.combinatorial.numbers import nC
1916
+ >>> from sympy.utilities.iterables import multiset_combinations
1917
+ >>> nC(3, 2)
1918
+ 3
1919
+ >>> nC('abc', 2)
1920
+ 3
1921
+ >>> nC('aab', 2)
1922
+ 2
1923
+
1924
+ When ``replacement`` is True, each item can have multiplicity
1925
+ equal to the length represented by ``n``:
1926
+
1927
+ >>> nC('aabc', replacement=True)
1928
+ 35
1929
+ >>> [len(list(multiset_combinations('aaaabbbbcccc', i))) for i in range(5)]
1930
+ [1, 3, 6, 10, 15]
1931
+ >>> sum(_)
1932
+ 35
1933
+
1934
+ If there are ``k`` items with multiplicities ``m_1, m_2, ..., m_k``
1935
+ then the total of all combinations of length 0 through ``k`` is the
1936
+ product, ``(m_1 + 1)*(m_2 + 1)*...*(m_k + 1)``. When the multiplicity
1937
+ of each item is 1 (i.e., k unique items) then there are 2**k
1938
+ combinations. For example, if there are 4 unique items, the total number
1939
+ of combinations is 16:
1940
+
1941
+ >>> sum(nC(4, i) for i in range(5))
1942
+ 16
1943
+
1944
+ See Also
1945
+ ========
1946
+
1947
+ sympy.utilities.iterables.multiset_combinations
1948
+
1949
+ References
1950
+ ==========
1951
+
1952
+ .. [1] https://en.wikipedia.org/wiki/Combination
1953
+ .. [2] https://tinyurl.com/cep849r
1954
+
1955
+ """
1956
+
1957
+ if isinstance(n, SYMPY_INTS):
1958
+ if k is None:
1959
+ if not replacement:
1960
+ return 2**n
1961
+ return sum(nC(n, i, replacement) for i in range(n + 1))
1962
+ if k < 0:
1963
+ raise ValueError("k cannot be negative")
1964
+ if replacement:
1965
+ return binomial(n + k - 1, k)
1966
+ return binomial(n, k)
1967
+ if isinstance(n, _MultisetHistogram):
1968
+ N = n[_N]
1969
+ if k is None:
1970
+ if not replacement:
1971
+ return prod(m + 1 for m in n[_M])
1972
+ return sum(nC(n, i, replacement) for i in range(N + 1))
1973
+ elif replacement:
1974
+ return nC(n[_ITEMS], k, replacement)
1975
+ # assert k >= 0
1976
+ elif k in (1, N - 1):
1977
+ return n[_ITEMS]
1978
+ elif k in (0, N):
1979
+ return 1
1980
+ return _AOP_product(tuple(n[_M]))[k]
1981
+ else:
1982
+ return nC(_multiset_histogram(n), k, replacement)
1983
+
1984
+
1985
+ def _eval_stirling1(n, k):
1986
+ if n == k == 0:
1987
+ return S.One
1988
+ if 0 in (n, k):
1989
+ return S.Zero
1990
+
1991
+ # some special values
1992
+ if n == k:
1993
+ return S.One
1994
+ elif k == n - 1:
1995
+ return binomial(n, 2)
1996
+ elif k == n - 2:
1997
+ return (3*n - 1)*binomial(n, 3)/4
1998
+ elif k == n - 3:
1999
+ return binomial(n, 2)*binomial(n, 4)
2000
+
2001
+ return _stirling1(n, k)
2002
+
2003
+
2004
+ @cacheit
2005
+ def _stirling1(n, k):
2006
+ row = [0, 1]+[0]*(k-1) # for n = 1
2007
+ for i in range(2, n+1):
2008
+ for j in range(min(k,i), 0, -1):
2009
+ row[j] = (i-1) * row[j] + row[j-1]
2010
+ return Integer(row[k])
2011
+
2012
+
2013
+ def _eval_stirling2(n, k):
2014
+ if n == k == 0:
2015
+ return S.One
2016
+ if 0 in (n, k):
2017
+ return S.Zero
2018
+
2019
+ # some special values
2020
+ if n == k:
2021
+ return S.One
2022
+ elif k == n - 1:
2023
+ return binomial(n, 2)
2024
+ elif k == 1:
2025
+ return S.One
2026
+ elif k == 2:
2027
+ return Integer(2**(n - 1) - 1)
2028
+
2029
+ return _stirling2(n, k)
2030
+
2031
+
2032
+ @cacheit
2033
+ def _stirling2(n, k):
2034
+ row = [0, 1]+[0]*(k-1) # for n = 1
2035
+ for i in range(2, n+1):
2036
+ for j in range(min(k,i), 0, -1):
2037
+ row[j] = j * row[j] + row[j-1]
2038
+ return Integer(row[k])
2039
+
2040
+
2041
+ def stirling(n, k, d=None, kind=2, signed=False):
2042
+ r"""Return Stirling number $S(n, k)$ of the first or second (default) kind.
2043
+
2044
+ The sum of all Stirling numbers of the second kind for $k = 1$
2045
+ through $n$ is ``bell(n)``. The recurrence relationship for these numbers
2046
+ is:
2047
+
2048
+ .. math :: {0 \brace 0} = 1; {n \brace 0} = {0 \brace k} = 0;
2049
+
2050
+ .. math :: {{n+1} \brace k} = j {n \brace k} + {n \brace {k-1}}
2051
+
2052
+ where $j$ is:
2053
+ $n$ for Stirling numbers of the first kind,
2054
+ $-n$ for signed Stirling numbers of the first kind,
2055
+ $k$ for Stirling numbers of the second kind.
2056
+
2057
+ The first kind of Stirling number counts the number of permutations of
2058
+ ``n`` distinct items that have ``k`` cycles; the second kind counts the
2059
+ ways in which ``n`` distinct items can be partitioned into ``k`` parts.
2060
+ If ``d`` is given, the "reduced Stirling number of the second kind" is
2061
+ returned: $S^{d}(n, k) = S(n - d + 1, k - d + 1)$ with $n \ge k \ge d$.
2062
+ (This counts the ways to partition $n$ consecutive integers into $k$
2063
+ groups with no pairwise difference less than $d$. See example below.)
2064
+
2065
+ To obtain the signed Stirling numbers of the first kind, use keyword
2066
+ ``signed=True``. Using this keyword automatically sets ``kind`` to 1.
2067
+
2068
+ Examples
2069
+ ========
2070
+
2071
+ >>> from sympy.functions.combinatorial.numbers import stirling, bell
2072
+ >>> from sympy.combinatorics import Permutation
2073
+ >>> from sympy.utilities.iterables import multiset_partitions, permutations
2074
+
2075
+ First kind (unsigned by default):
2076
+
2077
+ >>> [stirling(6, i, kind=1) for i in range(7)]
2078
+ [0, 120, 274, 225, 85, 15, 1]
2079
+ >>> perms = list(permutations(range(4)))
2080
+ >>> [sum(Permutation(p).cycles == i for p in perms) for i in range(5)]
2081
+ [0, 6, 11, 6, 1]
2082
+ >>> [stirling(4, i, kind=1) for i in range(5)]
2083
+ [0, 6, 11, 6, 1]
2084
+
2085
+ First kind (signed):
2086
+
2087
+ >>> [stirling(4, i, signed=True) for i in range(5)]
2088
+ [0, -6, 11, -6, 1]
2089
+
2090
+ Second kind:
2091
+
2092
+ >>> [stirling(10, i) for i in range(12)]
2093
+ [0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1, 0]
2094
+ >>> sum(_) == bell(10)
2095
+ True
2096
+ >>> len(list(multiset_partitions(range(4), 2))) == stirling(4, 2)
2097
+ True
2098
+
2099
+ Reduced second kind:
2100
+
2101
+ >>> from sympy import subsets, oo
2102
+ >>> def delta(p):
2103
+ ... if len(p) == 1:
2104
+ ... return oo
2105
+ ... return min(abs(i[0] - i[1]) for i in subsets(p, 2))
2106
+ >>> parts = multiset_partitions(range(5), 3)
2107
+ >>> d = 2
2108
+ >>> sum(1 for p in parts if all(delta(i) >= d for i in p))
2109
+ 7
2110
+ >>> stirling(5, 3, 2)
2111
+ 7
2112
+
2113
+ See Also
2114
+ ========
2115
+ sympy.utilities.iterables.multiset_partitions
2116
+
2117
+
2118
+ References
2119
+ ==========
2120
+
2121
+ .. [1] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
2122
+ .. [2] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
2123
+
2124
+ """
2125
+ # TODO: make this a class like bell()
2126
+
2127
+ n = as_int(n)
2128
+ k = as_int(k)
2129
+ if n < 0:
2130
+ raise ValueError('n must be nonnegative')
2131
+ if k > n:
2132
+ return S.Zero
2133
+ if d:
2134
+ # assert k >= d
2135
+ # kind is ignored -- only kind=2 is supported
2136
+ return _eval_stirling2(n - d + 1, k - d + 1)
2137
+ elif signed:
2138
+ # kind is ignored -- only kind=1 is supported
2139
+ return S.NegativeOne**(n - k)*_eval_stirling1(n, k)
2140
+
2141
+ if kind == 1:
2142
+ return _eval_stirling1(n, k)
2143
+ elif kind == 2:
2144
+ return _eval_stirling2(n, k)
2145
+ else:
2146
+ raise ValueError('kind must be 1 or 2, not %s' % k)
2147
+
2148
+
2149
+ @cacheit
2150
+ def _nT(n, k):
2151
+ """Return the partitions of ``n`` items into ``k`` parts. This
2152
+ is used by ``nT`` for the case when ``n`` is an integer."""
2153
+ # really quick exits
2154
+ if k > n or k < 0:
2155
+ return 0
2156
+ if k in (1, n):
2157
+ return 1
2158
+ if k == 0:
2159
+ return 0
2160
+ # exits that could be done below but this is quicker
2161
+ if k == 2:
2162
+ return n//2
2163
+ d = n - k
2164
+ if d <= 3:
2165
+ return d
2166
+ # quick exit
2167
+ if 3*k >= n: # or, equivalently, 2*k >= d
2168
+ # all the information needed in this case
2169
+ # will be in the cache needed to calculate
2170
+ # partition(d), so...
2171
+ # update cache
2172
+ tot = partition._partition(d)
2173
+ # and correct for values not needed
2174
+ if d - k > 0:
2175
+ tot -= sum(_npartition[:d - k])
2176
+ return tot
2177
+ # regular exit
2178
+ # nT(n, k) = Sum(nT(n - k, m), (m, 1, k));
2179
+ # calculate needed nT(i, j) values
2180
+ p = [1]*d
2181
+ for i in range(2, k + 1):
2182
+ for m in range(i + 1, d):
2183
+ p[m] += p[m - i]
2184
+ d -= 1
2185
+ # if p[0] were appended to the end of p then the last
2186
+ # k values of p are the nT(n, j) values for 0 < j < k in reverse
2187
+ # order p[-1] = nT(n, 1), p[-2] = nT(n, 2), etc.... Instead of
2188
+ # putting the 1 from p[0] there, however, it is simply added to
2189
+ # the sum below which is valid for 1 < k <= n//2
2190
+ return (1 + sum(p[1 - k:]))
2191
+
2192
+
2193
+ def nT(n, k=None):
2194
+ """Return the number of ``k``-sized partitions of ``n`` items.
2195
+
2196
+ Possible values for ``n``:
2197
+
2198
+ integer - ``n`` identical items
2199
+
2200
+ sequence - converted to a multiset internally
2201
+
2202
+ multiset - {element: multiplicity}
2203
+
2204
+ Note: the convention for ``nT`` is different than that of ``nC`` and
2205
+ ``nP`` in that
2206
+ here an integer indicates ``n`` *identical* items instead of a set of
2207
+ length ``n``; this is in keeping with the ``partitions`` function which
2208
+ treats its integer-``n`` input like a list of ``n`` 1s. One can use
2209
+ ``range(n)`` for ``n`` to indicate ``n`` distinct items.
2210
+
2211
+ If ``k`` is None then the total number of ways to partition the elements
2212
+ represented in ``n`` will be returned.
2213
+
2214
+ Examples
2215
+ ========
2216
+
2217
+ >>> from sympy.functions.combinatorial.numbers import nT
2218
+
2219
+ Partitions of the given multiset:
2220
+
2221
+ >>> [nT('aabbc', i) for i in range(1, 7)]
2222
+ [1, 8, 11, 5, 1, 0]
2223
+ >>> nT('aabbc') == sum(_)
2224
+ True
2225
+
2226
+ >>> [nT("mississippi", i) for i in range(1, 12)]
2227
+ [1, 74, 609, 1521, 1768, 1224, 579, 197, 50, 9, 1]
2228
+
2229
+ Partitions when all items are identical:
2230
+
2231
+ >>> [nT(5, i) for i in range(1, 6)]
2232
+ [1, 2, 2, 1, 1]
2233
+ >>> nT('1'*5) == sum(_)
2234
+ True
2235
+
2236
+ When all items are different:
2237
+
2238
+ >>> [nT(range(5), i) for i in range(1, 6)]
2239
+ [1, 15, 25, 10, 1]
2240
+ >>> nT(range(5)) == sum(_)
2241
+ True
2242
+
2243
+ Partitions of an integer expressed as a sum of positive integers:
2244
+
2245
+ >>> from sympy import partition
2246
+ >>> partition(4)
2247
+ 5
2248
+ >>> nT(4, 1) + nT(4, 2) + nT(4, 3) + nT(4, 4)
2249
+ 5
2250
+ >>> nT('1'*4)
2251
+ 5
2252
+
2253
+ See Also
2254
+ ========
2255
+ sympy.utilities.iterables.partitions
2256
+ sympy.utilities.iterables.multiset_partitions
2257
+ sympy.functions.combinatorial.numbers.partition
2258
+
2259
+ References
2260
+ ==========
2261
+
2262
+ .. [1] https://web.archive.org/web/20210507012732/https://teaching.csse.uwa.edu.au/units/CITS7209/partition.pdf
2263
+
2264
+ """
2265
+
2266
+ if isinstance(n, SYMPY_INTS):
2267
+ # n identical items
2268
+ if k is None:
2269
+ return partition(n)
2270
+ if isinstance(k, SYMPY_INTS):
2271
+ n = as_int(n)
2272
+ k = as_int(k)
2273
+ return Integer(_nT(n, k))
2274
+ if not isinstance(n, _MultisetHistogram):
2275
+ try:
2276
+ # if n contains hashable items there is some
2277
+ # quick handling that can be done
2278
+ u = len(set(n))
2279
+ if u <= 1:
2280
+ return nT(len(n), k)
2281
+ elif u == len(n):
2282
+ n = range(u)
2283
+ raise TypeError
2284
+ except TypeError:
2285
+ n = _multiset_histogram(n)
2286
+ N = n[_N]
2287
+ if k is None and N == 1:
2288
+ return 1
2289
+ if k in (1, N):
2290
+ return 1
2291
+ if k == 2 or N == 2 and k is None:
2292
+ m, r = divmod(N, 2)
2293
+ rv = sum(nC(n, i) for i in range(1, m + 1))
2294
+ if not r:
2295
+ rv -= nC(n, m)//2
2296
+ if k is None:
2297
+ rv += 1 # for k == 1
2298
+ return rv
2299
+ if N == n[_ITEMS]:
2300
+ # all distinct
2301
+ if k is None:
2302
+ return bell(N)
2303
+ return stirling(N, k)
2304
+ m = MultisetPartitionTraverser()
2305
+ if k is None:
2306
+ return m.count_partitions(n[_M])
2307
+ # MultisetPartitionTraverser does not have a range-limited count
2308
+ # method, so need to enumerate and count
2309
+ tot = 0
2310
+ for discard in m.enum_range(n[_M], k-1, k):
2311
+ tot += 1
2312
+ return tot
2313
+
2314
+
2315
+ #-----------------------------------------------------------------------------#
2316
+ # #
2317
+ # Motzkin numbers #
2318
+ # #
2319
+ #-----------------------------------------------------------------------------#
2320
+
2321
+
2322
+ class motzkin(Function):
2323
+ """
2324
+ The nth Motzkin number is the number
2325
+ of ways of drawing non-intersecting chords
2326
+ between n points on a circle (not necessarily touching
2327
+ every point by a chord). The Motzkin numbers are named
2328
+ after Theodore Motzkin and have diverse applications
2329
+ in geometry, combinatorics and number theory.
2330
+
2331
+ Motzkin numbers are the integer sequence defined by the
2332
+ initial terms `M_0 = 1`, `M_1 = 1` and the two-term recurrence relation
2333
+ `M_n = \frac{2*n + 1}{n + 2} * M_{n-1} + \frac{3n - 3}{n + 2} * M_{n-2}`.
2334
+
2335
+
2336
+ Examples
2337
+ ========
2338
+
2339
+ >>> from sympy import motzkin
2340
+
2341
+ >>> motzkin.is_motzkin(5)
2342
+ False
2343
+ >>> motzkin.find_motzkin_numbers_in_range(2,300)
2344
+ [2, 4, 9, 21, 51, 127]
2345
+ >>> motzkin.find_motzkin_numbers_in_range(2,900)
2346
+ [2, 4, 9, 21, 51, 127, 323, 835]
2347
+ >>> motzkin.find_first_n_motzkins(10)
2348
+ [1, 1, 2, 4, 9, 21, 51, 127, 323, 835]
2349
+
2350
+
2351
+ References
2352
+ ==========
2353
+
2354
+ .. [1] https://en.wikipedia.org/wiki/Motzkin_number
2355
+ .. [2] https://mathworld.wolfram.com/MotzkinNumber.html
2356
+
2357
+ """
2358
+
2359
+ @staticmethod
2360
+ def is_motzkin(n):
2361
+ try:
2362
+ n = as_int(n)
2363
+ except ValueError:
2364
+ return False
2365
+ if n > 0:
2366
+ if n in (1, 2):
2367
+ return True
2368
+
2369
+ tn1 = 1
2370
+ tn = 2
2371
+ i = 3
2372
+ while tn < n:
2373
+ a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
2374
+ i += 1
2375
+ tn1 = tn
2376
+ tn = a
2377
+
2378
+ if tn == n:
2379
+ return True
2380
+ else:
2381
+ return False
2382
+
2383
+ else:
2384
+ return False
2385
+
2386
+ @staticmethod
2387
+ def find_motzkin_numbers_in_range(x, y):
2388
+ if 0 <= x <= y:
2389
+ motzkins = []
2390
+ if x <= 1 <= y:
2391
+ motzkins.append(1)
2392
+ tn1 = 1
2393
+ tn = 2
2394
+ i = 3
2395
+ while tn <= y:
2396
+ if tn >= x:
2397
+ motzkins.append(tn)
2398
+ a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
2399
+ i += 1
2400
+ tn1 = tn
2401
+ tn = int(a)
2402
+
2403
+ return motzkins
2404
+
2405
+ else:
2406
+ raise ValueError('The provided range is not valid. This condition should satisfy x <= y')
2407
+
2408
+ @staticmethod
2409
+ def find_first_n_motzkins(n):
2410
+ try:
2411
+ n = as_int(n)
2412
+ except ValueError:
2413
+ raise ValueError('The provided number must be a positive integer')
2414
+ if n < 0:
2415
+ raise ValueError('The provided number must be a positive integer')
2416
+ motzkins = [1]
2417
+ if n >= 1:
2418
+ motzkins.append(1)
2419
+ tn1 = 1
2420
+ tn = 2
2421
+ i = 3
2422
+ while i <= n:
2423
+ motzkins.append(tn)
2424
+ a = ((2*i + 1)*tn + (3*i - 3)*tn1)/(i + 2)
2425
+ i += 1
2426
+ tn1 = tn
2427
+ tn = int(a)
2428
+
2429
+ return motzkins
2430
+
2431
+ @staticmethod
2432
+ @recurrence_memo([S.One, S.One])
2433
+ def _motzkin(n, prev):
2434
+ return ((2*n + 1)*prev[-1] + (3*n - 3)*prev[-2]) // (n + 2)
2435
+
2436
+ @classmethod
2437
+ def eval(cls, n):
2438
+ try:
2439
+ n = as_int(n)
2440
+ except ValueError:
2441
+ raise ValueError('The provided number must be a positive integer')
2442
+ if n < 0:
2443
+ raise ValueError('The provided number must be a positive integer')
2444
+ return Integer(cls._motzkin(n - 1))
2445
+
2446
+
2447
+ def nD(i=None, brute=None, *, n=None, m=None):
2448
+ """return the number of derangements for: ``n`` unique items, ``i``
2449
+ items (as a sequence or multiset), or multiplicities, ``m`` given
2450
+ as a sequence or multiset.
2451
+
2452
+ Examples
2453
+ ========
2454
+
2455
+ >>> from sympy.utilities.iterables import generate_derangements as enum
2456
+ >>> from sympy.functions.combinatorial.numbers import nD
2457
+
2458
+ A derangement ``d`` of sequence ``s`` has all ``d[i] != s[i]``:
2459
+
2460
+ >>> set([''.join(i) for i in enum('abc')])
2461
+ {'bca', 'cab'}
2462
+ >>> nD('abc')
2463
+ 2
2464
+
2465
+ Input as iterable or dictionary (multiset form) is accepted:
2466
+
2467
+ >>> assert nD([1, 2, 2, 3, 3, 3]) == nD({1: 1, 2: 2, 3: 3})
2468
+
2469
+ By default, a brute-force enumeration and count of multiset permutations
2470
+ is only done if there are fewer than 9 elements. There may be cases when
2471
+ there is high multiplicity with few unique elements that will benefit
2472
+ from a brute-force enumeration, too. For this reason, the `brute`
2473
+ keyword (default None) is provided. When False, the brute-force
2474
+ enumeration will never be used. When True, it will always be used.
2475
+
2476
+ >>> nD('1111222233', brute=True)
2477
+ 44
2478
+
2479
+ For convenience, one may specify ``n`` distinct items using the
2480
+ ``n`` keyword:
2481
+
2482
+ >>> assert nD(n=3) == nD('abc') == 2
2483
+
2484
+ Since the number of derangments depends on the multiplicity of the
2485
+ elements and not the elements themselves, it may be more convenient
2486
+ to give a list or multiset of multiplicities using keyword ``m``:
2487
+
2488
+ >>> assert nD('abc') == nD(m=(1,1,1)) == nD(m={1:3}) == 2
2489
+
2490
+ """
2491
+ from sympy.integrals.integrals import integrate
2492
+ from sympy.functions.special.polynomials import laguerre
2493
+ from sympy.abc import x
2494
+ def ok(x):
2495
+ if not isinstance(x, SYMPY_INTS):
2496
+ raise TypeError('expecting integer values')
2497
+ if x < 0:
2498
+ raise ValueError('value must not be negative')
2499
+ return True
2500
+
2501
+ if (i, n, m).count(None) != 2:
2502
+ raise ValueError('enter only 1 of i, n, or m')
2503
+ if i is not None:
2504
+ if isinstance(i, SYMPY_INTS):
2505
+ raise TypeError('items must be a list or dictionary')
2506
+ if not i:
2507
+ return S.Zero
2508
+ if type(i) is not dict:
2509
+ s = list(i)
2510
+ ms = multiset(s)
2511
+ elif type(i) is dict:
2512
+ all(ok(_) for _ in i.values())
2513
+ ms = {k: v for k, v in i.items() if v}
2514
+ s = None
2515
+ if not ms:
2516
+ return S.Zero
2517
+ N = sum(ms.values())
2518
+ counts = multiset(ms.values())
2519
+ nkey = len(ms)
2520
+ elif n is not None:
2521
+ ok(n)
2522
+ if not n:
2523
+ return S.Zero
2524
+ return subfactorial(n)
2525
+ elif m is not None:
2526
+ if isinstance(m, dict):
2527
+ all(ok(i) and ok(j) for i, j in m.items())
2528
+ counts = {k: v for k, v in m.items() if k*v}
2529
+ elif iterable(m) or isinstance(m, str):
2530
+ m = list(m)
2531
+ all(ok(i) for i in m)
2532
+ counts = multiset([i for i in m if i])
2533
+ else:
2534
+ raise TypeError('expecting iterable')
2535
+ if not counts:
2536
+ return S.Zero
2537
+ N = sum(k*v for k, v in counts.items())
2538
+ nkey = sum(counts.values())
2539
+ s = None
2540
+ big = int(max(counts))
2541
+ if big == 1: # no repetition
2542
+ return subfactorial(nkey)
2543
+ nval = len(counts)
2544
+ if big*2 > N:
2545
+ return S.Zero
2546
+ if big*2 == N:
2547
+ if nkey == 2 and nval == 1:
2548
+ return S.One # aaabbb
2549
+ if nkey - 1 == big: # one element repeated
2550
+ return factorial(big) # e.g. abc part of abcddd
2551
+ if N < 9 and brute is None or brute:
2552
+ # for all possibilities, this was found to be faster
2553
+ if s is None:
2554
+ s = []
2555
+ i = 0
2556
+ for m, v in counts.items():
2557
+ for j in range(v):
2558
+ s.extend([i]*m)
2559
+ i += 1
2560
+ return Integer(sum(1 for i in multiset_derangements(s)))
2561
+ from sympy.functions.elementary.exponential import exp
2562
+ return Integer(abs(integrate(exp(-x)*Mul(*[
2563
+ laguerre(i, x)**m for i, m in counts.items()]), (x, 0, oo))))
llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (208 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_factorials.cpython-310.pyc ADDED
Binary file (22 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_numbers.cpython-310.pyc ADDED
Binary file (35.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/test_comb_factorials.py ADDED
@@ -0,0 +1,650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.products import Product
2
+ from sympy.core.function import expand_func
3
+ from sympy.core.mod import Mod
4
+ from sympy.core.mul import Mul
5
+ from sympy.core import EulerGamma
6
+ from sympy.core.numbers import (Float, I, Rational, nan, oo, pi, zoo)
7
+ from sympy.core.relational import Eq
8
+ from sympy.core.singleton import S
9
+ from sympy.core.symbol import (Dummy, Symbol, symbols)
10
+ from sympy.functions.combinatorial.factorials import (ff, rf, binomial, factorial, factorial2)
11
+ from sympy.functions.elementary.miscellaneous import sqrt
12
+ from sympy.functions.elementary.piecewise import Piecewise
13
+ from sympy.functions.special.gamma_functions import (gamma, polygamma)
14
+ from sympy.polys.polytools import Poly
15
+ from sympy.series.order import O
16
+ from sympy.simplify.simplify import simplify
17
+ from sympy.core.expr import unchanged
18
+ from sympy.core.function import ArgumentIndexError
19
+ from sympy.functions.combinatorial.factorials import subfactorial
20
+ from sympy.functions.special.gamma_functions import uppergamma
21
+ from sympy.testing.pytest import XFAIL, raises, slow
22
+
23
+ #Solves and Fixes Issue #10388 - This is the updated test for the same solved issue
24
+
25
+ def test_rf_eval_apply():
26
+ x, y = symbols('x,y')
27
+ n, k = symbols('n k', integer=True)
28
+ m = Symbol('m', integer=True, nonnegative=True)
29
+
30
+ assert rf(nan, y) is nan
31
+ assert rf(x, nan) is nan
32
+
33
+ assert unchanged(rf, x, y)
34
+
35
+ assert rf(oo, 0) == 1
36
+ assert rf(-oo, 0) == 1
37
+
38
+ assert rf(oo, 6) is oo
39
+ assert rf(-oo, 7) is -oo
40
+ assert rf(-oo, 6) is oo
41
+
42
+ assert rf(oo, -6) is oo
43
+ assert rf(-oo, -7) is oo
44
+
45
+ assert rf(-1, pi) == 0
46
+ assert rf(-5, 1 + I) == 0
47
+
48
+ assert unchanged(rf, -3, k)
49
+ assert unchanged(rf, x, Symbol('k', integer=False))
50
+ assert rf(-3, Symbol('k', integer=False)) == 0
51
+ assert rf(Symbol('x', negative=True, integer=True), Symbol('k', integer=False)) == 0
52
+
53
+ assert rf(x, 0) == 1
54
+ assert rf(x, 1) == x
55
+ assert rf(x, 2) == x*(x + 1)
56
+ assert rf(x, 3) == x*(x + 1)*(x + 2)
57
+ assert rf(x, 5) == x*(x + 1)*(x + 2)*(x + 3)*(x + 4)
58
+
59
+ assert rf(x, -1) == 1/(x - 1)
60
+ assert rf(x, -2) == 1/((x - 1)*(x - 2))
61
+ assert rf(x, -3) == 1/((x - 1)*(x - 2)*(x - 3))
62
+
63
+ assert rf(1, 100) == factorial(100)
64
+
65
+ assert rf(x**2 + 3*x, 2) == (x**2 + 3*x)*(x**2 + 3*x + 1)
66
+ assert isinstance(rf(x**2 + 3*x, 2), Mul)
67
+ assert rf(x**3 + x, -2) == 1/((x**3 + x - 1)*(x**3 + x - 2))
68
+
69
+ assert rf(Poly(x**2 + 3*x, x), 2) == Poly(x**4 + 8*x**3 + 19*x**2 + 12*x, x)
70
+ assert isinstance(rf(Poly(x**2 + 3*x, x), 2), Poly)
71
+ raises(ValueError, lambda: rf(Poly(x**2 + 3*x, x, y), 2))
72
+ assert rf(Poly(x**3 + x, x), -2) == 1/(x**6 - 9*x**5 + 35*x**4 - 75*x**3 + 94*x**2 - 66*x + 20)
73
+ raises(ValueError, lambda: rf(Poly(x**3 + x, x, y), -2))
74
+
75
+ assert rf(x, m).is_integer is None
76
+ assert rf(n, k).is_integer is None
77
+ assert rf(n, m).is_integer is True
78
+ assert rf(n, k + pi).is_integer is False
79
+ assert rf(n, m + pi).is_integer is False
80
+ assert rf(pi, m).is_integer is False
81
+
82
+ def check(x, k, o, n):
83
+ a, b = Dummy(), Dummy()
84
+ r = lambda x, k: o(a, b).rewrite(n).subs({a:x,b:k})
85
+ for i in range(-5,5):
86
+ for j in range(-5,5):
87
+ assert o(i, j) == r(i, j), (o, n, i, j)
88
+ check(x, k, rf, ff)
89
+ check(x, k, rf, binomial)
90
+ check(n, k, rf, factorial)
91
+ check(x, y, rf, factorial)
92
+ check(x, y, rf, binomial)
93
+
94
+ assert rf(x, k).rewrite(ff) == ff(x + k - 1, k)
95
+ assert rf(x, k).rewrite(gamma) == Piecewise(
96
+ (gamma(k + x)/gamma(x), x > 0),
97
+ ((-1)**k*gamma(1 - x)/gamma(-k - x + 1), True))
98
+ assert rf(5, k).rewrite(gamma) == gamma(k + 5)/24
99
+ assert rf(x, k).rewrite(binomial) == factorial(k)*binomial(x + k - 1, k)
100
+ assert rf(n, k).rewrite(factorial) == Piecewise(
101
+ (factorial(k + n - 1)/factorial(n - 1), n > 0),
102
+ ((-1)**k*factorial(-n)/factorial(-k - n), True))
103
+ assert rf(5, k).rewrite(factorial) == factorial(k + 4)/24
104
+ assert rf(x, y).rewrite(factorial) == rf(x, y)
105
+ assert rf(x, y).rewrite(binomial) == rf(x, y)
106
+
107
+ import random
108
+ from mpmath import rf as mpmath_rf
109
+ for i in range(100):
110
+ x = -500 + 500 * random.random()
111
+ k = -500 + 500 * random.random()
112
+ assert (abs(mpmath_rf(x, k) - rf(x, k)) < 10**(-15))
113
+
114
+
115
+ def test_ff_eval_apply():
116
+ x, y = symbols('x,y')
117
+ n, k = symbols('n k', integer=True)
118
+ m = Symbol('m', integer=True, nonnegative=True)
119
+
120
+ assert ff(nan, y) is nan
121
+ assert ff(x, nan) is nan
122
+
123
+ assert unchanged(ff, x, y)
124
+
125
+ assert ff(oo, 0) == 1
126
+ assert ff(-oo, 0) == 1
127
+
128
+ assert ff(oo, 6) is oo
129
+ assert ff(-oo, 7) is -oo
130
+ assert ff(-oo, 6) is oo
131
+
132
+ assert ff(oo, -6) is oo
133
+ assert ff(-oo, -7) is oo
134
+
135
+ assert ff(x, 0) == 1
136
+ assert ff(x, 1) == x
137
+ assert ff(x, 2) == x*(x - 1)
138
+ assert ff(x, 3) == x*(x - 1)*(x - 2)
139
+ assert ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4)
140
+
141
+ assert ff(x, -1) == 1/(x + 1)
142
+ assert ff(x, -2) == 1/((x + 1)*(x + 2))
143
+ assert ff(x, -3) == 1/((x + 1)*(x + 2)*(x + 3))
144
+
145
+ assert ff(100, 100) == factorial(100)
146
+
147
+ assert ff(2*x**2 - 5*x, 2) == (2*x**2 - 5*x)*(2*x**2 - 5*x - 1)
148
+ assert isinstance(ff(2*x**2 - 5*x, 2), Mul)
149
+ assert ff(x**2 + 3*x, -2) == 1/((x**2 + 3*x + 1)*(x**2 + 3*x + 2))
150
+
151
+ assert ff(Poly(2*x**2 - 5*x, x), 2) == Poly(4*x**4 - 28*x**3 + 59*x**2 - 35*x, x)
152
+ assert isinstance(ff(Poly(2*x**2 - 5*x, x), 2), Poly)
153
+ raises(ValueError, lambda: ff(Poly(2*x**2 - 5*x, x, y), 2))
154
+ assert ff(Poly(x**2 + 3*x, x), -2) == 1/(x**4 + 12*x**3 + 49*x**2 + 78*x + 40)
155
+ raises(ValueError, lambda: ff(Poly(x**2 + 3*x, x, y), -2))
156
+
157
+
158
+ assert ff(x, m).is_integer is None
159
+ assert ff(n, k).is_integer is None
160
+ assert ff(n, m).is_integer is True
161
+ assert ff(n, k + pi).is_integer is False
162
+ assert ff(n, m + pi).is_integer is False
163
+ assert ff(pi, m).is_integer is False
164
+
165
+ assert isinstance(ff(x, x), ff)
166
+ assert ff(n, n) == factorial(n)
167
+
168
+ def check(x, k, o, n):
169
+ a, b = Dummy(), Dummy()
170
+ r = lambda x, k: o(a, b).rewrite(n).subs({a:x,b:k})
171
+ for i in range(-5,5):
172
+ for j in range(-5,5):
173
+ assert o(i, j) == r(i, j), (o, n)
174
+ check(x, k, ff, rf)
175
+ check(x, k, ff, gamma)
176
+ check(n, k, ff, factorial)
177
+ check(x, k, ff, binomial)
178
+ check(x, y, ff, factorial)
179
+ check(x, y, ff, binomial)
180
+
181
+ assert ff(x, k).rewrite(rf) == rf(x - k + 1, k)
182
+ assert ff(x, k).rewrite(gamma) == Piecewise(
183
+ (gamma(x + 1)/gamma(-k + x + 1), x >= 0),
184
+ ((-1)**k*gamma(k - x)/gamma(-x), True))
185
+ assert ff(5, k).rewrite(gamma) == 120/gamma(6 - k)
186
+ assert ff(n, k).rewrite(factorial) == Piecewise(
187
+ (factorial(n)/factorial(-k + n), n >= 0),
188
+ ((-1)**k*factorial(k - n - 1)/factorial(-n - 1), True))
189
+ assert ff(5, k).rewrite(factorial) == 120/factorial(5 - k)
190
+ assert ff(x, k).rewrite(binomial) == factorial(k) * binomial(x, k)
191
+ assert ff(x, y).rewrite(factorial) == ff(x, y)
192
+ assert ff(x, y).rewrite(binomial) == ff(x, y)
193
+
194
+ import random
195
+ from mpmath import ff as mpmath_ff
196
+ for i in range(100):
197
+ x = -500 + 500 * random.random()
198
+ k = -500 + 500 * random.random()
199
+ a = mpmath_ff(x, k)
200
+ b = ff(x, k)
201
+ assert (abs(a - b) < abs(a) * 10**(-15))
202
+
203
+
204
+ def test_rf_ff_eval_hiprec():
205
+ maple = Float('6.9109401292234329956525265438452')
206
+ us = ff(18, Rational(2, 3)).evalf(32)
207
+ assert abs(us - maple)/us < 1e-31
208
+
209
+ maple = Float('6.8261540131125511557924466355367')
210
+ us = rf(18, Rational(2, 3)).evalf(32)
211
+ assert abs(us - maple)/us < 1e-31
212
+
213
+ maple = Float('34.007346127440197150854651814225')
214
+ us = rf(Float('4.4', 32), Float('2.2', 32));
215
+ assert abs(us - maple)/us < 1e-31
216
+
217
+
218
+ def test_rf_lambdify_mpmath():
219
+ from sympy.utilities.lambdify import lambdify
220
+ x, y = symbols('x,y')
221
+ f = lambdify((x,y), rf(x, y), 'mpmath')
222
+ maple = Float('34.007346127440197')
223
+ us = f(4.4, 2.2)
224
+ assert abs(us - maple)/us < 1e-15
225
+
226
+
227
+ def test_factorial():
228
+ x = Symbol('x')
229
+ n = Symbol('n', integer=True)
230
+ k = Symbol('k', integer=True, nonnegative=True)
231
+ r = Symbol('r', integer=False)
232
+ s = Symbol('s', integer=False, negative=True)
233
+ t = Symbol('t', nonnegative=True)
234
+ u = Symbol('u', noninteger=True)
235
+
236
+ assert factorial(-2) is zoo
237
+ assert factorial(0) == 1
238
+ assert factorial(7) == 5040
239
+ assert factorial(19) == 121645100408832000
240
+ assert factorial(31) == 8222838654177922817725562880000000
241
+ assert factorial(n).func == factorial
242
+ assert factorial(2*n).func == factorial
243
+
244
+ assert factorial(x).is_integer is None
245
+ assert factorial(n).is_integer is None
246
+ assert factorial(k).is_integer
247
+ assert factorial(r).is_integer is None
248
+
249
+ assert factorial(n).is_positive is None
250
+ assert factorial(k).is_positive
251
+
252
+ assert factorial(x).is_real is None
253
+ assert factorial(n).is_real is None
254
+ assert factorial(k).is_real is True
255
+ assert factorial(r).is_real is None
256
+ assert factorial(s).is_real is True
257
+ assert factorial(t).is_real is True
258
+ assert factorial(u).is_real is True
259
+
260
+ assert factorial(x).is_composite is None
261
+ assert factorial(n).is_composite is None
262
+ assert factorial(k).is_composite is None
263
+ assert factorial(k + 3).is_composite is True
264
+ assert factorial(r).is_composite is None
265
+ assert factorial(s).is_composite is None
266
+ assert factorial(t).is_composite is None
267
+ assert factorial(u).is_composite is None
268
+
269
+ assert factorial(oo) is oo
270
+
271
+
272
+ def test_factorial_Mod():
273
+ pr = Symbol('pr', prime=True)
274
+ p, q = 10**9 + 9, 10**9 + 33 # prime modulo
275
+ r, s = 10**7 + 5, 33333333 # composite modulo
276
+ assert Mod(factorial(pr - 1), pr) == pr - 1
277
+ assert Mod(factorial(pr - 1), -pr) == -1
278
+ assert Mod(factorial(r - 1, evaluate=False), r) == 0
279
+ assert Mod(factorial(s - 1, evaluate=False), s) == 0
280
+ assert Mod(factorial(p - 1, evaluate=False), p) == p - 1
281
+ assert Mod(factorial(q - 1, evaluate=False), q) == q - 1
282
+ assert Mod(factorial(p - 50, evaluate=False), p) == 854928834
283
+ assert Mod(factorial(q - 1800, evaluate=False), q) == 905504050
284
+ assert Mod(factorial(153, evaluate=False), r) == Mod(factorial(153), r)
285
+ assert Mod(factorial(255, evaluate=False), s) == Mod(factorial(255), s)
286
+ assert Mod(factorial(4, evaluate=False), 3) == S.Zero
287
+ assert Mod(factorial(5, evaluate=False), 6) == S.Zero
288
+
289
+
290
+ def test_factorial_diff():
291
+ n = Symbol('n', integer=True)
292
+
293
+ assert factorial(n).diff(n) == \
294
+ gamma(1 + n)*polygamma(0, 1 + n)
295
+ assert factorial(n**2).diff(n) == \
296
+ 2*n*gamma(1 + n**2)*polygamma(0, 1 + n**2)
297
+ raises(ArgumentIndexError, lambda: factorial(n**2).fdiff(2))
298
+
299
+
300
+ def test_factorial_series():
301
+ n = Symbol('n', integer=True)
302
+
303
+ assert factorial(n).series(n, 0, 3) == \
304
+ 1 - n*EulerGamma + n**2*(EulerGamma**2/2 + pi**2/12) + O(n**3)
305
+
306
+
307
+ def test_factorial_rewrite():
308
+ n = Symbol('n', integer=True)
309
+ k = Symbol('k', integer=True, nonnegative=True)
310
+
311
+ assert factorial(n).rewrite(gamma) == gamma(n + 1)
312
+ _i = Dummy('i')
313
+ assert factorial(k).rewrite(Product).dummy_eq(Product(_i, (_i, 1, k)))
314
+ assert factorial(n).rewrite(Product) == factorial(n)
315
+
316
+
317
+ def test_factorial2():
318
+ n = Symbol('n', integer=True)
319
+
320
+ assert factorial2(-1) == 1
321
+ assert factorial2(0) == 1
322
+ assert factorial2(7) == 105
323
+ assert factorial2(8) == 384
324
+
325
+ # The following is exhaustive
326
+ tt = Symbol('tt', integer=True, nonnegative=True)
327
+ tte = Symbol('tte', even=True, nonnegative=True)
328
+ tpe = Symbol('tpe', even=True, positive=True)
329
+ tto = Symbol('tto', odd=True, nonnegative=True)
330
+ tf = Symbol('tf', integer=True, nonnegative=False)
331
+ tfe = Symbol('tfe', even=True, nonnegative=False)
332
+ tfo = Symbol('tfo', odd=True, nonnegative=False)
333
+ ft = Symbol('ft', integer=False, nonnegative=True)
334
+ ff = Symbol('ff', integer=False, nonnegative=False)
335
+ fn = Symbol('fn', integer=False)
336
+ nt = Symbol('nt', nonnegative=True)
337
+ nf = Symbol('nf', nonnegative=False)
338
+ nn = Symbol('nn')
339
+ z = Symbol('z', zero=True)
340
+ #Solves and Fixes Issue #10388 - This is the updated test for the same solved issue
341
+ raises(ValueError, lambda: factorial2(oo))
342
+ raises(ValueError, lambda: factorial2(Rational(5, 2)))
343
+ raises(ValueError, lambda: factorial2(-4))
344
+ assert factorial2(n).is_integer is None
345
+ assert factorial2(tt - 1).is_integer
346
+ assert factorial2(tte - 1).is_integer
347
+ assert factorial2(tpe - 3).is_integer
348
+ assert factorial2(tto - 4).is_integer
349
+ assert factorial2(tto - 2).is_integer
350
+ assert factorial2(tf).is_integer is None
351
+ assert factorial2(tfe).is_integer is None
352
+ assert factorial2(tfo).is_integer is None
353
+ assert factorial2(ft).is_integer is None
354
+ assert factorial2(ff).is_integer is None
355
+ assert factorial2(fn).is_integer is None
356
+ assert factorial2(nt).is_integer is None
357
+ assert factorial2(nf).is_integer is None
358
+ assert factorial2(nn).is_integer is None
359
+
360
+ assert factorial2(n).is_positive is None
361
+ assert factorial2(tt - 1).is_positive is True
362
+ assert factorial2(tte - 1).is_positive is True
363
+ assert factorial2(tpe - 3).is_positive is True
364
+ assert factorial2(tpe - 1).is_positive is True
365
+ assert factorial2(tto - 2).is_positive is True
366
+ assert factorial2(tto - 1).is_positive is True
367
+ assert factorial2(tf).is_positive is None
368
+ assert factorial2(tfe).is_positive is None
369
+ assert factorial2(tfo).is_positive is None
370
+ assert factorial2(ft).is_positive is None
371
+ assert factorial2(ff).is_positive is None
372
+ assert factorial2(fn).is_positive is None
373
+ assert factorial2(nt).is_positive is None
374
+ assert factorial2(nf).is_positive is None
375
+ assert factorial2(nn).is_positive is None
376
+
377
+ assert factorial2(tt).is_even is None
378
+ assert factorial2(tt).is_odd is None
379
+ assert factorial2(tte).is_even is None
380
+ assert factorial2(tte).is_odd is None
381
+ assert factorial2(tte + 2).is_even is True
382
+ assert factorial2(tpe).is_even is True
383
+ assert factorial2(tpe).is_odd is False
384
+ assert factorial2(tto).is_odd is True
385
+ assert factorial2(tf).is_even is None
386
+ assert factorial2(tf).is_odd is None
387
+ assert factorial2(tfe).is_even is None
388
+ assert factorial2(tfe).is_odd is None
389
+ assert factorial2(tfo).is_even is False
390
+ assert factorial2(tfo).is_odd is None
391
+ assert factorial2(z).is_even is False
392
+ assert factorial2(z).is_odd is True
393
+
394
+
395
+ def test_factorial2_rewrite():
396
+ n = Symbol('n', integer=True)
397
+ assert factorial2(n).rewrite(gamma) == \
398
+ 2**(n/2)*Piecewise((1, Eq(Mod(n, 2), 0)), (sqrt(2)/sqrt(pi), Eq(Mod(n, 2), 1)))*gamma(n/2 + 1)
399
+ assert factorial2(2*n).rewrite(gamma) == 2**n*gamma(n + 1)
400
+ assert factorial2(2*n + 1).rewrite(gamma) == \
401
+ sqrt(2)*2**(n + S.Half)*gamma(n + Rational(3, 2))/sqrt(pi)
402
+
403
+
404
+ def test_binomial():
405
+ x = Symbol('x')
406
+ n = Symbol('n', integer=True)
407
+ nz = Symbol('nz', integer=True, nonzero=True)
408
+ k = Symbol('k', integer=True)
409
+ kp = Symbol('kp', integer=True, positive=True)
410
+ kn = Symbol('kn', integer=True, negative=True)
411
+ u = Symbol('u', negative=True)
412
+ v = Symbol('v', nonnegative=True)
413
+ p = Symbol('p', positive=True)
414
+ z = Symbol('z', zero=True)
415
+ nt = Symbol('nt', integer=False)
416
+ kt = Symbol('kt', integer=False)
417
+ a = Symbol('a', integer=True, nonnegative=True)
418
+ b = Symbol('b', integer=True, nonnegative=True)
419
+
420
+ assert binomial(0, 0) == 1
421
+ assert binomial(1, 1) == 1
422
+ assert binomial(10, 10) == 1
423
+ assert binomial(n, z) == 1
424
+ assert binomial(1, 2) == 0
425
+ assert binomial(-1, 2) == 1
426
+ assert binomial(1, -1) == 0
427
+ assert binomial(-1, 1) == -1
428
+ assert binomial(-1, -1) == 0
429
+ assert binomial(S.Half, S.Half) == 1
430
+ assert binomial(-10, 1) == -10
431
+ assert binomial(-10, 7) == -11440
432
+ assert binomial(n, -1) == 0 # holds for all integers (negative, zero, positive)
433
+ assert binomial(kp, -1) == 0
434
+ assert binomial(nz, 0) == 1
435
+ assert expand_func(binomial(n, 1)) == n
436
+ assert expand_func(binomial(n, 2)) == n*(n - 1)/2
437
+ assert expand_func(binomial(n, n - 2)) == n*(n - 1)/2
438
+ assert expand_func(binomial(n, n - 1)) == n
439
+ assert binomial(n, 3).func == binomial
440
+ assert binomial(n, 3).expand(func=True) == n**3/6 - n**2/2 + n/3
441
+ assert expand_func(binomial(n, 3)) == n*(n - 2)*(n - 1)/6
442
+ assert binomial(n, n).func == binomial # e.g. (-1, -1) == 0, (2, 2) == 1
443
+ assert binomial(n, n + 1).func == binomial # e.g. (-1, 0) == 1
444
+ assert binomial(kp, kp + 1) == 0
445
+ assert binomial(kn, kn) == 0 # issue #14529
446
+ assert binomial(n, u).func == binomial
447
+ assert binomial(kp, u).func == binomial
448
+ assert binomial(n, p).func == binomial
449
+ assert binomial(n, k).func == binomial
450
+ assert binomial(n, n + p).func == binomial
451
+ assert binomial(kp, kp + p).func == binomial
452
+
453
+ assert expand_func(binomial(n, n - 3)) == n*(n - 2)*(n - 1)/6
454
+
455
+ assert binomial(n, k).is_integer
456
+ assert binomial(nt, k).is_integer is None
457
+ assert binomial(x, nt).is_integer is False
458
+
459
+ assert binomial(gamma(25), 6) == 79232165267303928292058750056084441948572511312165380965440075720159859792344339983120618959044048198214221915637090855535036339620413440000
460
+ assert binomial(1324, 47) == 906266255662694632984994480774946083064699457235920708992926525848438478406790323869952
461
+ assert binomial(1735, 43) == 190910140420204130794758005450919715396159959034348676124678207874195064798202216379800
462
+ assert binomial(2512, 53) == 213894469313832631145798303740098720367984955243020898718979538096223399813295457822575338958939834177325304000
463
+ assert binomial(3383, 52) == 27922807788818096863529701501764372757272890613101645521813434902890007725667814813832027795881839396839287659777235
464
+ assert binomial(4321, 51) == 124595639629264868916081001263541480185227731958274383287107643816863897851139048158022599533438936036467601690983780576
465
+
466
+ assert binomial(a, b).is_nonnegative is True
467
+ assert binomial(-1, 2, evaluate=False).is_nonnegative is True
468
+ assert binomial(10, 5, evaluate=False).is_nonnegative is True
469
+ assert binomial(10, -3, evaluate=False).is_nonnegative is True
470
+ assert binomial(-10, -3, evaluate=False).is_nonnegative is True
471
+ assert binomial(-10, 2, evaluate=False).is_nonnegative is True
472
+ assert binomial(-10, 1, evaluate=False).is_nonnegative is False
473
+ assert binomial(-10, 7, evaluate=False).is_nonnegative is False
474
+
475
+ # issue #14625
476
+ for _ in (pi, -pi, nt, v, a):
477
+ assert binomial(_, _) == 1
478
+ assert binomial(_, _ - 1) == _
479
+ assert isinstance(binomial(u, u), binomial)
480
+ assert isinstance(binomial(u, u - 1), binomial)
481
+ assert isinstance(binomial(x, x), binomial)
482
+ assert isinstance(binomial(x, x - 1), binomial)
483
+
484
+ #issue #18802
485
+ assert expand_func(binomial(x + 1, x)) == x + 1
486
+ assert expand_func(binomial(x, x - 1)) == x
487
+ assert expand_func(binomial(x + 1, x - 1)) == x*(x + 1)/2
488
+ assert expand_func(binomial(x**2 + 1, x**2)) == x**2 + 1
489
+
490
+ # issue #13980 and #13981
491
+ assert binomial(-7, -5) == 0
492
+ assert binomial(-23, -12) == 0
493
+ assert binomial(Rational(13, 2), -10) == 0
494
+ assert binomial(-49, -51) == 0
495
+
496
+ assert binomial(19, Rational(-7, 2)) == S(-68719476736)/(911337863661225*pi)
497
+ assert binomial(0, Rational(3, 2)) == S(-2)/(3*pi)
498
+ assert binomial(-3, Rational(-7, 2)) is zoo
499
+ assert binomial(kn, kt) is zoo
500
+
501
+ assert binomial(nt, kt).func == binomial
502
+ assert binomial(nt, Rational(15, 6)) == 8*gamma(nt + 1)/(15*sqrt(pi)*gamma(nt - Rational(3, 2)))
503
+ assert binomial(Rational(20, 3), Rational(-10, 8)) == gamma(Rational(23, 3))/(gamma(Rational(-1, 4))*gamma(Rational(107, 12)))
504
+ assert binomial(Rational(19, 2), Rational(-7, 2)) == Rational(-1615, 8388608)
505
+ assert binomial(Rational(-13, 5), Rational(-7, 8)) == gamma(Rational(-8, 5))/(gamma(Rational(-29, 40))*gamma(Rational(1, 8)))
506
+ assert binomial(Rational(-19, 8), Rational(-13, 5)) == gamma(Rational(-11, 8))/(gamma(Rational(-8, 5))*gamma(Rational(49, 40)))
507
+
508
+ # binomial for complexes
509
+ assert binomial(I, Rational(-89, 8)) == gamma(1 + I)/(gamma(Rational(-81, 8))*gamma(Rational(97, 8) + I))
510
+ assert binomial(I, 2*I) == gamma(1 + I)/(gamma(1 - I)*gamma(1 + 2*I))
511
+ assert binomial(-7, I) is zoo
512
+ assert binomial(Rational(-7, 6), I) == gamma(Rational(-1, 6))/(gamma(Rational(-1, 6) - I)*gamma(1 + I))
513
+ assert binomial((1+2*I), (1+3*I)) == gamma(2 + 2*I)/(gamma(1 - I)*gamma(2 + 3*I))
514
+ assert binomial(I, 5) == Rational(1, 3) - I/S(12)
515
+ assert binomial((2*I + 3), 7) == -13*I/S(63)
516
+ assert isinstance(binomial(I, n), binomial)
517
+ assert expand_func(binomial(3, 2, evaluate=False)) == 3
518
+ assert expand_func(binomial(n, 0, evaluate=False)) == 1
519
+ assert expand_func(binomial(n, -2, evaluate=False)) == 0
520
+ assert expand_func(binomial(n, k)) == binomial(n, k)
521
+
522
+
523
+ def test_binomial_Mod():
524
+ p, q = 10**5 + 3, 10**9 + 33 # prime modulo
525
+ r = 10**7 + 5 # composite modulo
526
+
527
+ # A few tests to get coverage
528
+ # Lucas Theorem
529
+ assert Mod(binomial(156675, 4433, evaluate=False), p) == Mod(binomial(156675, 4433), p)
530
+
531
+ # factorial Mod
532
+ assert Mod(binomial(1234, 432, evaluate=False), q) == Mod(binomial(1234, 432), q)
533
+
534
+ # binomial factorize
535
+ assert Mod(binomial(253, 113, evaluate=False), r) == Mod(binomial(253, 113), r)
536
+
537
+
538
+ @slow
539
+ def test_binomial_Mod_slow():
540
+ p, q = 10**5 + 3, 10**9 + 33 # prime modulo
541
+ r, s = 10**7 + 5, 33333333 # composite modulo
542
+
543
+ n, k, m = symbols('n k m')
544
+ assert (binomial(n, k) % q).subs({n: s, k: p}) == Mod(binomial(s, p), q)
545
+ assert (binomial(n, k) % m).subs({n: 8, k: 5, m: 13}) == 4
546
+ assert (binomial(9, k) % 7).subs(k, 2) == 1
547
+
548
+ # Lucas Theorem
549
+ assert Mod(binomial(123456, 43253, evaluate=False), p) == Mod(binomial(123456, 43253), p)
550
+ assert Mod(binomial(-178911, 237, evaluate=False), p) == Mod(-binomial(178911 + 237 - 1, 237), p)
551
+ assert Mod(binomial(-178911, 238, evaluate=False), p) == Mod(binomial(178911 + 238 - 1, 238), p)
552
+
553
+ # factorial Mod
554
+ assert Mod(binomial(9734, 451, evaluate=False), q) == Mod(binomial(9734, 451), q)
555
+ assert Mod(binomial(-10733, 4459, evaluate=False), q) == Mod(binomial(-10733, 4459), q)
556
+ assert Mod(binomial(-15733, 4458, evaluate=False), q) == Mod(binomial(-15733, 4458), q)
557
+ assert Mod(binomial(23, -38, evaluate=False), q) is S.Zero
558
+ assert Mod(binomial(23, 38, evaluate=False), q) is S.Zero
559
+
560
+ # binomial factorize
561
+ assert Mod(binomial(753, 119, evaluate=False), r) == Mod(binomial(753, 119), r)
562
+ assert Mod(binomial(3781, 948, evaluate=False), s) == Mod(binomial(3781, 948), s)
563
+ assert Mod(binomial(25773, 1793, evaluate=False), s) == Mod(binomial(25773, 1793), s)
564
+ assert Mod(binomial(-753, 118, evaluate=False), r) == Mod(binomial(-753, 118), r)
565
+ assert Mod(binomial(-25773, 1793, evaluate=False), s) == Mod(binomial(-25773, 1793), s)
566
+
567
+
568
+ def test_binomial_diff():
569
+ n = Symbol('n', integer=True)
570
+ k = Symbol('k', integer=True)
571
+
572
+ assert binomial(n, k).diff(n) == \
573
+ (-polygamma(0, 1 + n - k) + polygamma(0, 1 + n))*binomial(n, k)
574
+ assert binomial(n**2, k**3).diff(n) == \
575
+ 2*n*(-polygamma(
576
+ 0, 1 + n**2 - k**3) + polygamma(0, 1 + n**2))*binomial(n**2, k**3)
577
+
578
+ assert binomial(n, k).diff(k) == \
579
+ (-polygamma(0, 1 + k) + polygamma(0, 1 + n - k))*binomial(n, k)
580
+ assert binomial(n**2, k**3).diff(k) == \
581
+ 3*k**2*(-polygamma(
582
+ 0, 1 + k**3) + polygamma(0, 1 + n**2 - k**3))*binomial(n**2, k**3)
583
+ raises(ArgumentIndexError, lambda: binomial(n, k).fdiff(3))
584
+
585
+
586
+ def test_binomial_rewrite():
587
+ n = Symbol('n', integer=True)
588
+ k = Symbol('k', integer=True)
589
+ x = Symbol('x')
590
+
591
+ assert binomial(n, k).rewrite(
592
+ factorial) == factorial(n)/(factorial(k)*factorial(n - k))
593
+ assert binomial(
594
+ n, k).rewrite(gamma) == gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
595
+ assert binomial(n, k).rewrite(ff) == ff(n, k) / factorial(k)
596
+ assert binomial(n, x).rewrite(ff) == binomial(n, x)
597
+
598
+
599
+ @XFAIL
600
+ def test_factorial_simplify_fail():
601
+ # simplify(factorial(x + 1).diff(x) - ((x + 1)*factorial(x)).diff(x))) == 0
602
+ from sympy.abc import x
603
+ assert simplify(x*polygamma(0, x + 1) - x*polygamma(0, x + 2) +
604
+ polygamma(0, x + 1) - polygamma(0, x + 2) + 1) == 0
605
+
606
+
607
+ def test_subfactorial():
608
+ assert all(subfactorial(i) == ans for i, ans in enumerate(
609
+ [1, 0, 1, 2, 9, 44, 265, 1854, 14833, 133496]))
610
+ assert subfactorial(oo) is oo
611
+ assert subfactorial(nan) is nan
612
+ assert subfactorial(23) == 9510425471055777937262
613
+ assert unchanged(subfactorial, 2.2)
614
+
615
+ x = Symbol('x')
616
+ assert subfactorial(x).rewrite(uppergamma) == uppergamma(x + 1, -1)/S.Exp1
617
+
618
+ tt = Symbol('tt', integer=True, nonnegative=True)
619
+ tf = Symbol('tf', integer=True, nonnegative=False)
620
+ tn = Symbol('tf', integer=True)
621
+ ft = Symbol('ft', integer=False, nonnegative=True)
622
+ ff = Symbol('ff', integer=False, nonnegative=False)
623
+ fn = Symbol('ff', integer=False)
624
+ nt = Symbol('nt', nonnegative=True)
625
+ nf = Symbol('nf', nonnegative=False)
626
+ nn = Symbol('nf')
627
+ te = Symbol('te', even=True, nonnegative=True)
628
+ to = Symbol('to', odd=True, nonnegative=True)
629
+ assert subfactorial(tt).is_integer
630
+ assert subfactorial(tf).is_integer is None
631
+ assert subfactorial(tn).is_integer is None
632
+ assert subfactorial(ft).is_integer is None
633
+ assert subfactorial(ff).is_integer is None
634
+ assert subfactorial(fn).is_integer is None
635
+ assert subfactorial(nt).is_integer is None
636
+ assert subfactorial(nf).is_integer is None
637
+ assert subfactorial(nn).is_integer is None
638
+ assert subfactorial(tt).is_nonnegative
639
+ assert subfactorial(tf).is_nonnegative is None
640
+ assert subfactorial(tn).is_nonnegative is None
641
+ assert subfactorial(ft).is_nonnegative is None
642
+ assert subfactorial(ff).is_nonnegative is None
643
+ assert subfactorial(fn).is_nonnegative is None
644
+ assert subfactorial(nt).is_nonnegative is None
645
+ assert subfactorial(nf).is_nonnegative is None
646
+ assert subfactorial(nn).is_nonnegative is None
647
+ assert subfactorial(tt).is_even is None
648
+ assert subfactorial(tt).is_odd is None
649
+ assert subfactorial(te).is_odd is True
650
+ assert subfactorial(to).is_even is True
llmeval-env/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/test_comb_numbers.py ADDED
@@ -0,0 +1,852 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import string
2
+
3
+ from sympy.concrete.products import Product
4
+ from sympy.concrete.summations import Sum
5
+ from sympy.core.function import (diff, expand_func)
6
+ from sympy.core import (EulerGamma, TribonacciConstant)
7
+ from sympy.core.numbers import (Float, I, Rational, oo, pi)
8
+ from sympy.core.singleton import S
9
+ from sympy.core.symbol import (Dummy, Symbol, symbols)
10
+ from sympy.functions.combinatorial.numbers import carmichael
11
+ from sympy.functions.elementary.complexes import (im, re)
12
+ from sympy.functions.elementary.integers import floor
13
+ from sympy.polys.polytools import cancel
14
+ from sympy.series.limits import limit, Limit
15
+ from sympy.series.order import O
16
+ from sympy.functions import (
17
+ bernoulli, harmonic, bell, fibonacci, tribonacci, lucas, euler, catalan,
18
+ genocchi, andre, partition, motzkin, binomial, gamma, sqrt, cbrt, hyper, log, digamma,
19
+ trigamma, polygamma, factorial, sin, cos, cot, polylog, zeta, dirichlet_eta)
20
+ from sympy.functions.combinatorial.numbers import _nT
21
+
22
+ from sympy.core.expr import unchanged
23
+ from sympy.core.numbers import GoldenRatio, Integer
24
+
25
+ from sympy.testing.pytest import raises, nocache_fail, warns_deprecated_sympy
26
+ from sympy.abc import x
27
+
28
+
29
+ def test_carmichael():
30
+ assert carmichael.find_carmichael_numbers_in_range(0, 561) == []
31
+ assert carmichael.find_carmichael_numbers_in_range(561, 562) == [561]
32
+ assert carmichael.find_carmichael_numbers_in_range(561, 1105) == carmichael.find_carmichael_numbers_in_range(561,
33
+ 562)
34
+ assert carmichael.find_first_n_carmichaels(5) == [561, 1105, 1729, 2465, 2821]
35
+ raises(ValueError, lambda: carmichael.is_carmichael(-2))
36
+ raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(-2, 2))
37
+ raises(ValueError, lambda: carmichael.find_carmichael_numbers_in_range(22, 2))
38
+ with warns_deprecated_sympy():
39
+ assert carmichael.is_prime(2821) == False
40
+
41
+
42
+ def test_bernoulli():
43
+ assert bernoulli(0) == 1
44
+ assert bernoulli(1) == Rational(1, 2)
45
+ assert bernoulli(2) == Rational(1, 6)
46
+ assert bernoulli(3) == 0
47
+ assert bernoulli(4) == Rational(-1, 30)
48
+ assert bernoulli(5) == 0
49
+ assert bernoulli(6) == Rational(1, 42)
50
+ assert bernoulli(7) == 0
51
+ assert bernoulli(8) == Rational(-1, 30)
52
+ assert bernoulli(10) == Rational(5, 66)
53
+ assert bernoulli(1000001) == 0
54
+
55
+ assert bernoulli(0, x) == 1
56
+ assert bernoulli(1, x) == x - S.Half
57
+ assert bernoulli(2, x) == x**2 - x + Rational(1, 6)
58
+ assert bernoulli(3, x) == x**3 - (3*x**2)/2 + x/2
59
+
60
+ # Should be fast; computed with mpmath
61
+ b = bernoulli(1000)
62
+ assert b.p % 10**10 == 7950421099
63
+ assert b.q == 342999030
64
+
65
+ b = bernoulli(10**6, evaluate=False).evalf()
66
+ assert str(b) == '-2.23799235765713e+4767529'
67
+
68
+ # Issue #8527
69
+ l = Symbol('l', integer=True)
70
+ m = Symbol('m', integer=True, nonnegative=True)
71
+ n = Symbol('n', integer=True, positive=True)
72
+ assert isinstance(bernoulli(2 * l + 1), bernoulli)
73
+ assert isinstance(bernoulli(2 * m + 1), bernoulli)
74
+ assert bernoulli(2 * n + 1) == 0
75
+
76
+ assert bernoulli(x, 1) == bernoulli(x)
77
+
78
+ assert str(bernoulli(0.0, 2.3).evalf(n=10)) == '1.000000000'
79
+ assert str(bernoulli(1.0).evalf(n=10)) == '0.5000000000'
80
+ assert str(bernoulli(1.2).evalf(n=10)) == '0.4195995367'
81
+ assert str(bernoulli(1.2, 0.8).evalf(n=10)) == '0.2144830348'
82
+ assert str(bernoulli(1.2, -0.8).evalf(n=10)) == '-1.158865646 - 0.6745558744*I'
83
+ assert str(bernoulli(3.0, 1j).evalf(n=10)) == '1.5 - 0.5*I'
84
+ assert str(bernoulli(I).evalf(n=10)) == '0.9268485643 - 0.5821580598*I'
85
+ assert str(bernoulli(I, I).evalf(n=10)) == '0.1267792071 + 0.01947413152*I'
86
+ assert bernoulli(x).evalf() == bernoulli(x)
87
+
88
+
89
+ def test_bernoulli_rewrite():
90
+ from sympy.functions.elementary.piecewise import Piecewise
91
+ n = Symbol('n', integer=True, nonnegative=True)
92
+
93
+ assert bernoulli(-1).rewrite(zeta) == pi**2/6
94
+ assert bernoulli(-2).rewrite(zeta) == 2*zeta(3)
95
+ assert not bernoulli(n, -3).rewrite(zeta).has(harmonic)
96
+ assert bernoulli(-4, x).rewrite(zeta) == 4*zeta(5, x)
97
+ assert isinstance(bernoulli(n, x).rewrite(zeta), Piecewise)
98
+ assert bernoulli(n+1, x).rewrite(zeta) == -(n+1) * zeta(-n, x)
99
+
100
+
101
+ def test_fibonacci():
102
+ assert [fibonacci(n) for n in range(-3, 5)] == [2, -1, 1, 0, 1, 1, 2, 3]
103
+ assert fibonacci(100) == 354224848179261915075
104
+ assert [lucas(n) for n in range(-3, 5)] == [-4, 3, -1, 2, 1, 3, 4, 7]
105
+ assert lucas(100) == 792070839848372253127
106
+
107
+ assert fibonacci(1, x) == 1
108
+ assert fibonacci(2, x) == x
109
+ assert fibonacci(3, x) == x**2 + 1
110
+ assert fibonacci(4, x) == x**3 + 2*x
111
+
112
+ # issue #8800
113
+ n = Dummy('n')
114
+ assert fibonacci(n).limit(n, S.Infinity) is S.Infinity
115
+ assert lucas(n).limit(n, S.Infinity) is S.Infinity
116
+
117
+ assert fibonacci(n).rewrite(sqrt) == \
118
+ 2**(-n)*sqrt(5)*((1 + sqrt(5))**n - (-sqrt(5) + 1)**n) / 5
119
+ assert fibonacci(n).rewrite(sqrt).subs(n, 10).expand() == fibonacci(10)
120
+ assert fibonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \
121
+ Float(fibonacci(10))
122
+ assert lucas(n).rewrite(sqrt) == \
123
+ (fibonacci(n-1).rewrite(sqrt) + fibonacci(n+1).rewrite(sqrt)).simplify()
124
+ assert lucas(n).rewrite(sqrt).subs(n, 10).expand() == lucas(10)
125
+ raises(ValueError, lambda: fibonacci(-3, x))
126
+
127
+
128
+ def test_tribonacci():
129
+ assert [tribonacci(n) for n in range(8)] == [0, 1, 1, 2, 4, 7, 13, 24]
130
+ assert tribonacci(100) == 98079530178586034536500564
131
+
132
+ assert tribonacci(0, x) == 0
133
+ assert tribonacci(1, x) == 1
134
+ assert tribonacci(2, x) == x**2
135
+ assert tribonacci(3, x) == x**4 + x
136
+ assert tribonacci(4, x) == x**6 + 2*x**3 + 1
137
+ assert tribonacci(5, x) == x**8 + 3*x**5 + 3*x**2
138
+
139
+ n = Dummy('n')
140
+ assert tribonacci(n).limit(n, S.Infinity) is S.Infinity
141
+
142
+ w = (-1 + S.ImaginaryUnit * sqrt(3)) / 2
143
+ a = (1 + cbrt(19 + 3*sqrt(33)) + cbrt(19 - 3*sqrt(33))) / 3
144
+ b = (1 + w*cbrt(19 + 3*sqrt(33)) + w**2*cbrt(19 - 3*sqrt(33))) / 3
145
+ c = (1 + w**2*cbrt(19 + 3*sqrt(33)) + w*cbrt(19 - 3*sqrt(33))) / 3
146
+ assert tribonacci(n).rewrite(sqrt) == \
147
+ (a**(n + 1)/((a - b)*(a - c))
148
+ + b**(n + 1)/((b - a)*(b - c))
149
+ + c**(n + 1)/((c - a)*(c - b)))
150
+ assert tribonacci(n).rewrite(sqrt).subs(n, 4).simplify() == tribonacci(4)
151
+ assert tribonacci(n).rewrite(GoldenRatio).subs(n,10).evalf() == \
152
+ Float(tribonacci(10))
153
+ assert tribonacci(n).rewrite(TribonacciConstant) == floor(
154
+ 3*TribonacciConstant**n*(102*sqrt(33) + 586)**Rational(1, 3)/
155
+ (-2*(102*sqrt(33) + 586)**Rational(1, 3) + 4 + (102*sqrt(33)
156
+ + 586)**Rational(2, 3)) + S.Half)
157
+ raises(ValueError, lambda: tribonacci(-1, x))
158
+
159
+
160
+ @nocache_fail
161
+ def test_bell():
162
+ assert [bell(n) for n in range(8)] == [1, 1, 2, 5, 15, 52, 203, 877]
163
+
164
+ assert bell(0, x) == 1
165
+ assert bell(1, x) == x
166
+ assert bell(2, x) == x**2 + x
167
+ assert bell(5, x) == x**5 + 10*x**4 + 25*x**3 + 15*x**2 + x
168
+ assert bell(oo) is S.Infinity
169
+ raises(ValueError, lambda: bell(oo, x))
170
+
171
+ raises(ValueError, lambda: bell(-1))
172
+ raises(ValueError, lambda: bell(S.Half))
173
+
174
+ X = symbols('x:6')
175
+ # X = (x0, x1, .. x5)
176
+ # at the same time: X[1] = x1, X[2] = x2 for standard readablity.
177
+ # but we must supply zero-based indexed object X[1:] = (x1, .. x5)
178
+
179
+ assert bell(6, 2, X[1:]) == 6*X[5]*X[1] + 15*X[4]*X[2] + 10*X[3]**2
180
+ assert bell(
181
+ 6, 3, X[1:]) == 15*X[4]*X[1]**2 + 60*X[3]*X[2]*X[1] + 15*X[2]**3
182
+
183
+ X = (1, 10, 100, 1000, 10000)
184
+ assert bell(6, 2, X) == (6 + 15 + 10)*10000
185
+
186
+ X = (1, 2, 3, 3, 5)
187
+ assert bell(6, 2, X) == 6*5 + 15*3*2 + 10*3**2
188
+
189
+ X = (1, 2, 3, 5)
190
+ assert bell(6, 3, X) == 15*5 + 60*3*2 + 15*2**3
191
+
192
+ # Dobinski's formula
193
+ n = Symbol('n', integer=True, nonnegative=True)
194
+ # For large numbers, this is too slow
195
+ # For nonintegers, there are significant precision errors
196
+ for i in [0, 2, 3, 7, 13, 42, 55]:
197
+ # Running without the cache this is either very slow or goes into an
198
+ # infinite loop.
199
+ assert bell(i).evalf() == bell(n).rewrite(Sum).evalf(subs={n: i})
200
+
201
+ m = Symbol("m")
202
+ assert bell(m).rewrite(Sum) == bell(m)
203
+ assert bell(n, m).rewrite(Sum) == bell(n, m)
204
+ # issue 9184
205
+ n = Dummy('n')
206
+ assert bell(n).limit(n, S.Infinity) is S.Infinity
207
+
208
+
209
+ def test_harmonic():
210
+ n = Symbol("n")
211
+ m = Symbol("m")
212
+
213
+ assert harmonic(n, 0) == n
214
+ assert harmonic(n).evalf() == harmonic(n)
215
+ assert harmonic(n, 1) == harmonic(n)
216
+ assert harmonic(1, n) == 1
217
+
218
+ assert harmonic(0, 1) == 0
219
+ assert harmonic(1, 1) == 1
220
+ assert harmonic(2, 1) == Rational(3, 2)
221
+ assert harmonic(3, 1) == Rational(11, 6)
222
+ assert harmonic(4, 1) == Rational(25, 12)
223
+ assert harmonic(0, 2) == 0
224
+ assert harmonic(1, 2) == 1
225
+ assert harmonic(2, 2) == Rational(5, 4)
226
+ assert harmonic(3, 2) == Rational(49, 36)
227
+ assert harmonic(4, 2) == Rational(205, 144)
228
+ assert harmonic(0, 3) == 0
229
+ assert harmonic(1, 3) == 1
230
+ assert harmonic(2, 3) == Rational(9, 8)
231
+ assert harmonic(3, 3) == Rational(251, 216)
232
+ assert harmonic(4, 3) == Rational(2035, 1728)
233
+
234
+ assert harmonic(oo, -1) is S.NaN
235
+ assert harmonic(oo, 0) is oo
236
+ assert harmonic(oo, S.Half) is oo
237
+ assert harmonic(oo, 1) is oo
238
+ assert harmonic(oo, 2) == (pi**2)/6
239
+ assert harmonic(oo, 3) == zeta(3)
240
+ assert harmonic(oo, Dummy(negative=True)) is S.NaN
241
+ ip = Dummy(integer=True, positive=True)
242
+ if (1/ip <= 1) is True: #---------------------------------+
243
+ assert None, 'delete this if-block and the next line' #|
244
+ ip = Dummy(even=True, positive=True) #--------------------+
245
+ assert harmonic(oo, 1/ip) is oo
246
+ assert harmonic(oo, 1 + ip) is zeta(1 + ip)
247
+
248
+ assert harmonic(0, m) == 0
249
+ assert harmonic(-1, -1) == 0
250
+ assert harmonic(-1, 0) == -1
251
+ assert harmonic(-1, 1) is S.ComplexInfinity
252
+ assert harmonic(-1, 2) is S.NaN
253
+ assert harmonic(-3, -2) == -5
254
+ assert harmonic(-3, -3) == 9
255
+
256
+
257
+ def test_harmonic_rational():
258
+ ne = S(6)
259
+ no = S(5)
260
+ pe = S(8)
261
+ po = S(9)
262
+ qe = S(10)
263
+ qo = S(13)
264
+
265
+ Heee = harmonic(ne + pe/qe)
266
+ Aeee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
267
+ + 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
268
+ + pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(13944145, 4720968))
269
+
270
+ Heeo = harmonic(ne + pe/qo)
271
+ Aeeo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(4, 13)) + 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(32, 13))
272
+ + 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13))
273
+ - 2*log(sin(pi*Rational(4, 13)))*cos(pi/13) + pi*cot(pi*Rational(5, 13))/2 - 2*log(sin(pi/13))*cos(pi*Rational(3, 13))
274
+ + Rational(2422020029, 702257080))
275
+
276
+ Heoe = harmonic(ne + po/qe)
277
+ Aeoe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4)
278
+ + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
279
+ + 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
280
+ + 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4)
281
+ + Rational(11818877030, 4286604231) + pi*sqrt(2*sqrt(5) + 5)/2)
282
+
283
+ Heoo = harmonic(ne + po/qo)
284
+ Aeoo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(54, 13)) + 2*log(sin(pi*Rational(4, 13)))*cos(pi*Rational(6, 13))
285
+ + 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13)
286
+ - 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2
287
+ - 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(3, 13)) + Rational(11669332571, 3628714320))
288
+
289
+ Hoee = harmonic(no + pe/qe)
290
+ Aoee = (-log(10) + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
291
+ + 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
292
+ + pi*sqrt(2*sqrt(5)/5 + 1)/2 + Rational(779405, 277704))
293
+
294
+ Hoeo = harmonic(no + pe/qo)
295
+ Aoeo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(4, 13)) + 2*log(sin(pi*Rational(2, 13)))*cos(pi*Rational(32, 13))
296
+ + 2*log(sin(pi*Rational(5, 13)))*cos(pi*Rational(80, 13)) - 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(5, 13))
297
+ - 2*log(sin(pi*Rational(4, 13)))*cos(pi/13) + pi*cot(pi*Rational(5, 13))/2
298
+ - 2*log(sin(pi/13))*cos(pi*Rational(3, 13)) + Rational(53857323, 16331560))
299
+
300
+ Hooe = harmonic(no + po/qe)
301
+ Aooe = (-log(20) + 2*(Rational(1, 4) + sqrt(5)/4)*log(Rational(-1, 4) + sqrt(5)/4)
302
+ + 2*(Rational(-1, 4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + Rational(5, 8)))
303
+ + 2*(-sqrt(5)/4 - Rational(1, 4))*log(sqrt(sqrt(5)/8 + Rational(5, 8)))
304
+ + 2*(-sqrt(5)/4 + Rational(1, 4))*log(Rational(1, 4) + sqrt(5)/4)
305
+ + Rational(486853480, 186374097) + pi*sqrt(2*sqrt(5) + 5)/2)
306
+
307
+ Hooo = harmonic(no + po/qo)
308
+ Aooo = (-log(26) + 2*log(sin(pi*Rational(3, 13)))*cos(pi*Rational(54, 13)) + 2*log(sin(pi*Rational(4, 13)))*cos(pi*Rational(6, 13))
309
+ + 2*log(sin(pi*Rational(6, 13)))*cos(pi*Rational(108, 13)) - 2*log(sin(pi*Rational(5, 13)))*cos(pi/13)
310
+ - 2*log(sin(pi/13))*cos(pi*Rational(5, 13)) + pi*cot(pi*Rational(4, 13))/2
311
+ - 2*log(sin(pi*Rational(2, 13)))*cos(3*pi/13) + Rational(383693479, 125128080))
312
+
313
+ H = [Heee, Heeo, Heoe, Heoo, Hoee, Hoeo, Hooe, Hooo]
314
+ A = [Aeee, Aeeo, Aeoe, Aeoo, Aoee, Aoeo, Aooe, Aooo]
315
+ for h, a in zip(H, A):
316
+ e = expand_func(h).doit()
317
+ assert cancel(e/a) == 1
318
+ assert abs(h.n() - a.n()) < 1e-12
319
+
320
+
321
+ def test_harmonic_evalf():
322
+ assert str(harmonic(1.5).evalf(n=10)) == '1.280372306'
323
+ assert str(harmonic(1.5, 2).evalf(n=10)) == '1.154576311' # issue 7443
324
+ assert str(harmonic(4.0, -3).evalf(n=10)) == '100.0000000'
325
+ assert str(harmonic(7.0, 1.0).evalf(n=10)) == '2.592857143'
326
+ assert str(harmonic(1, pi).evalf(n=10)) == '1.000000000'
327
+ assert str(harmonic(2, pi).evalf(n=10)) == '1.113314732'
328
+ assert str(harmonic(1000.0, pi).evalf(n=10)) == '1.176241563'
329
+ assert str(harmonic(I).evalf(n=10)) == '0.6718659855 + 1.076674047*I'
330
+ assert str(harmonic(I, I).evalf(n=10)) == '-0.3970915266 + 1.9629689*I'
331
+
332
+ assert harmonic(-1.0, 1).evalf() is S.NaN
333
+ assert harmonic(-2.0, 2.0).evalf() is S.NaN
334
+
335
+ def test_harmonic_rewrite():
336
+ from sympy.functions.elementary.piecewise import Piecewise
337
+ n = Symbol("n")
338
+ m = Symbol("m", integer=True, positive=True)
339
+ x1 = Symbol("x1", positive=True)
340
+ x2 = Symbol("x2", negative=True)
341
+
342
+ assert harmonic(n).rewrite(digamma) == polygamma(0, n + 1) + EulerGamma
343
+ assert harmonic(n).rewrite(trigamma) == polygamma(0, n + 1) + EulerGamma
344
+ assert harmonic(n).rewrite(polygamma) == polygamma(0, n + 1) + EulerGamma
345
+
346
+ assert harmonic(n,3).rewrite(polygamma) == polygamma(2, n + 1)/2 - polygamma(2, 1)/2
347
+ assert isinstance(harmonic(n,m).rewrite(polygamma), Piecewise)
348
+
349
+ assert expand_func(harmonic(n+4)) == harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)
350
+ assert expand_func(harmonic(n-4)) == harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n
351
+
352
+ assert harmonic(n, m).rewrite("tractable") == harmonic(n, m).rewrite(polygamma)
353
+ assert harmonic(n, x1).rewrite("tractable") == harmonic(n, x1)
354
+ assert harmonic(n, x1 + 1).rewrite("tractable") == zeta(x1 + 1) - zeta(x1 + 1, n + 1)
355
+ assert harmonic(n, x2).rewrite("tractable") == zeta(x2) - zeta(x2, n + 1)
356
+
357
+ _k = Dummy("k")
358
+ assert harmonic(n).rewrite(Sum).dummy_eq(Sum(1/_k, (_k, 1, n)))
359
+ assert harmonic(n, m).rewrite(Sum).dummy_eq(Sum(_k**(-m), (_k, 1, n)))
360
+
361
+
362
+ def test_harmonic_calculus():
363
+ y = Symbol("y", positive=True)
364
+ z = Symbol("z", negative=True)
365
+ assert harmonic(x, 1).limit(x, 0) == 0
366
+ assert harmonic(x, y).limit(x, 0) == 0
367
+ assert harmonic(x, 1).series(x, y, 2) == \
368
+ harmonic(y) + (x - y)*zeta(2, y + 1) + O((x - y)**2, (x, y))
369
+ assert limit(harmonic(x, y), x, oo) == harmonic(oo, y)
370
+ assert limit(harmonic(x, y + 1), x, oo) == zeta(y + 1)
371
+ assert limit(harmonic(x, y - 1), x, oo) == harmonic(oo, y - 1)
372
+ assert limit(harmonic(x, z), x, oo) == Limit(harmonic(x, z), x, oo, dir='-')
373
+ assert limit(harmonic(x, z + 1), x, oo) == oo
374
+ assert limit(harmonic(x, z + 2), x, oo) == harmonic(oo, z + 2)
375
+ assert limit(harmonic(x, z - 1), x, oo) == Limit(harmonic(x, z - 1), x, oo, dir='-')
376
+
377
+
378
+ def test_euler():
379
+ assert euler(0) == 1
380
+ assert euler(1) == 0
381
+ assert euler(2) == -1
382
+ assert euler(3) == 0
383
+ assert euler(4) == 5
384
+ assert euler(6) == -61
385
+ assert euler(8) == 1385
386
+
387
+ assert euler(20, evaluate=False) != 370371188237525
388
+
389
+ n = Symbol('n', integer=True)
390
+ assert euler(n) != -1
391
+ assert euler(n).subs(n, 2) == -1
392
+
393
+ assert euler(-1) == S.Pi / 2
394
+ assert euler(-1, 1) == 2*log(2)
395
+ assert euler(-2).evalf() == (2*S.Catalan).evalf()
396
+ assert euler(-3).evalf() == (S.Pi**3 / 16).evalf()
397
+ assert str(euler(2.3).evalf(n=10)) == '-1.052850274'
398
+ assert str(euler(1.2, 3.4).evalf(n=10)) == '3.575613489'
399
+ assert str(euler(I).evalf(n=10)) == '1.248446443 - 0.7675445124*I'
400
+ assert str(euler(I, I).evalf(n=10)) == '0.04812930469 + 0.01052411008*I'
401
+
402
+ assert euler(20).evalf() == 370371188237525.0
403
+ assert euler(20, evaluate=False).evalf() == 370371188237525.0
404
+
405
+ assert euler(n).rewrite(Sum) == euler(n)
406
+ n = Symbol('n', integer=True, nonnegative=True)
407
+ assert euler(2*n + 1).rewrite(Sum) == 0
408
+ _j = Dummy('j')
409
+ _k = Dummy('k')
410
+ assert euler(2*n).rewrite(Sum).dummy_eq(
411
+ I*Sum((-1)**_j*2**(-_k)*I**(-_k)*(-2*_j + _k)**(2*n + 1)*
412
+ binomial(_k, _j)/_k, (_j, 0, _k), (_k, 1, 2*n + 1)))
413
+
414
+
415
+ def test_euler_odd():
416
+ n = Symbol('n', odd=True, positive=True)
417
+ assert euler(n) == 0
418
+ n = Symbol('n', odd=True)
419
+ assert euler(n) != 0
420
+
421
+
422
+ def test_euler_polynomials():
423
+ assert euler(0, x) == 1
424
+ assert euler(1, x) == x - S.Half
425
+ assert euler(2, x) == x**2 - x
426
+ assert euler(3, x) == x**3 - (3*x**2)/2 + Rational(1, 4)
427
+ m = Symbol('m')
428
+ assert isinstance(euler(m, x), euler)
429
+ from sympy.core.numbers import Float
430
+ A = Float('-0.46237208575048694923364757452876131e8') # from Maple
431
+ B = euler(19, S.Pi).evalf(32)
432
+ assert abs((A - B)/A) < 1e-31
433
+
434
+
435
+ def test_euler_polynomial_rewrite():
436
+ m = Symbol('m')
437
+ A = euler(m, x).rewrite('Sum');
438
+ assert A.subs({m:3, x:5}).doit() == euler(3, 5)
439
+
440
+
441
+ def test_catalan():
442
+ n = Symbol('n', integer=True)
443
+ m = Symbol('m', integer=True, positive=True)
444
+ k = Symbol('k', integer=True, nonnegative=True)
445
+ p = Symbol('p', nonnegative=True)
446
+
447
+ catalans = [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786]
448
+ for i, c in enumerate(catalans):
449
+ assert catalan(i) == c
450
+ assert catalan(n).rewrite(factorial).subs(n, i) == c
451
+ assert catalan(n).rewrite(Product).subs(n, i).doit() == c
452
+
453
+ assert unchanged(catalan, x)
454
+ assert catalan(2*x).rewrite(binomial) == binomial(4*x, 2*x)/(2*x + 1)
455
+ assert catalan(S.Half).rewrite(gamma) == 8/(3*pi)
456
+ assert catalan(S.Half).rewrite(factorial).rewrite(gamma) ==\
457
+ 8 / (3 * pi)
458
+ assert catalan(3*x).rewrite(gamma) == 4**(
459
+ 3*x)*gamma(3*x + S.Half)/(sqrt(pi)*gamma(3*x + 2))
460
+ assert catalan(x).rewrite(hyper) == hyper((-x + 1, -x), (2,), 1)
461
+
462
+ assert catalan(n).rewrite(factorial) == factorial(2*n) / (factorial(n + 1)
463
+ * factorial(n))
464
+ assert isinstance(catalan(n).rewrite(Product), catalan)
465
+ assert isinstance(catalan(m).rewrite(Product), Product)
466
+
467
+ assert diff(catalan(x), x) == (polygamma(
468
+ 0, x + S.Half) - polygamma(0, x + 2) + log(4))*catalan(x)
469
+
470
+ assert catalan(x).evalf() == catalan(x)
471
+ c = catalan(S.Half).evalf()
472
+ assert str(c) == '0.848826363156775'
473
+ c = catalan(I).evalf(3)
474
+ assert str((re(c), im(c))) == '(0.398, -0.0209)'
475
+
476
+ # Assumptions
477
+ assert catalan(p).is_positive is True
478
+ assert catalan(k).is_integer is True
479
+ assert catalan(m+3).is_composite is True
480
+
481
+
482
+ def test_genocchi():
483
+ genocchis = [0, -1, -1, 0, 1, 0, -3, 0, 17]
484
+ for n, g in enumerate(genocchis):
485
+ assert genocchi(n) == g
486
+
487
+ m = Symbol('m', integer=True)
488
+ n = Symbol('n', integer=True, positive=True)
489
+ assert unchanged(genocchi, m)
490
+ assert genocchi(2*n + 1) == 0
491
+ gn = 2 * (1 - 2**n) * bernoulli(n)
492
+ assert genocchi(n).rewrite(bernoulli).factor() == gn.factor()
493
+ gnx = 2 * (bernoulli(n, x) - 2**n * bernoulli(n, (x+1) / 2))
494
+ assert genocchi(n, x).rewrite(bernoulli).factor() == gnx.factor()
495
+ assert genocchi(2 * n).is_odd
496
+ assert genocchi(2 * n).is_even is False
497
+ assert genocchi(2 * n + 1).is_even
498
+ assert genocchi(n).is_integer
499
+ assert genocchi(4 * n).is_positive
500
+ # these are the only 2 prime Genocchi numbers
501
+ assert genocchi(6, evaluate=False).is_prime == S(-3).is_prime
502
+ assert genocchi(8, evaluate=False).is_prime
503
+ assert genocchi(4 * n + 2).is_negative
504
+ assert genocchi(4 * n + 1).is_negative is False
505
+ assert genocchi(4 * n - 2).is_negative
506
+
507
+ g0 = genocchi(0, evaluate=False)
508
+ assert g0.is_positive is False
509
+ assert g0.is_negative is False
510
+ assert g0.is_even is True
511
+ assert g0.is_odd is False
512
+
513
+ assert genocchi(0, x) == 0
514
+ assert genocchi(1, x) == -1
515
+ assert genocchi(2, x) == 1 - 2*x
516
+ assert genocchi(3, x) == 3*x - 3*x**2
517
+ assert genocchi(4, x) == -1 + 6*x**2 - 4*x**3
518
+ y = Symbol("y")
519
+ assert genocchi(5, (x+y)**100) == -5*(x+y)**400 + 10*(x+y)**300 - 5*(x+y)**100
520
+
521
+ assert str(genocchi(5.0, 4.0).evalf(n=10)) == '-660.0000000'
522
+ assert str(genocchi(Rational(5, 4)).evalf(n=10)) == '-1.104286457'
523
+ assert str(genocchi(-2).evalf(n=10)) == '3.606170709'
524
+ assert str(genocchi(1.3, 3.7).evalf(n=10)) == '-1.847375373'
525
+ assert str(genocchi(I, 1.0).evalf(n=10)) == '-0.3161917278 - 1.45311955*I'
526
+
527
+ n = Symbol('n')
528
+ assert genocchi(n, x).rewrite(dirichlet_eta) == -2*n * dirichlet_eta(1-n, x)
529
+
530
+
531
+ def test_andre():
532
+ nums = [1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]
533
+ for n, a in enumerate(nums):
534
+ assert andre(n) == a
535
+ assert andre(S.Infinity) == S.Infinity
536
+ assert andre(-1) == -log(2)
537
+ assert andre(-2) == -2*S.Catalan
538
+ assert andre(-3) == 3*zeta(3)/16
539
+ assert andre(-5) == -15*zeta(5)/256
540
+ # In fact andre(-2*n) is related to the Dirichlet *beta* function
541
+ # at 2*n, but SymPy doesn't implement that (or general L-functions)
542
+ assert unchanged(andre, -4)
543
+
544
+ n = Symbol('n', integer=True, nonnegative=True)
545
+ assert unchanged(andre, n)
546
+ assert andre(n).is_integer is True
547
+ assert andre(n).is_positive is True
548
+
549
+ assert str(andre(10, evaluate=False).evalf(n=10)) == '50521.00000'
550
+ assert str(andre(-1, evaluate=False).evalf(n=10)) == '-0.6931471806'
551
+ assert str(andre(-2, evaluate=False).evalf(n=10)) == '-1.831931188'
552
+ assert str(andre(-4, evaluate=False).evalf(n=10)) == '1.977889103'
553
+ assert str(andre(I, evaluate=False).evalf(n=10)) == '2.378417833 + 0.6343322845*I'
554
+
555
+ assert andre(x).rewrite(polylog) == \
556
+ (-I)**(x+1) * polylog(-x, I) + I**(x+1) * polylog(-x, -I)
557
+ assert andre(x).rewrite(zeta) == \
558
+ 2 * gamma(x+1) / (2*pi)**(x+1) * \
559
+ (zeta(x+1, Rational(1,4)) - cos(pi*x) * zeta(x+1, Rational(3,4)))
560
+
561
+
562
+ @nocache_fail
563
+ def test_partition():
564
+ partition_nums = [1, 1, 2, 3, 5, 7, 11, 15, 22]
565
+ for n, p in enumerate(partition_nums):
566
+ assert partition(n) == p
567
+
568
+ x = Symbol('x')
569
+ y = Symbol('y', real=True)
570
+ m = Symbol('m', integer=True)
571
+ n = Symbol('n', integer=True, negative=True)
572
+ p = Symbol('p', integer=True, nonnegative=True)
573
+ assert partition(m).is_integer
574
+ assert not partition(m).is_negative
575
+ assert partition(m).is_nonnegative
576
+ assert partition(n).is_zero
577
+ assert partition(p).is_positive
578
+ assert partition(x).subs(x, 7) == 15
579
+ assert partition(y).subs(y, 8) == 22
580
+ raises(ValueError, lambda: partition(Rational(5, 4)))
581
+
582
+
583
+ def test__nT():
584
+ assert [_nT(i, j) for i in range(5) for j in range(i + 2)] == [
585
+ 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 2, 1, 1, 0]
586
+ check = [_nT(10, i) for i in range(11)]
587
+ assert check == [0, 1, 5, 8, 9, 7, 5, 3, 2, 1, 1]
588
+ assert all(type(i) is int for i in check)
589
+ assert _nT(10, 5) == 7
590
+ assert _nT(100, 98) == 2
591
+ assert _nT(100, 100) == 1
592
+ assert _nT(10, 3) == 8
593
+
594
+
595
+ def test_nC_nP_nT():
596
+ from sympy.utilities.iterables import (
597
+ multiset_permutations, multiset_combinations, multiset_partitions,
598
+ partitions, subsets, permutations)
599
+ from sympy.functions.combinatorial.numbers import (
600
+ nP, nC, nT, stirling, _stirling1, _stirling2, _multiset_histogram, _AOP_product)
601
+
602
+ from sympy.combinatorics.permutations import Permutation
603
+ from sympy.core.random import choice
604
+
605
+ c = string.ascii_lowercase
606
+ for i in range(100):
607
+ s = ''.join(choice(c) for i in range(7))
608
+ u = len(s) == len(set(s))
609
+ try:
610
+ tot = 0
611
+ for i in range(8):
612
+ check = nP(s, i)
613
+ tot += check
614
+ assert len(list(multiset_permutations(s, i))) == check
615
+ if u:
616
+ assert nP(len(s), i) == check
617
+ assert nP(s) == tot
618
+ except AssertionError:
619
+ print(s, i, 'failed perm test')
620
+ raise ValueError()
621
+
622
+ for i in range(100):
623
+ s = ''.join(choice(c) for i in range(7))
624
+ u = len(s) == len(set(s))
625
+ try:
626
+ tot = 0
627
+ for i in range(8):
628
+ check = nC(s, i)
629
+ tot += check
630
+ assert len(list(multiset_combinations(s, i))) == check
631
+ if u:
632
+ assert nC(len(s), i) == check
633
+ assert nC(s) == tot
634
+ if u:
635
+ assert nC(len(s)) == tot
636
+ except AssertionError:
637
+ print(s, i, 'failed combo test')
638
+ raise ValueError()
639
+
640
+ for i in range(1, 10):
641
+ tot = 0
642
+ for j in range(1, i + 2):
643
+ check = nT(i, j)
644
+ assert check.is_Integer
645
+ tot += check
646
+ assert sum(1 for p in partitions(i, j, size=True) if p[0] == j) == check
647
+ assert nT(i) == tot
648
+
649
+ for i in range(1, 10):
650
+ tot = 0
651
+ for j in range(1, i + 2):
652
+ check = nT(range(i), j)
653
+ tot += check
654
+ assert len(list(multiset_partitions(list(range(i)), j))) == check
655
+ assert nT(range(i)) == tot
656
+
657
+ for i in range(100):
658
+ s = ''.join(choice(c) for i in range(7))
659
+ u = len(s) == len(set(s))
660
+ try:
661
+ tot = 0
662
+ for i in range(1, 8):
663
+ check = nT(s, i)
664
+ tot += check
665
+ assert len(list(multiset_partitions(s, i))) == check
666
+ if u:
667
+ assert nT(range(len(s)), i) == check
668
+ if u:
669
+ assert nT(range(len(s))) == tot
670
+ assert nT(s) == tot
671
+ except AssertionError:
672
+ print(s, i, 'failed partition test')
673
+ raise ValueError()
674
+
675
+ # tests for Stirling numbers of the first kind that are not tested in the
676
+ # above
677
+ assert [stirling(9, i, kind=1) for i in range(11)] == [
678
+ 0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1, 0]
679
+ perms = list(permutations(range(4)))
680
+ assert [sum(1 for p in perms if Permutation(p).cycles == i)
681
+ for i in range(5)] == [0, 6, 11, 6, 1] == [
682
+ stirling(4, i, kind=1) for i in range(5)]
683
+ # http://oeis.org/A008275
684
+ assert [stirling(n, k, signed=1)
685
+ for n in range(10) for k in range(1, n + 1)] == [
686
+ 1, -1,
687
+ 1, 2, -3,
688
+ 1, -6, 11, -6,
689
+ 1, 24, -50, 35, -10,
690
+ 1, -120, 274, -225, 85, -15,
691
+ 1, 720, -1764, 1624, -735, 175, -21,
692
+ 1, -5040, 13068, -13132, 6769, -1960, 322, -28,
693
+ 1, 40320, -109584, 118124, -67284, 22449, -4536, 546, -36, 1]
694
+ # https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
695
+ assert [stirling(n, k, kind=1)
696
+ for n in range(10) for k in range(n+1)] == [
697
+ 1,
698
+ 0, 1,
699
+ 0, 1, 1,
700
+ 0, 2, 3, 1,
701
+ 0, 6, 11, 6, 1,
702
+ 0, 24, 50, 35, 10, 1,
703
+ 0, 120, 274, 225, 85, 15, 1,
704
+ 0, 720, 1764, 1624, 735, 175, 21, 1,
705
+ 0, 5040, 13068, 13132, 6769, 1960, 322, 28, 1,
706
+ 0, 40320, 109584, 118124, 67284, 22449, 4536, 546, 36, 1]
707
+ # https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind
708
+ assert [stirling(n, k, kind=2)
709
+ for n in range(10) for k in range(n+1)] == [
710
+ 1,
711
+ 0, 1,
712
+ 0, 1, 1,
713
+ 0, 1, 3, 1,
714
+ 0, 1, 7, 6, 1,
715
+ 0, 1, 15, 25, 10, 1,
716
+ 0, 1, 31, 90, 65, 15, 1,
717
+ 0, 1, 63, 301, 350, 140, 21, 1,
718
+ 0, 1, 127, 966, 1701, 1050, 266, 28, 1,
719
+ 0, 1, 255, 3025, 7770, 6951, 2646, 462, 36, 1]
720
+ assert stirling(3, 4, kind=1) == stirling(3, 4, kind=1) == 0
721
+ raises(ValueError, lambda: stirling(-2, 2))
722
+
723
+ # Assertion that the return type is SymPy Integer.
724
+ assert isinstance(_stirling1(6, 3), Integer)
725
+ assert isinstance(_stirling2(6, 3), Integer)
726
+
727
+ def delta(p):
728
+ if len(p) == 1:
729
+ return oo
730
+ return min(abs(i[0] - i[1]) for i in subsets(p, 2))
731
+ parts = multiset_partitions(range(5), 3)
732
+ d = 2
733
+ assert (sum(1 for p in parts if all(delta(i) >= d for i in p)) ==
734
+ stirling(5, 3, d=d) == 7)
735
+
736
+ # other coverage tests
737
+ assert nC('abb', 2) == nC('aab', 2) == 2
738
+ assert nP(3, 3, replacement=True) == nP('aabc', 3, replacement=True) == 27
739
+ assert nP(3, 4) == 0
740
+ assert nP('aabc', 5) == 0
741
+ assert nC(4, 2, replacement=True) == nC('abcdd', 2, replacement=True) == \
742
+ len(list(multiset_combinations('aabbccdd', 2))) == 10
743
+ assert nC('abcdd') == sum(nC('abcdd', i) for i in range(6)) == 24
744
+ assert nC(list('abcdd'), 4) == 4
745
+ assert nT('aaaa') == nT(4) == len(list(partitions(4))) == 5
746
+ assert nT('aaab') == len(list(multiset_partitions('aaab'))) == 7
747
+ assert nC('aabb'*3, 3) == 4 # aaa, bbb, abb, baa
748
+ assert dict(_AOP_product((4,1,1,1))) == {
749
+ 0: 1, 1: 4, 2: 7, 3: 8, 4: 8, 5: 7, 6: 4, 7: 1}
750
+ # the following was the first t that showed a problem in a previous form of
751
+ # the function, so it's not as random as it may appear
752
+ t = (3, 9, 4, 6, 6, 5, 5, 2, 10, 4)
753
+ assert sum(_AOP_product(t)[i] for i in range(55)) == 58212000
754
+ raises(ValueError, lambda: _multiset_histogram({1:'a'}))
755
+
756
+
757
+ def test_PR_14617():
758
+ from sympy.functions.combinatorial.numbers import nT
759
+ for n in (0, []):
760
+ for k in (-1, 0, 1):
761
+ if k == 0:
762
+ assert nT(n, k) == 1
763
+ else:
764
+ assert nT(n, k) == 0
765
+
766
+
767
+ def test_issue_8496():
768
+ n = Symbol("n")
769
+ k = Symbol("k")
770
+
771
+ raises(TypeError, lambda: catalan(n, k))
772
+
773
+
774
+ def test_issue_8601():
775
+ n = Symbol('n', integer=True, negative=True)
776
+
777
+ assert catalan(n - 1) is S.Zero
778
+ assert catalan(Rational(-1, 2)) is S.ComplexInfinity
779
+ assert catalan(-S.One) == Rational(-1, 2)
780
+ c1 = catalan(-5.6).evalf()
781
+ assert str(c1) == '6.93334070531408e-5'
782
+ c2 = catalan(-35.4).evalf()
783
+ assert str(c2) == '-4.14189164517449e-24'
784
+
785
+
786
+ def test_motzkin():
787
+ assert motzkin.is_motzkin(4) == True
788
+ assert motzkin.is_motzkin(9) == True
789
+ assert motzkin.is_motzkin(10) == False
790
+ assert motzkin.find_motzkin_numbers_in_range(10,200) == [21, 51, 127]
791
+ assert motzkin.find_motzkin_numbers_in_range(10,400) == [21, 51, 127, 323]
792
+ assert motzkin.find_motzkin_numbers_in_range(10,1600) == [21, 51, 127, 323, 835]
793
+ assert motzkin.find_first_n_motzkins(5) == [1, 1, 2, 4, 9]
794
+ assert motzkin.find_first_n_motzkins(7) == [1, 1, 2, 4, 9, 21, 51]
795
+ assert motzkin.find_first_n_motzkins(10) == [1, 1, 2, 4, 9, 21, 51, 127, 323, 835]
796
+ raises(ValueError, lambda: motzkin.eval(77.58))
797
+ raises(ValueError, lambda: motzkin.eval(-8))
798
+ raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(-2,7))
799
+ raises(ValueError, lambda: motzkin.find_motzkin_numbers_in_range(13,7))
800
+ raises(ValueError, lambda: motzkin.find_first_n_motzkins(112.8))
801
+
802
+
803
+ def test_nD_derangements():
804
+ from sympy.utilities.iterables import (partitions, multiset,
805
+ multiset_derangements, multiset_permutations)
806
+ from sympy.functions.combinatorial.numbers import nD
807
+
808
+ got = []
809
+ for i in partitions(8, k=4):
810
+ s = []
811
+ it = 0
812
+ for k, v in i.items():
813
+ for i in range(v):
814
+ s.extend([it]*k)
815
+ it += 1
816
+ ms = multiset(s)
817
+ c1 = sum(1 for i in multiset_permutations(s) if
818
+ all(i != j for i, j in zip(i, s)))
819
+ assert c1 == nD(ms) == nD(ms, 0) == nD(ms, 1)
820
+ v = [tuple(i) for i in multiset_derangements(s)]
821
+ c2 = len(v)
822
+ assert c2 == len(set(v))
823
+ assert c1 == c2
824
+ got.append(c1)
825
+ assert got == [1, 4, 6, 12, 24, 24, 61, 126, 315, 780, 297, 772,
826
+ 2033, 5430, 14833]
827
+
828
+ assert nD('1112233456', brute=True) == nD('1112233456') == 16356
829
+ assert nD('') == nD([]) == nD({}) == 0
830
+ assert nD({1: 0}) == 0
831
+ raises(ValueError, lambda: nD({1: -1}))
832
+ assert nD('112') == 0
833
+ assert nD(i='112') == 0
834
+ assert [nD(n=i) for i in range(6)] == [0, 0, 1, 2, 9, 44]
835
+ assert nD((i for i in range(4))) == nD('0123') == 9
836
+ assert nD(m=(i for i in range(4))) == 3
837
+ assert nD(m={0: 1, 1: 1, 2: 1, 3: 1}) == 3
838
+ assert nD(m=[0, 1, 2, 3]) == 3
839
+ raises(TypeError, lambda: nD(m=0))
840
+ raises(TypeError, lambda: nD(-1))
841
+ assert nD({-1: 1, -2: 1}) == 1
842
+ assert nD(m={0: 3}) == 0
843
+ raises(ValueError, lambda: nD(i='123', n=3))
844
+ raises(ValueError, lambda: nD(i='123', m=(1,2)))
845
+ raises(ValueError, lambda: nD(n=0, m=(1,2)))
846
+ raises(ValueError, lambda: nD({1: -1}))
847
+ raises(ValueError, lambda: nD(m={-1: 1, 2: 1}))
848
+ raises(ValueError, lambda: nD(m={1: -1, 2: 1}))
849
+ raises(ValueError, lambda: nD(m=[-1, 2]))
850
+ raises(TypeError, lambda: nD({1: x}))
851
+ raises(TypeError, lambda: nD(m={1: x}))
852
+ raises(TypeError, lambda: nD(m={x: 1}))
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/complexes.cpython-310.pyc ADDED
Binary file (39 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/exponential.cpython-310.pyc ADDED
Binary file (34.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/integers.cpython-310.pyc ADDED
Binary file (16 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (210 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/__pycache__/bench_exp.cpython-310.pyc ADDED
Binary file (535 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/benchmarks/bench_exp.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import symbols
2
+ from sympy.functions.elementary.exponential import exp
3
+
4
+ x, y = symbols('x,y')
5
+
6
+ e = exp(2*x)
7
+ q = exp(3*x)
8
+
9
+
10
+ def timeit_exp_subs():
11
+ e.subs(q, y)
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (205 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_complexes.cpython-310.pyc ADDED
Binary file (30.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_exponential.cpython-310.pyc ADDED
Binary file (29.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_hyperbolic.cpython-310.pyc ADDED
Binary file (54.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_integers.cpython-310.pyc ADDED
Binary file (16.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_interface.cpython-310.pyc ADDED
Binary file (3.11 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_miscellaneous.cpython-310.pyc ADDED
Binary file (15.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_piecewise.cpython-310.pyc ADDED
Binary file (54.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_trigonometric.cpython-310.pyc ADDED
Binary file (85.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_complexes.py ADDED
@@ -0,0 +1,1018 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.expr import Expr
2
+ from sympy.core.function import (Derivative, Function, Lambda, expand)
3
+ from sympy.core.numbers import (E, I, Rational, comp, nan, oo, pi, zoo)
4
+ from sympy.core.relational import Eq
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import (Symbol, symbols)
7
+ from sympy.functions.elementary.complexes import (Abs, adjoint, arg, conjugate, im, re, sign, transpose)
8
+ from sympy.functions.elementary.exponential import (exp, exp_polar, log)
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.functions.elementary.piecewise import Piecewise
11
+ from sympy.functions.elementary.trigonometric import (acos, atan, atan2, cos, sin)
12
+ from sympy.functions.special.delta_functions import (DiracDelta, Heaviside)
13
+ from sympy.integrals.integrals import Integral
14
+ from sympy.matrices.dense import Matrix
15
+ from sympy.matrices.expressions.funcmatrix import FunctionMatrix
16
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
17
+ from sympy.matrices.immutable import (ImmutableMatrix, ImmutableSparseMatrix)
18
+ from sympy.matrices import SparseMatrix
19
+ from sympy.sets.sets import Interval
20
+ from sympy.core.expr import unchanged
21
+ from sympy.core.function import ArgumentIndexError
22
+ from sympy.testing.pytest import XFAIL, raises, _both_exp_pow
23
+
24
+
25
+ def N_equals(a, b):
26
+ """Check whether two complex numbers are numerically close"""
27
+ return comp(a.n(), b.n(), 1.e-6)
28
+
29
+
30
+ def test_re():
31
+ x, y = symbols('x,y')
32
+ a, b = symbols('a,b', real=True)
33
+
34
+ r = Symbol('r', real=True)
35
+ i = Symbol('i', imaginary=True)
36
+
37
+ assert re(nan) is nan
38
+
39
+ assert re(oo) is oo
40
+ assert re(-oo) is -oo
41
+
42
+ assert re(0) == 0
43
+
44
+ assert re(1) == 1
45
+ assert re(-1) == -1
46
+
47
+ assert re(E) == E
48
+ assert re(-E) == -E
49
+
50
+ assert unchanged(re, x)
51
+ assert re(x*I) == -im(x)
52
+ assert re(r*I) == 0
53
+ assert re(r) == r
54
+ assert re(i*I) == I * i
55
+ assert re(i) == 0
56
+
57
+ assert re(x + y) == re(x) + re(y)
58
+ assert re(x + r) == re(x) + r
59
+
60
+ assert re(re(x)) == re(x)
61
+
62
+ assert re(2 + I) == 2
63
+ assert re(x + I) == re(x)
64
+
65
+ assert re(x + y*I) == re(x) - im(y)
66
+ assert re(x + r*I) == re(x)
67
+
68
+ assert re(log(2*I)) == log(2)
69
+
70
+ assert re((2 + I)**2).expand(complex=True) == 3
71
+
72
+ assert re(conjugate(x)) == re(x)
73
+ assert conjugate(re(x)) == re(x)
74
+
75
+ assert re(x).as_real_imag() == (re(x), 0)
76
+
77
+ assert re(i*r*x).diff(r) == re(i*x)
78
+ assert re(i*r*x).diff(i) == I*r*im(x)
79
+
80
+ assert re(
81
+ sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)
82
+ assert re(a * (2 + b*I)) == 2*a
83
+
84
+ assert re((1 + sqrt(a + b*I))/2) == \
85
+ (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)/2 + S.Half
86
+
87
+ assert re(x).rewrite(im) == x - S.ImaginaryUnit*im(x)
88
+ assert (x + re(y)).rewrite(re, im) == x + y - S.ImaginaryUnit*im(y)
89
+
90
+ a = Symbol('a', algebraic=True)
91
+ t = Symbol('t', transcendental=True)
92
+ x = Symbol('x')
93
+ assert re(a).is_algebraic
94
+ assert re(x).is_algebraic is None
95
+ assert re(t).is_algebraic is False
96
+
97
+ assert re(S.ComplexInfinity) is S.NaN
98
+
99
+ n, m, l = symbols('n m l')
100
+ A = MatrixSymbol('A',n,m)
101
+ assert re(A) == (S.Half) * (A + conjugate(A))
102
+
103
+ A = Matrix([[1 + 4*I,2],[0, -3*I]])
104
+ assert re(A) == Matrix([[1, 2],[0, 0]])
105
+
106
+ A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]])
107
+ assert re(A) == ImmutableMatrix([[1, 3],[0, 0]])
108
+
109
+ X = SparseMatrix([[2*j + i*I for i in range(5)] for j in range(5)])
110
+ assert re(X) - Matrix([[0, 0, 0, 0, 0],
111
+ [2, 2, 2, 2, 2],
112
+ [4, 4, 4, 4, 4],
113
+ [6, 6, 6, 6, 6],
114
+ [8, 8, 8, 8, 8]]) == Matrix.zeros(5)
115
+
116
+ assert im(X) - Matrix([[0, 1, 2, 3, 4],
117
+ [0, 1, 2, 3, 4],
118
+ [0, 1, 2, 3, 4],
119
+ [0, 1, 2, 3, 4],
120
+ [0, 1, 2, 3, 4]]) == Matrix.zeros(5)
121
+
122
+ X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I))
123
+ assert re(X) == Matrix([[0, 0, 0], [1, 1, 1], [2, 2, 2]])
124
+
125
+
126
+ def test_im():
127
+ x, y = symbols('x,y')
128
+ a, b = symbols('a,b', real=True)
129
+
130
+ r = Symbol('r', real=True)
131
+ i = Symbol('i', imaginary=True)
132
+
133
+ assert im(nan) is nan
134
+
135
+ assert im(oo*I) is oo
136
+ assert im(-oo*I) is -oo
137
+
138
+ assert im(0) == 0
139
+
140
+ assert im(1) == 0
141
+ assert im(-1) == 0
142
+
143
+ assert im(E*I) == E
144
+ assert im(-E*I) == -E
145
+
146
+ assert unchanged(im, x)
147
+ assert im(x*I) == re(x)
148
+ assert im(r*I) == r
149
+ assert im(r) == 0
150
+ assert im(i*I) == 0
151
+ assert im(i) == -I * i
152
+
153
+ assert im(x + y) == im(x) + im(y)
154
+ assert im(x + r) == im(x)
155
+ assert im(x + r*I) == im(x) + r
156
+
157
+ assert im(im(x)*I) == im(x)
158
+
159
+ assert im(2 + I) == 1
160
+ assert im(x + I) == im(x) + 1
161
+
162
+ assert im(x + y*I) == im(x) + re(y)
163
+ assert im(x + r*I) == im(x) + r
164
+
165
+ assert im(log(2*I)) == pi/2
166
+
167
+ assert im((2 + I)**2).expand(complex=True) == 4
168
+
169
+ assert im(conjugate(x)) == -im(x)
170
+ assert conjugate(im(x)) == im(x)
171
+
172
+ assert im(x).as_real_imag() == (im(x), 0)
173
+
174
+ assert im(i*r*x).diff(r) == im(i*x)
175
+ assert im(i*r*x).diff(i) == -I * re(r*x)
176
+
177
+ assert im(
178
+ sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)
179
+ assert im(a * (2 + b*I)) == a*b
180
+
181
+ assert im((1 + sqrt(a + b*I))/2) == \
182
+ (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2
183
+
184
+ assert im(x).rewrite(re) == -S.ImaginaryUnit * (x - re(x))
185
+ assert (x + im(y)).rewrite(im, re) == x - S.ImaginaryUnit * (y - re(y))
186
+
187
+ a = Symbol('a', algebraic=True)
188
+ t = Symbol('t', transcendental=True)
189
+ x = Symbol('x')
190
+ assert re(a).is_algebraic
191
+ assert re(x).is_algebraic is None
192
+ assert re(t).is_algebraic is False
193
+
194
+ assert im(S.ComplexInfinity) is S.NaN
195
+
196
+ n, m, l = symbols('n m l')
197
+ A = MatrixSymbol('A',n,m)
198
+
199
+ assert im(A) == (S.One/(2*I)) * (A - conjugate(A))
200
+
201
+ A = Matrix([[1 + 4*I, 2],[0, -3*I]])
202
+ assert im(A) == Matrix([[4, 0],[0, -3]])
203
+
204
+ A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]])
205
+ assert im(A) == ImmutableMatrix([[3, -2],[0, 2]])
206
+
207
+ X = ImmutableSparseMatrix(
208
+ [[i*I + i for i in range(5)] for i in range(5)])
209
+ Y = SparseMatrix([list(range(5)) for i in range(5)])
210
+ assert im(X).as_immutable() == Y
211
+
212
+ X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I))
213
+ assert im(X) == Matrix([[0, 1, 2], [0, 1, 2], [0, 1, 2]])
214
+
215
+ def test_sign():
216
+ assert sign(1.2) == 1
217
+ assert sign(-1.2) == -1
218
+ assert sign(3*I) == I
219
+ assert sign(-3*I) == -I
220
+ assert sign(0) == 0
221
+ assert sign(0, evaluate=False).doit() == 0
222
+ assert sign(oo, evaluate=False).doit() == 1
223
+ assert sign(nan) is nan
224
+ assert sign(2 + 2*I).doit() == sqrt(2)*(2 + 2*I)/4
225
+ assert sign(2 + 3*I).simplify() == sign(2 + 3*I)
226
+ assert sign(2 + 2*I).simplify() == sign(1 + I)
227
+ assert sign(im(sqrt(1 - sqrt(3)))) == 1
228
+ assert sign(sqrt(1 - sqrt(3))) == I
229
+
230
+ x = Symbol('x')
231
+ assert sign(x).is_finite is True
232
+ assert sign(x).is_complex is True
233
+ assert sign(x).is_imaginary is None
234
+ assert sign(x).is_integer is None
235
+ assert sign(x).is_real is None
236
+ assert sign(x).is_zero is None
237
+ assert sign(x).doit() == sign(x)
238
+ assert sign(1.2*x) == sign(x)
239
+ assert sign(2*x) == sign(x)
240
+ assert sign(I*x) == I*sign(x)
241
+ assert sign(-2*I*x) == -I*sign(x)
242
+ assert sign(conjugate(x)) == conjugate(sign(x))
243
+
244
+ p = Symbol('p', positive=True)
245
+ n = Symbol('n', negative=True)
246
+ m = Symbol('m', negative=True)
247
+ assert sign(2*p*x) == sign(x)
248
+ assert sign(n*x) == -sign(x)
249
+ assert sign(n*m*x) == sign(x)
250
+
251
+ x = Symbol('x', imaginary=True)
252
+ assert sign(x).is_imaginary is True
253
+ assert sign(x).is_integer is False
254
+ assert sign(x).is_real is False
255
+ assert sign(x).is_zero is False
256
+ assert sign(x).diff(x) == 2*DiracDelta(-I*x)
257
+ assert sign(x).doit() == x / Abs(x)
258
+ assert conjugate(sign(x)) == -sign(x)
259
+
260
+ x = Symbol('x', real=True)
261
+ assert sign(x).is_imaginary is False
262
+ assert sign(x).is_integer is True
263
+ assert sign(x).is_real is True
264
+ assert sign(x).is_zero is None
265
+ assert sign(x).diff(x) == 2*DiracDelta(x)
266
+ assert sign(x).doit() == sign(x)
267
+ assert conjugate(sign(x)) == sign(x)
268
+
269
+ x = Symbol('x', nonzero=True)
270
+ assert sign(x).is_imaginary is False
271
+ assert sign(x).is_integer is True
272
+ assert sign(x).is_real is True
273
+ assert sign(x).is_zero is False
274
+ assert sign(x).doit() == x / Abs(x)
275
+ assert sign(Abs(x)) == 1
276
+ assert Abs(sign(x)) == 1
277
+
278
+ x = Symbol('x', positive=True)
279
+ assert sign(x).is_imaginary is False
280
+ assert sign(x).is_integer is True
281
+ assert sign(x).is_real is True
282
+ assert sign(x).is_zero is False
283
+ assert sign(x).doit() == x / Abs(x)
284
+ assert sign(Abs(x)) == 1
285
+ assert Abs(sign(x)) == 1
286
+
287
+ x = 0
288
+ assert sign(x).is_imaginary is False
289
+ assert sign(x).is_integer is True
290
+ assert sign(x).is_real is True
291
+ assert sign(x).is_zero is True
292
+ assert sign(x).doit() == 0
293
+ assert sign(Abs(x)) == 0
294
+ assert Abs(sign(x)) == 0
295
+
296
+ nz = Symbol('nz', nonzero=True, integer=True)
297
+ assert sign(nz).is_imaginary is False
298
+ assert sign(nz).is_integer is True
299
+ assert sign(nz).is_real is True
300
+ assert sign(nz).is_zero is False
301
+ assert sign(nz)**2 == 1
302
+ assert (sign(nz)**3).args == (sign(nz), 3)
303
+
304
+ assert sign(Symbol('x', nonnegative=True)).is_nonnegative
305
+ assert sign(Symbol('x', nonnegative=True)).is_nonpositive is None
306
+ assert sign(Symbol('x', nonpositive=True)).is_nonnegative is None
307
+ assert sign(Symbol('x', nonpositive=True)).is_nonpositive
308
+ assert sign(Symbol('x', real=True)).is_nonnegative is None
309
+ assert sign(Symbol('x', real=True)).is_nonpositive is None
310
+ assert sign(Symbol('x', real=True, zero=False)).is_nonpositive is None
311
+
312
+ x, y = Symbol('x', real=True), Symbol('y')
313
+ f = Function('f')
314
+ assert sign(x).rewrite(Piecewise) == \
315
+ Piecewise((1, x > 0), (-1, x < 0), (0, True))
316
+ assert sign(y).rewrite(Piecewise) == sign(y)
317
+ assert sign(x).rewrite(Heaviside) == 2*Heaviside(x, H0=S(1)/2) - 1
318
+ assert sign(y).rewrite(Heaviside) == sign(y)
319
+ assert sign(y).rewrite(Abs) == Piecewise((0, Eq(y, 0)), (y/Abs(y), True))
320
+ assert sign(f(y)).rewrite(Abs) == Piecewise((0, Eq(f(y), 0)), (f(y)/Abs(f(y)), True))
321
+
322
+ # evaluate what can be evaluated
323
+ assert sign(exp_polar(I*pi)*pi) is S.NegativeOne
324
+
325
+ eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
326
+ # if there is a fast way to know when and when you cannot prove an
327
+ # expression like this is zero then the equality to zero is ok
328
+ assert sign(eq).func is sign or sign(eq) == 0
329
+ # but sometimes it's hard to do this so it's better not to load
330
+ # abs down with tests that will be very slow
331
+ q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
332
+ p = expand(q**3)**Rational(1, 3)
333
+ d = p - q
334
+ assert sign(d).func is sign or sign(d) == 0
335
+
336
+
337
+ def test_as_real_imag():
338
+ n = pi**1000
339
+ # the special code for working out the real
340
+ # and complex parts of a power with Integer exponent
341
+ # should not run if there is no imaginary part, hence
342
+ # this should not hang
343
+ assert n.as_real_imag() == (n, 0)
344
+
345
+ # issue 6261
346
+ x = Symbol('x')
347
+ assert sqrt(x).as_real_imag() == \
348
+ ((re(x)**2 + im(x)**2)**Rational(1, 4)*cos(atan2(im(x), re(x))/2),
349
+ (re(x)**2 + im(x)**2)**Rational(1, 4)*sin(atan2(im(x), re(x))/2))
350
+
351
+ # issue 3853
352
+ a, b = symbols('a,b', real=True)
353
+ assert ((1 + sqrt(a + b*I))/2).as_real_imag() == \
354
+ (
355
+ (a**2 + b**2)**Rational(
356
+ 1, 4)*cos(atan2(b, a)/2)/2 + S.Half,
357
+ (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2)
358
+
359
+ assert sqrt(a**2).as_real_imag() == (sqrt(a**2), 0)
360
+ i = symbols('i', imaginary=True)
361
+ assert sqrt(i**2).as_real_imag() == (0, abs(i))
362
+
363
+ assert ((1 + I)/(1 - I)).as_real_imag() == (0, 1)
364
+ assert ((1 + I)**3/(1 - I)).as_real_imag() == (-2, 0)
365
+
366
+
367
+ @XFAIL
368
+ def test_sign_issue_3068():
369
+ n = pi**1000
370
+ i = int(n)
371
+ x = Symbol('x')
372
+ assert (n - i).round() == 1 # doesn't hang
373
+ assert sign(n - i) == 1
374
+ # perhaps it's not possible to get the sign right when
375
+ # only 1 digit is being requested for this situation;
376
+ # 2 digits works
377
+ assert (n - x).n(1, subs={x: i}) > 0
378
+ assert (n - x).n(2, subs={x: i}) > 0
379
+
380
+
381
+ def test_Abs():
382
+ raises(TypeError, lambda: Abs(Interval(2, 3))) # issue 8717
383
+
384
+ x, y = symbols('x,y')
385
+ assert sign(sign(x)) == sign(x)
386
+ assert sign(x*y).func is sign
387
+ assert Abs(0) == 0
388
+ assert Abs(1) == 1
389
+ assert Abs(-1) == 1
390
+ assert Abs(I) == 1
391
+ assert Abs(-I) == 1
392
+ assert Abs(nan) is nan
393
+ assert Abs(zoo) is oo
394
+ assert Abs(I * pi) == pi
395
+ assert Abs(-I * pi) == pi
396
+ assert Abs(I * x) == Abs(x)
397
+ assert Abs(-I * x) == Abs(x)
398
+ assert Abs(-2*x) == 2*Abs(x)
399
+ assert Abs(-2.0*x) == 2.0*Abs(x)
400
+ assert Abs(2*pi*x*y) == 2*pi*Abs(x*y)
401
+ assert Abs(conjugate(x)) == Abs(x)
402
+ assert conjugate(Abs(x)) == Abs(x)
403
+ assert Abs(x).expand(complex=True) == sqrt(re(x)**2 + im(x)**2)
404
+
405
+ a = Symbol('a', positive=True)
406
+ assert Abs(2*pi*x*a) == 2*pi*a*Abs(x)
407
+ assert Abs(2*pi*I*x*a) == 2*pi*a*Abs(x)
408
+
409
+ x = Symbol('x', real=True)
410
+ n = Symbol('n', integer=True)
411
+ assert Abs((-1)**n) == 1
412
+ assert x**(2*n) == Abs(x)**(2*n)
413
+ assert Abs(x).diff(x) == sign(x)
414
+ assert abs(x) == Abs(x) # Python built-in
415
+ assert Abs(x)**3 == x**2*Abs(x)
416
+ assert Abs(x)**4 == x**4
417
+ assert (
418
+ Abs(x)**(3*n)).args == (Abs(x), 3*n) # leave symbolic odd unchanged
419
+ assert (1/Abs(x)).args == (Abs(x), -1)
420
+ assert 1/Abs(x)**3 == 1/(x**2*Abs(x))
421
+ assert Abs(x)**-3 == Abs(x)/(x**4)
422
+ assert Abs(x**3) == x**2*Abs(x)
423
+ assert Abs(I**I) == exp(-pi/2)
424
+ assert Abs((4 + 5*I)**(6 + 7*I)) == 68921*exp(-7*atan(Rational(5, 4)))
425
+ y = Symbol('y', real=True)
426
+ assert Abs(I**y) == 1
427
+ y = Symbol('y')
428
+ assert Abs(I**y) == exp(-pi*im(y)/2)
429
+
430
+ x = Symbol('x', imaginary=True)
431
+ assert Abs(x).diff(x) == -sign(x)
432
+
433
+ eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
434
+ # if there is a fast way to know when you can and when you cannot prove an
435
+ # expression like this is zero then the equality to zero is ok
436
+ assert abs(eq).func is Abs or abs(eq) == 0
437
+ # but sometimes it's hard to do this so it's better not to load
438
+ # abs down with tests that will be very slow
439
+ q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
440
+ p = expand(q**3)**Rational(1, 3)
441
+ d = p - q
442
+ assert abs(d).func is Abs or abs(d) == 0
443
+
444
+ assert Abs(4*exp(pi*I/4)) == 4
445
+ assert Abs(3**(2 + I)) == 9
446
+ assert Abs((-3)**(1 - I)) == 3*exp(pi)
447
+
448
+ assert Abs(oo) is oo
449
+ assert Abs(-oo) is oo
450
+ assert Abs(oo + I) is oo
451
+ assert Abs(oo + I*oo) is oo
452
+
453
+ a = Symbol('a', algebraic=True)
454
+ t = Symbol('t', transcendental=True)
455
+ x = Symbol('x')
456
+ assert re(a).is_algebraic
457
+ assert re(x).is_algebraic is None
458
+ assert re(t).is_algebraic is False
459
+ assert Abs(x).fdiff() == sign(x)
460
+ raises(ArgumentIndexError, lambda: Abs(x).fdiff(2))
461
+
462
+ # doesn't have recursion error
463
+ arg = sqrt(acos(1 - I)*acos(1 + I))
464
+ assert abs(arg) == arg
465
+
466
+ # special handling to put Abs in denom
467
+ assert abs(1/x) == 1/Abs(x)
468
+ e = abs(2/x**2)
469
+ assert e.is_Mul and e == 2/Abs(x**2)
470
+ assert unchanged(Abs, y/x)
471
+ assert unchanged(Abs, x/(x + 1))
472
+ assert unchanged(Abs, x*y)
473
+ p = Symbol('p', positive=True)
474
+ assert abs(x/p) == abs(x)/p
475
+
476
+ # coverage
477
+ assert unchanged(Abs, Symbol('x', real=True)**y)
478
+ # issue 19627
479
+ f = Function('f', positive=True)
480
+ assert sqrt(f(x)**2) == f(x)
481
+ # issue 21625
482
+ assert unchanged(Abs, S("im(acos(-i + acosh(-g + i)))"))
483
+
484
+
485
+ def test_Abs_rewrite():
486
+ x = Symbol('x', real=True)
487
+ a = Abs(x).rewrite(Heaviside).expand()
488
+ assert a == x*Heaviside(x) - x*Heaviside(-x)
489
+ for i in [-2, -1, 0, 1, 2]:
490
+ assert a.subs(x, i) == abs(i)
491
+ y = Symbol('y')
492
+ assert Abs(y).rewrite(Heaviside) == Abs(y)
493
+
494
+ x, y = Symbol('x', real=True), Symbol('y')
495
+ assert Abs(x).rewrite(Piecewise) == Piecewise((x, x >= 0), (-x, True))
496
+ assert Abs(y).rewrite(Piecewise) == Abs(y)
497
+ assert Abs(y).rewrite(sign) == y/sign(y)
498
+
499
+ i = Symbol('i', imaginary=True)
500
+ assert abs(i).rewrite(Piecewise) == Piecewise((I*i, I*i >= 0), (-I*i, True))
501
+
502
+
503
+ assert Abs(y).rewrite(conjugate) == sqrt(y*conjugate(y))
504
+ assert Abs(i).rewrite(conjugate) == sqrt(-i**2) # == -I*i
505
+
506
+ y = Symbol('y', extended_real=True)
507
+ assert (Abs(exp(-I*x)-exp(-I*y))**2).rewrite(conjugate) == \
508
+ -exp(I*x)*exp(-I*y) + 2 - exp(-I*x)*exp(I*y)
509
+
510
+
511
+ def test_Abs_real():
512
+ # test some properties of abs that only apply
513
+ # to real numbers
514
+ x = Symbol('x', complex=True)
515
+ assert sqrt(x**2) != Abs(x)
516
+ assert Abs(x**2) != x**2
517
+
518
+ x = Symbol('x', real=True)
519
+ assert sqrt(x**2) == Abs(x)
520
+ assert Abs(x**2) == x**2
521
+
522
+ # if the symbol is zero, the following will still apply
523
+ nn = Symbol('nn', nonnegative=True, real=True)
524
+ np = Symbol('np', nonpositive=True, real=True)
525
+ assert Abs(nn) == nn
526
+ assert Abs(np) == -np
527
+
528
+
529
+ def test_Abs_properties():
530
+ x = Symbol('x')
531
+ assert Abs(x).is_real is None
532
+ assert Abs(x).is_extended_real is True
533
+ assert Abs(x).is_rational is None
534
+ assert Abs(x).is_positive is None
535
+ assert Abs(x).is_nonnegative is None
536
+ assert Abs(x).is_extended_positive is None
537
+ assert Abs(x).is_extended_nonnegative is True
538
+
539
+ f = Symbol('x', finite=True)
540
+ assert Abs(f).is_real is True
541
+ assert Abs(f).is_extended_real is True
542
+ assert Abs(f).is_rational is None
543
+ assert Abs(f).is_positive is None
544
+ assert Abs(f).is_nonnegative is True
545
+ assert Abs(f).is_extended_positive is None
546
+ assert Abs(f).is_extended_nonnegative is True
547
+
548
+ z = Symbol('z', complex=True, zero=False)
549
+ assert Abs(z).is_real is True # since complex implies finite
550
+ assert Abs(z).is_extended_real is True
551
+ assert Abs(z).is_rational is None
552
+ assert Abs(z).is_positive is True
553
+ assert Abs(z).is_extended_positive is True
554
+ assert Abs(z).is_zero is False
555
+
556
+ p = Symbol('p', positive=True)
557
+ assert Abs(p).is_real is True
558
+ assert Abs(p).is_extended_real is True
559
+ assert Abs(p).is_rational is None
560
+ assert Abs(p).is_positive is True
561
+ assert Abs(p).is_zero is False
562
+
563
+ q = Symbol('q', rational=True)
564
+ assert Abs(q).is_real is True
565
+ assert Abs(q).is_rational is True
566
+ assert Abs(q).is_integer is None
567
+ assert Abs(q).is_positive is None
568
+ assert Abs(q).is_nonnegative is True
569
+
570
+ i = Symbol('i', integer=True)
571
+ assert Abs(i).is_real is True
572
+ assert Abs(i).is_integer is True
573
+ assert Abs(i).is_positive is None
574
+ assert Abs(i).is_nonnegative is True
575
+
576
+ e = Symbol('n', even=True)
577
+ ne = Symbol('ne', real=True, even=False)
578
+ assert Abs(e).is_even is True
579
+ assert Abs(ne).is_even is False
580
+ assert Abs(i).is_even is None
581
+
582
+ o = Symbol('n', odd=True)
583
+ no = Symbol('no', real=True, odd=False)
584
+ assert Abs(o).is_odd is True
585
+ assert Abs(no).is_odd is False
586
+ assert Abs(i).is_odd is None
587
+
588
+
589
+ def test_abs():
590
+ # this tests that abs calls Abs; don't rename to
591
+ # test_Abs since that test is already above
592
+ a = Symbol('a', positive=True)
593
+ assert abs(I*(1 + a)**2) == (1 + a)**2
594
+
595
+
596
+ def test_arg():
597
+ assert arg(0) is nan
598
+ assert arg(1) == 0
599
+ assert arg(-1) == pi
600
+ assert arg(I) == pi/2
601
+ assert arg(-I) == -pi/2
602
+ assert arg(1 + I) == pi/4
603
+ assert arg(-1 + I) == pi*Rational(3, 4)
604
+ assert arg(1 - I) == -pi/4
605
+ assert arg(exp_polar(4*pi*I)) == 4*pi
606
+ assert arg(exp_polar(-7*pi*I)) == -7*pi
607
+ assert arg(exp_polar(5 - 3*pi*I/4)) == pi*Rational(-3, 4)
608
+ f = Function('f')
609
+ assert not arg(f(0) + I*f(1)).atoms(re)
610
+
611
+ # check nesting
612
+ x = Symbol('x')
613
+ assert arg(arg(arg(x))) is not S.NaN
614
+ assert arg(arg(arg(arg(x)))) is S.NaN
615
+ r = Symbol('r', extended_real=True)
616
+ assert arg(arg(r)) is not S.NaN
617
+ assert arg(arg(arg(r))) is S.NaN
618
+
619
+ p = Function('p', extended_positive=True)
620
+ assert arg(p(x)) == 0
621
+ assert arg((3 + I)*p(x)) == arg(3 + I)
622
+
623
+ p = Symbol('p', positive=True)
624
+ assert arg(p) == 0
625
+ assert arg(p*I) == pi/2
626
+
627
+ n = Symbol('n', negative=True)
628
+ assert arg(n) == pi
629
+ assert arg(n*I) == -pi/2
630
+
631
+ x = Symbol('x')
632
+ assert conjugate(arg(x)) == arg(x)
633
+
634
+ e = p + I*p**2
635
+ assert arg(e) == arg(1 + p*I)
636
+ # make sure sign doesn't swap
637
+ e = -2*p + 4*I*p**2
638
+ assert arg(e) == arg(-1 + 2*p*I)
639
+ # make sure sign isn't lost
640
+ x = symbols('x', real=True) # could be zero
641
+ e = x + I*x
642
+ assert arg(e) == arg(x*(1 + I))
643
+ assert arg(e/p) == arg(x*(1 + I))
644
+ e = p*cos(p) + I*log(p)*exp(p)
645
+ assert arg(e).args[0] == e
646
+ # keep it simple -- let the user do more advanced cancellation
647
+ e = (p + 1) + I*(p**2 - 1)
648
+ assert arg(e).args[0] == e
649
+
650
+ f = Function('f')
651
+ e = 2*x*(f(0) - 1) - 2*x*f(0)
652
+ assert arg(e) == arg(-2*x)
653
+ assert arg(f(0)).func == arg and arg(f(0)).args == (f(0),)
654
+
655
+
656
+ def test_arg_rewrite():
657
+ assert arg(1 + I) == atan2(1, 1)
658
+
659
+ x = Symbol('x', real=True)
660
+ y = Symbol('y', real=True)
661
+ assert arg(x + I*y).rewrite(atan2) == atan2(y, x)
662
+
663
+
664
+ def test_adjoint():
665
+ a = Symbol('a', antihermitian=True)
666
+ b = Symbol('b', hermitian=True)
667
+ assert adjoint(a) == -a
668
+ assert adjoint(I*a) == I*a
669
+ assert adjoint(b) == b
670
+ assert adjoint(I*b) == -I*b
671
+ assert adjoint(a*b) == -b*a
672
+ assert adjoint(I*a*b) == I*b*a
673
+
674
+ x, y = symbols('x y')
675
+ assert adjoint(adjoint(x)) == x
676
+ assert adjoint(x + y) == adjoint(x) + adjoint(y)
677
+ assert adjoint(x - y) == adjoint(x) - adjoint(y)
678
+ assert adjoint(x * y) == adjoint(x) * adjoint(y)
679
+ assert adjoint(x / y) == adjoint(x) / adjoint(y)
680
+ assert adjoint(-x) == -adjoint(x)
681
+
682
+ x, y = symbols('x y', commutative=False)
683
+ assert adjoint(adjoint(x)) == x
684
+ assert adjoint(x + y) == adjoint(x) + adjoint(y)
685
+ assert adjoint(x - y) == adjoint(x) - adjoint(y)
686
+ assert adjoint(x * y) == adjoint(y) * adjoint(x)
687
+ assert adjoint(x / y) == 1 / adjoint(y) * adjoint(x)
688
+ assert adjoint(-x) == -adjoint(x)
689
+
690
+
691
+ def test_conjugate():
692
+ a = Symbol('a', real=True)
693
+ b = Symbol('b', imaginary=True)
694
+ assert conjugate(a) == a
695
+ assert conjugate(I*a) == -I*a
696
+ assert conjugate(b) == -b
697
+ assert conjugate(I*b) == I*b
698
+ assert conjugate(a*b) == -a*b
699
+ assert conjugate(I*a*b) == I*a*b
700
+
701
+ x, y = symbols('x y')
702
+ assert conjugate(conjugate(x)) == x
703
+ assert conjugate(x).inverse() == conjugate
704
+ assert conjugate(x + y) == conjugate(x) + conjugate(y)
705
+ assert conjugate(x - y) == conjugate(x) - conjugate(y)
706
+ assert conjugate(x * y) == conjugate(x) * conjugate(y)
707
+ assert conjugate(x / y) == conjugate(x) / conjugate(y)
708
+ assert conjugate(-x) == -conjugate(x)
709
+
710
+ a = Symbol('a', algebraic=True)
711
+ t = Symbol('t', transcendental=True)
712
+ assert re(a).is_algebraic
713
+ assert re(x).is_algebraic is None
714
+ assert re(t).is_algebraic is False
715
+
716
+
717
+ def test_conjugate_transpose():
718
+ x = Symbol('x')
719
+ assert conjugate(transpose(x)) == adjoint(x)
720
+ assert transpose(conjugate(x)) == adjoint(x)
721
+ assert adjoint(transpose(x)) == conjugate(x)
722
+ assert transpose(adjoint(x)) == conjugate(x)
723
+ assert adjoint(conjugate(x)) == transpose(x)
724
+ assert conjugate(adjoint(x)) == transpose(x)
725
+
726
+ class Symmetric(Expr):
727
+ def _eval_adjoint(self):
728
+ return None
729
+
730
+ def _eval_conjugate(self):
731
+ return None
732
+
733
+ def _eval_transpose(self):
734
+ return self
735
+ x = Symmetric()
736
+ assert conjugate(x) == adjoint(x)
737
+ assert transpose(x) == x
738
+
739
+
740
+ def test_transpose():
741
+ a = Symbol('a', complex=True)
742
+ assert transpose(a) == a
743
+ assert transpose(I*a) == I*a
744
+
745
+ x, y = symbols('x y')
746
+ assert transpose(transpose(x)) == x
747
+ assert transpose(x + y) == transpose(x) + transpose(y)
748
+ assert transpose(x - y) == transpose(x) - transpose(y)
749
+ assert transpose(x * y) == transpose(x) * transpose(y)
750
+ assert transpose(x / y) == transpose(x) / transpose(y)
751
+ assert transpose(-x) == -transpose(x)
752
+
753
+ x, y = symbols('x y', commutative=False)
754
+ assert transpose(transpose(x)) == x
755
+ assert transpose(x + y) == transpose(x) + transpose(y)
756
+ assert transpose(x - y) == transpose(x) - transpose(y)
757
+ assert transpose(x * y) == transpose(y) * transpose(x)
758
+ assert transpose(x / y) == 1 / transpose(y) * transpose(x)
759
+ assert transpose(-x) == -transpose(x)
760
+
761
+
762
+ @_both_exp_pow
763
+ def test_polarify():
764
+ from sympy.functions.elementary.complexes import (polar_lift, polarify)
765
+ x = Symbol('x')
766
+ z = Symbol('z', polar=True)
767
+ f = Function('f')
768
+ ES = {}
769
+
770
+ assert polarify(-1) == (polar_lift(-1), ES)
771
+ assert polarify(1 + I) == (polar_lift(1 + I), ES)
772
+
773
+ assert polarify(exp(x), subs=False) == exp(x)
774
+ assert polarify(1 + x, subs=False) == 1 + x
775
+ assert polarify(f(I) + x, subs=False) == f(polar_lift(I)) + x
776
+
777
+ assert polarify(x, lift=True) == polar_lift(x)
778
+ assert polarify(z, lift=True) == z
779
+ assert polarify(f(x), lift=True) == f(polar_lift(x))
780
+ assert polarify(1 + x, lift=True) == polar_lift(1 + x)
781
+ assert polarify(1 + f(x), lift=True) == polar_lift(1 + f(polar_lift(x)))
782
+
783
+ newex, subs = polarify(f(x) + z)
784
+ assert newex.subs(subs) == f(x) + z
785
+
786
+ mu = Symbol("mu")
787
+ sigma = Symbol("sigma", positive=True)
788
+
789
+ # Make sure polarify(lift=True) doesn't try to lift the integration
790
+ # variable
791
+ assert polarify(
792
+ Integral(sqrt(2)*x*exp(-(-mu + x)**2/(2*sigma**2))/(2*sqrt(pi)*sigma),
793
+ (x, -oo, oo)), lift=True) == Integral(sqrt(2)*(sigma*exp_polar(0))**exp_polar(I*pi)*
794
+ exp((sigma*exp_polar(0))**(2*exp_polar(I*pi))*exp_polar(I*pi)*polar_lift(-mu + x)**
795
+ (2*exp_polar(0))/2)*exp_polar(0)*polar_lift(x)/(2*sqrt(pi)), (x, -oo, oo))
796
+
797
+
798
+ def test_unpolarify():
799
+ from sympy.functions.elementary.complexes import (polar_lift, principal_branch, unpolarify)
800
+ from sympy.core.relational import Ne
801
+ from sympy.functions.elementary.hyperbolic import tanh
802
+ from sympy.functions.special.error_functions import erf
803
+ from sympy.functions.special.gamma_functions import (gamma, uppergamma)
804
+ from sympy.abc import x
805
+ p = exp_polar(7*I) + 1
806
+ u = exp(7*I) + 1
807
+
808
+ assert unpolarify(1) == 1
809
+ assert unpolarify(p) == u
810
+ assert unpolarify(p**2) == u**2
811
+ assert unpolarify(p**x) == p**x
812
+ assert unpolarify(p*x) == u*x
813
+ assert unpolarify(p + x) == u + x
814
+ assert unpolarify(sqrt(sin(p))) == sqrt(sin(u))
815
+
816
+ # Test reduction to principal branch 2*pi.
817
+ t = principal_branch(x, 2*pi)
818
+ assert unpolarify(t) == x
819
+ assert unpolarify(sqrt(t)) == sqrt(t)
820
+
821
+ # Test exponents_only.
822
+ assert unpolarify(p**p, exponents_only=True) == p**u
823
+ assert unpolarify(uppergamma(x, p**p)) == uppergamma(x, p**u)
824
+
825
+ # Test functions.
826
+ assert unpolarify(sin(p)) == sin(u)
827
+ assert unpolarify(tanh(p)) == tanh(u)
828
+ assert unpolarify(gamma(p)) == gamma(u)
829
+ assert unpolarify(erf(p)) == erf(u)
830
+ assert unpolarify(uppergamma(x, p)) == uppergamma(x, p)
831
+
832
+ assert unpolarify(uppergamma(sin(p), sin(p + exp_polar(0)))) == \
833
+ uppergamma(sin(u), sin(u + 1))
834
+ assert unpolarify(uppergamma(polar_lift(0), 2*exp_polar(0))) == \
835
+ uppergamma(0, 2)
836
+
837
+ assert unpolarify(Eq(p, 0)) == Eq(u, 0)
838
+ assert unpolarify(Ne(p, 0)) == Ne(u, 0)
839
+ assert unpolarify(polar_lift(x) > 0) == (x > 0)
840
+
841
+ # Test bools
842
+ assert unpolarify(True) is True
843
+
844
+
845
+ def test_issue_4035():
846
+ x = Symbol('x')
847
+ assert Abs(x).expand(trig=True) == Abs(x)
848
+ assert sign(x).expand(trig=True) == sign(x)
849
+ assert arg(x).expand(trig=True) == arg(x)
850
+
851
+
852
+ def test_issue_3206():
853
+ x = Symbol('x')
854
+ assert Abs(Abs(x)) == Abs(x)
855
+
856
+
857
+ def test_issue_4754_derivative_conjugate():
858
+ x = Symbol('x', real=True)
859
+ y = Symbol('y', imaginary=True)
860
+ f = Function('f')
861
+ assert (f(x).conjugate()).diff(x) == (f(x).diff(x)).conjugate()
862
+ assert (f(y).conjugate()).diff(y) == -(f(y).diff(y)).conjugate()
863
+
864
+
865
+ def test_derivatives_issue_4757():
866
+ x = Symbol('x', real=True)
867
+ y = Symbol('y', imaginary=True)
868
+ f = Function('f')
869
+ assert re(f(x)).diff(x) == re(f(x).diff(x))
870
+ assert im(f(x)).diff(x) == im(f(x).diff(x))
871
+ assert re(f(y)).diff(y) == -I*im(f(y).diff(y))
872
+ assert im(f(y)).diff(y) == -I*re(f(y).diff(y))
873
+ assert Abs(f(x)).diff(x).subs(f(x), 1 + I*x).doit() == x/sqrt(1 + x**2)
874
+ assert arg(f(x)).diff(x).subs(f(x), 1 + I*x**2).doit() == 2*x/(1 + x**4)
875
+ assert Abs(f(y)).diff(y).subs(f(y), 1 + y).doit() == -y/sqrt(1 - y**2)
876
+ assert arg(f(y)).diff(y).subs(f(y), I + y**2).doit() == 2*y/(1 + y**4)
877
+
878
+
879
+ def test_issue_11413():
880
+ from sympy.simplify.simplify import simplify
881
+ v0 = Symbol('v0')
882
+ v1 = Symbol('v1')
883
+ v2 = Symbol('v2')
884
+ V = Matrix([[v0],[v1],[v2]])
885
+ U = V.normalized()
886
+ assert U == Matrix([
887
+ [v0/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
888
+ [v1/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
889
+ [v2/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)]])
890
+ U.norm = sqrt(v0**2/(v0**2 + v1**2 + v2**2) + v1**2/(v0**2 + v1**2 + v2**2) + v2**2/(v0**2 + v1**2 + v2**2))
891
+ assert simplify(U.norm) == 1
892
+
893
+
894
+ def test_periodic_argument():
895
+ from sympy.functions.elementary.complexes import (periodic_argument, polar_lift, principal_branch, unbranched_argument)
896
+ x = Symbol('x')
897
+ p = Symbol('p', positive=True)
898
+
899
+ assert unbranched_argument(2 + I) == periodic_argument(2 + I, oo)
900
+ assert unbranched_argument(1 + x) == periodic_argument(1 + x, oo)
901
+ assert N_equals(unbranched_argument((1 + I)**2), pi/2)
902
+ assert N_equals(unbranched_argument((1 - I)**2), -pi/2)
903
+ assert N_equals(periodic_argument((1 + I)**2, 3*pi), pi/2)
904
+ assert N_equals(periodic_argument((1 - I)**2, 3*pi), -pi/2)
905
+
906
+ assert unbranched_argument(principal_branch(x, pi)) == \
907
+ periodic_argument(x, pi)
908
+
909
+ assert unbranched_argument(polar_lift(2 + I)) == unbranched_argument(2 + I)
910
+ assert periodic_argument(polar_lift(2 + I), 2*pi) == \
911
+ periodic_argument(2 + I, 2*pi)
912
+ assert periodic_argument(polar_lift(2 + I), 3*pi) == \
913
+ periodic_argument(2 + I, 3*pi)
914
+ assert periodic_argument(polar_lift(2 + I), pi) == \
915
+ periodic_argument(polar_lift(2 + I), pi)
916
+
917
+ assert unbranched_argument(polar_lift(1 + I)) == pi/4
918
+ assert periodic_argument(2*p, p) == periodic_argument(p, p)
919
+ assert periodic_argument(pi*p, p) == periodic_argument(p, p)
920
+
921
+ assert Abs(polar_lift(1 + I)) == Abs(1 + I)
922
+
923
+
924
+ @XFAIL
925
+ def test_principal_branch_fail():
926
+ # TODO XXX why does abs(x)._eval_evalf() not fall back to global evalf?
927
+ from sympy.functions.elementary.complexes import principal_branch
928
+ assert N_equals(principal_branch((1 + I)**2, pi/2), 0)
929
+
930
+
931
+ def test_principal_branch():
932
+ from sympy.functions.elementary.complexes import (polar_lift, principal_branch)
933
+ p = Symbol('p', positive=True)
934
+ x = Symbol('x')
935
+ neg = Symbol('x', negative=True)
936
+
937
+ assert principal_branch(polar_lift(x), p) == principal_branch(x, p)
938
+ assert principal_branch(polar_lift(2 + I), p) == principal_branch(2 + I, p)
939
+ assert principal_branch(2*x, p) == 2*principal_branch(x, p)
940
+ assert principal_branch(1, pi) == exp_polar(0)
941
+ assert principal_branch(-1, 2*pi) == exp_polar(I*pi)
942
+ assert principal_branch(-1, pi) == exp_polar(0)
943
+ assert principal_branch(exp_polar(3*pi*I)*x, 2*pi) == \
944
+ principal_branch(exp_polar(I*pi)*x, 2*pi)
945
+ assert principal_branch(neg*exp_polar(pi*I), 2*pi) == neg*exp_polar(-I*pi)
946
+ # related to issue #14692
947
+ assert principal_branch(exp_polar(-I*pi/2)/polar_lift(neg), 2*pi) == \
948
+ exp_polar(-I*pi/2)/neg
949
+
950
+ assert N_equals(principal_branch((1 + I)**2, 2*pi), 2*I)
951
+ assert N_equals(principal_branch((1 + I)**2, 3*pi), 2*I)
952
+ assert N_equals(principal_branch((1 + I)**2, 1*pi), 2*I)
953
+
954
+ # test argument sanitization
955
+ assert principal_branch(x, I).func is principal_branch
956
+ assert principal_branch(x, -4).func is principal_branch
957
+ assert principal_branch(x, -oo).func is principal_branch
958
+ assert principal_branch(x, zoo).func is principal_branch
959
+
960
+
961
+ @XFAIL
962
+ def test_issue_6167_6151():
963
+ n = pi**1000
964
+ i = int(n)
965
+ assert sign(n - i) == 1
966
+ assert abs(n - i) == n - i
967
+ x = Symbol('x')
968
+ eps = pi**-1500
969
+ big = pi**1000
970
+ one = cos(x)**2 + sin(x)**2
971
+ e = big*one - big + eps
972
+ from sympy.simplify.simplify import simplify
973
+ assert sign(simplify(e)) == 1
974
+ for xi in (111, 11, 1, Rational(1, 10)):
975
+ assert sign(e.subs(x, xi)) == 1
976
+
977
+
978
+ def test_issue_14216():
979
+ from sympy.functions.elementary.complexes import unpolarify
980
+ A = MatrixSymbol("A", 2, 2)
981
+ assert unpolarify(A[0, 0]) == A[0, 0]
982
+ assert unpolarify(A[0, 0]*A[1, 0]) == A[0, 0]*A[1, 0]
983
+
984
+
985
+ def test_issue_14238():
986
+ # doesn't cause recursion error
987
+ r = Symbol('r', real=True)
988
+ assert Abs(r + Piecewise((0, r > 0), (1 - r, True)))
989
+
990
+
991
+ def test_issue_22189():
992
+ x = Symbol('x')
993
+ for a in (sqrt(7 - 2*x) - 2, 1 - x):
994
+ assert Abs(a) - Abs(-a) == 0, a
995
+
996
+
997
+ def test_zero_assumptions():
998
+ nr = Symbol('nonreal', real=False, finite=True)
999
+ ni = Symbol('nonimaginary', imaginary=False)
1000
+ # imaginary implies not zero
1001
+ nzni = Symbol('nonzerononimaginary', zero=False, imaginary=False)
1002
+
1003
+ assert re(nr).is_zero is None
1004
+ assert im(nr).is_zero is False
1005
+
1006
+ assert re(ni).is_zero is None
1007
+ assert im(ni).is_zero is None
1008
+
1009
+ assert re(nzni).is_zero is False
1010
+ assert im(nzni).is_zero is None
1011
+
1012
+
1013
+ @_both_exp_pow
1014
+ def test_issue_15893():
1015
+ f = Function('f', real=True)
1016
+ x = Symbol('x', real=True)
1017
+ eq = Derivative(Abs(f(x)), f(x))
1018
+ assert eq.doit() == sign(f(x))
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_exponential.py ADDED
@@ -0,0 +1,806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions.refine import refine
2
+ from sympy.calculus.accumulationbounds import AccumBounds
3
+ from sympy.concrete.products import Product
4
+ from sympy.concrete.summations import Sum
5
+ from sympy.core.function import expand_log
6
+ from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
7
+ from sympy.core.power import Pow
8
+ from sympy.core.singleton import S
9
+ from sympy.core.symbol import (Symbol, symbols)
10
+ from sympy.functions.elementary.complexes import (adjoint, conjugate, re, sign, transpose)
11
+ from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log)
12
+ from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh)
13
+ from sympy.functions.elementary.miscellaneous import sqrt
14
+ from sympy.functions.elementary.trigonometric import (cos, sin, tan)
15
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
16
+ from sympy.polys.polytools import gcd
17
+ from sympy.series.order import O
18
+ from sympy.simplify.simplify import simplify
19
+ from sympy.core.parameters import global_parameters
20
+ from sympy.functions.elementary.exponential import match_real_imag
21
+ from sympy.abc import x, y, z
22
+ from sympy.core.expr import unchanged
23
+ from sympy.core.function import ArgumentIndexError
24
+ from sympy.testing.pytest import raises, XFAIL, _both_exp_pow
25
+
26
+
27
+ @_both_exp_pow
28
+ def test_exp_values():
29
+ if global_parameters.exp_is_pow:
30
+ assert type(exp(x)) is Pow
31
+ else:
32
+ assert type(exp(x)) is exp
33
+
34
+ k = Symbol('k', integer=True)
35
+
36
+ assert exp(nan) is nan
37
+
38
+ assert exp(oo) is oo
39
+ assert exp(-oo) == 0
40
+
41
+ assert exp(0) == 1
42
+ assert exp(1) == E
43
+ assert exp(-1 + x).as_base_exp() == (S.Exp1, x - 1)
44
+ assert exp(1 + x).as_base_exp() == (S.Exp1, x + 1)
45
+
46
+ assert exp(pi*I/2) == I
47
+ assert exp(pi*I) == -1
48
+ assert exp(pi*I*Rational(3, 2)) == -I
49
+ assert exp(2*pi*I) == 1
50
+
51
+ assert refine(exp(pi*I*2*k)) == 1
52
+ assert refine(exp(pi*I*2*(k + S.Half))) == -1
53
+ assert refine(exp(pi*I*2*(k + Rational(1, 4)))) == I
54
+ assert refine(exp(pi*I*2*(k + Rational(3, 4)))) == -I
55
+
56
+ assert exp(log(x)) == x
57
+ assert exp(2*log(x)) == x**2
58
+ assert exp(pi*log(x)) == x**pi
59
+
60
+ assert exp(17*log(x) + E*log(y)) == x**17 * y**E
61
+
62
+ assert exp(x*log(x)) != x**x
63
+ assert exp(sin(x)*log(x)) != x
64
+
65
+ assert exp(3*log(x) + oo*x) == exp(oo*x) * x**3
66
+ assert exp(4*log(x)*log(y) + 3*log(x)) == x**3 * exp(4*log(x)*log(y))
67
+
68
+ assert exp(-oo, evaluate=False).is_finite is True
69
+ assert exp(oo, evaluate=False).is_finite is False
70
+
71
+
72
+ @_both_exp_pow
73
+ def test_exp_period():
74
+ assert exp(I*pi*Rational(9, 4)) == exp(I*pi/4)
75
+ assert exp(I*pi*Rational(46, 18)) == exp(I*pi*Rational(5, 9))
76
+ assert exp(I*pi*Rational(25, 7)) == exp(I*pi*Rational(-3, 7))
77
+ assert exp(I*pi*Rational(-19, 3)) == exp(-I*pi/3)
78
+ assert exp(I*pi*Rational(37, 8)) - exp(I*pi*Rational(-11, 8)) == 0
79
+ assert exp(I*pi*Rational(-5, 3)) / exp(I*pi*Rational(11, 5)) * exp(I*pi*Rational(148, 15)) == 1
80
+
81
+ assert exp(2 - I*pi*Rational(17, 5)) == exp(2 + I*pi*Rational(3, 5))
82
+ assert exp(log(3) + I*pi*Rational(29, 9)) == 3 * exp(I*pi*Rational(-7, 9))
83
+
84
+ n = Symbol('n', integer=True)
85
+ e = Symbol('e', even=True)
86
+ assert exp(e*I*pi) == 1
87
+ assert exp((e + 1)*I*pi) == -1
88
+ assert exp((1 + 4*n)*I*pi/2) == I
89
+ assert exp((-1 + 4*n)*I*pi/2) == -I
90
+
91
+
92
+ @_both_exp_pow
93
+ def test_exp_log():
94
+ x = Symbol("x", real=True)
95
+ assert log(exp(x)) == x
96
+ assert exp(log(x)) == x
97
+
98
+ if not global_parameters.exp_is_pow:
99
+ assert log(x).inverse() == exp
100
+ assert exp(x).inverse() == log
101
+
102
+ y = Symbol("y", polar=True)
103
+ assert log(exp_polar(z)) == z
104
+ assert exp(log(y)) == y
105
+
106
+
107
+ @_both_exp_pow
108
+ def test_exp_expand():
109
+ e = exp(log(Rational(2))*(1 + x) - log(Rational(2))*x)
110
+ assert e.expand() == 2
111
+ assert exp(x + y) != exp(x)*exp(y)
112
+ assert exp(x + y).expand() == exp(x)*exp(y)
113
+
114
+
115
+ @_both_exp_pow
116
+ def test_exp__as_base_exp():
117
+ assert exp(x).as_base_exp() == (E, x)
118
+ assert exp(2*x).as_base_exp() == (E, 2*x)
119
+ assert exp(x*y).as_base_exp() == (E, x*y)
120
+ assert exp(-x).as_base_exp() == (E, -x)
121
+
122
+ # Pow( *expr.as_base_exp() ) == expr invariant should hold
123
+ assert E**x == exp(x)
124
+ assert E**(2*x) == exp(2*x)
125
+ assert E**(x*y) == exp(x*y)
126
+
127
+ assert exp(x).base is S.Exp1
128
+ assert exp(x).exp == x
129
+
130
+
131
+ @_both_exp_pow
132
+ def test_exp_infinity():
133
+ assert exp(I*y) != nan
134
+ assert refine(exp(I*oo)) is nan
135
+ assert refine(exp(-I*oo)) is nan
136
+ assert exp(y*I*oo) != nan
137
+ assert exp(zoo) is nan
138
+ x = Symbol('x', extended_real=True, finite=False)
139
+ assert exp(x).is_complex is None
140
+
141
+
142
+ @_both_exp_pow
143
+ def test_exp_subs():
144
+ x = Symbol('x')
145
+ e = (exp(3*log(x), evaluate=False)) # evaluates to x**3
146
+ assert e.subs(x**3, y**3) == e
147
+ assert e.subs(x**2, 5) == e
148
+ assert (x**3).subs(x**2, y) != y**Rational(3, 2)
149
+ assert exp(exp(x) + exp(x**2)).subs(exp(exp(x)), y) == y * exp(exp(x**2))
150
+ assert exp(x).subs(E, y) == y**x
151
+ x = symbols('x', real=True)
152
+ assert exp(5*x).subs(exp(7*x), y) == y**Rational(5, 7)
153
+ assert exp(2*x + 7).subs(exp(3*x), y) == y**Rational(2, 3) * exp(7)
154
+ x = symbols('x', positive=True)
155
+ assert exp(3*log(x)).subs(x**2, y) == y**Rational(3, 2)
156
+ # differentiate between E and exp
157
+ assert exp(exp(x + E)).subs(exp, 3) == 3**(3**(x + E))
158
+ assert exp(exp(x + E)).subs(exp, sin) == sin(sin(x + E))
159
+ assert exp(exp(x + E)).subs(E, 3) == 3**(3**(x + 3))
160
+ assert exp(3).subs(E, sin) == sin(3)
161
+
162
+
163
+ def test_exp_adjoint():
164
+ assert adjoint(exp(x)) == exp(adjoint(x))
165
+
166
+
167
+ def test_exp_conjugate():
168
+ assert conjugate(exp(x)) == exp(conjugate(x))
169
+
170
+
171
+ @_both_exp_pow
172
+ def test_exp_transpose():
173
+ assert transpose(exp(x)) == exp(transpose(x))
174
+
175
+
176
+ @_both_exp_pow
177
+ def test_exp_rewrite():
178
+ assert exp(x).rewrite(sin) == sinh(x) + cosh(x)
179
+ assert exp(x*I).rewrite(cos) == cos(x) + I*sin(x)
180
+ assert exp(1).rewrite(cos) == sinh(1) + cosh(1)
181
+ assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
182
+ assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
183
+ assert exp(x).rewrite(tanh) == (1 + tanh(x/2))/(1 - tanh(x/2))
184
+ assert exp(pi*I/4).rewrite(sqrt) == sqrt(2)/2 + sqrt(2)*I/2
185
+ assert exp(pi*I/3).rewrite(sqrt) == S.Half + sqrt(3)*I/2
186
+ if not global_parameters.exp_is_pow:
187
+ assert exp(x*log(y)).rewrite(Pow) == y**x
188
+ assert exp(log(x)*log(y)).rewrite(Pow) in [x**log(y), y**log(x)]
189
+ assert exp(log(log(x))*y).rewrite(Pow) == log(x)**y
190
+
191
+ n = Symbol('n', integer=True)
192
+
193
+ assert Sum((exp(pi*I/2)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == Rational(4, 5) + I*2/5
194
+ assert Sum((exp(pi*I/4)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == 1/(1 - sqrt(2)*(1 + I)/4)
195
+ assert (Sum((exp(pi*I/3)/2)**n, (n, 0, oo)).rewrite(sqrt).doit().cancel()
196
+ == 4*I/(sqrt(3) + 3*I))
197
+
198
+
199
+ @_both_exp_pow
200
+ def test_exp_leading_term():
201
+ assert exp(x).as_leading_term(x) == 1
202
+ assert exp(2 + x).as_leading_term(x) == exp(2)
203
+ assert exp((2*x + 3) / (x+1)).as_leading_term(x) == exp(3)
204
+
205
+ # The following tests are commented, since now SymPy returns the
206
+ # original function when the leading term in the series expansion does
207
+ # not exist.
208
+ # raises(NotImplementedError, lambda: exp(1/x).as_leading_term(x))
209
+ # raises(NotImplementedError, lambda: exp((x + 1) / x**2).as_leading_term(x))
210
+ # raises(NotImplementedError, lambda: exp(x + 1/x).as_leading_term(x))
211
+
212
+
213
+ @_both_exp_pow
214
+ def test_exp_taylor_term():
215
+ x = symbols('x')
216
+ assert exp(x).taylor_term(1, x) == x
217
+ assert exp(x).taylor_term(3, x) == x**3/6
218
+ assert exp(x).taylor_term(4, x) == x**4/24
219
+ assert exp(x).taylor_term(-1, x) is S.Zero
220
+
221
+
222
+ def test_exp_MatrixSymbol():
223
+ A = MatrixSymbol("A", 2, 2)
224
+ assert exp(A).has(exp)
225
+
226
+
227
+ def test_exp_fdiff():
228
+ x = Symbol('x')
229
+ raises(ArgumentIndexError, lambda: exp(x).fdiff(2))
230
+
231
+
232
+ def test_log_values():
233
+ assert log(nan) is nan
234
+
235
+ assert log(oo) is oo
236
+ assert log(-oo) is oo
237
+
238
+ assert log(zoo) is zoo
239
+ assert log(-zoo) is zoo
240
+
241
+ assert log(0) is zoo
242
+
243
+ assert log(1) == 0
244
+ assert log(-1) == I*pi
245
+
246
+ assert log(E) == 1
247
+ assert log(-E).expand() == 1 + I*pi
248
+
249
+ assert unchanged(log, pi)
250
+ assert log(-pi).expand() == log(pi) + I*pi
251
+
252
+ assert unchanged(log, 17)
253
+ assert log(-17) == log(17) + I*pi
254
+
255
+ assert log(I) == I*pi/2
256
+ assert log(-I) == -I*pi/2
257
+
258
+ assert log(17*I) == I*pi/2 + log(17)
259
+ assert log(-17*I).expand() == -I*pi/2 + log(17)
260
+
261
+ assert log(oo*I) is oo
262
+ assert log(-oo*I) is oo
263
+ assert log(0, 2) is zoo
264
+ assert log(0, 5) is zoo
265
+
266
+ assert exp(-log(3))**(-1) == 3
267
+
268
+ assert log(S.Half) == -log(2)
269
+ assert log(2*3).func is log
270
+ assert log(2*3**2).func is log
271
+
272
+
273
+ def test_match_real_imag():
274
+ x, y = symbols('x,y', real=True)
275
+ i = Symbol('i', imaginary=True)
276
+ assert match_real_imag(S.One) == (1, 0)
277
+ assert match_real_imag(I) == (0, 1)
278
+ assert match_real_imag(3 - 5*I) == (3, -5)
279
+ assert match_real_imag(-sqrt(3) + S.Half*I) == (-sqrt(3), S.Half)
280
+ assert match_real_imag(x + y*I) == (x, y)
281
+ assert match_real_imag(x*I + y*I) == (0, x + y)
282
+ assert match_real_imag((x + y)*I) == (0, x + y)
283
+ assert match_real_imag(Rational(-2, 3)*i*I) == (None, None)
284
+ assert match_real_imag(1 - 2*i) == (None, None)
285
+ assert match_real_imag(sqrt(2)*(3 - 5*I)) == (None, None)
286
+
287
+
288
+ def test_log_exact():
289
+ # check for pi/2, pi/3, pi/4, pi/6, pi/8, pi/12; pi/5, pi/10:
290
+ for n in range(-23, 24):
291
+ if gcd(n, 24) != 1:
292
+ assert log(exp(n*I*pi/24).rewrite(sqrt)) == n*I*pi/24
293
+ for n in range(-9, 10):
294
+ assert log(exp(n*I*pi/10).rewrite(sqrt)) == n*I*pi/10
295
+
296
+ assert log(S.Half - I*sqrt(3)/2) == -I*pi/3
297
+ assert log(Rational(-1, 2) + I*sqrt(3)/2) == I*pi*Rational(2, 3)
298
+ assert log(-sqrt(2)/2 - I*sqrt(2)/2) == -I*pi*Rational(3, 4)
299
+ assert log(-sqrt(3)/2 - I*S.Half) == -I*pi*Rational(5, 6)
300
+
301
+ assert log(Rational(-1, 4) + sqrt(5)/4 - I*sqrt(sqrt(5)/8 + Rational(5, 8))) == -I*pi*Rational(2, 5)
302
+ assert log(sqrt(Rational(5, 8) - sqrt(5)/8) + I*(Rational(1, 4) + sqrt(5)/4)) == I*pi*Rational(3, 10)
303
+ assert log(-sqrt(sqrt(2)/4 + S.Half) + I*sqrt(S.Half - sqrt(2)/4)) == I*pi*Rational(7, 8)
304
+ assert log(-sqrt(6)/4 - sqrt(2)/4 + I*(-sqrt(6)/4 + sqrt(2)/4)) == -I*pi*Rational(11, 12)
305
+
306
+ assert log(-1 + I*sqrt(3)) == log(2) + I*pi*Rational(2, 3)
307
+ assert log(5 + 5*I) == log(5*sqrt(2)) + I*pi/4
308
+ assert log(sqrt(-12)) == log(2*sqrt(3)) + I*pi/2
309
+ assert log(-sqrt(6) + sqrt(2) - I*sqrt(6) - I*sqrt(2)) == log(4) - I*pi*Rational(7, 12)
310
+ assert log(-sqrt(6-3*sqrt(2)) - I*sqrt(6+3*sqrt(2))) == log(2*sqrt(3)) - I*pi*Rational(5, 8)
311
+ assert log(1 + I*sqrt(2-sqrt(2))/sqrt(2+sqrt(2))) == log(2/sqrt(sqrt(2) + 2)) + I*pi/8
312
+ assert log(cos(pi*Rational(7, 12)) + I*sin(pi*Rational(7, 12))) == I*pi*Rational(7, 12)
313
+ assert log(cos(pi*Rational(6, 5)) + I*sin(pi*Rational(6, 5))) == I*pi*Rational(-4, 5)
314
+
315
+ assert log(5*(1 + I)/sqrt(2)) == log(5) + I*pi/4
316
+ assert log(sqrt(2)*(-sqrt(3) + 1 - sqrt(3)*I - I)) == log(4) - I*pi*Rational(7, 12)
317
+ assert log(-sqrt(2)*(1 - I*sqrt(3))) == log(2*sqrt(2)) + I*pi*Rational(2, 3)
318
+ assert log(sqrt(3)*I*(-sqrt(6 - 3*sqrt(2)) - I*sqrt(3*sqrt(2) + 6))) == log(6) - I*pi/8
319
+
320
+ zero = (1 + sqrt(2))**2 - 3 - 2*sqrt(2)
321
+ assert log(zero - I*sqrt(3)) == log(sqrt(3)) - I*pi/2
322
+ assert unchanged(log, zero + I*zero) or log(zero + zero*I) is zoo
323
+
324
+ # bail quickly if no obvious simplification is possible:
325
+ assert unchanged(log, (sqrt(2)-1/sqrt(sqrt(3)+I))**1000)
326
+ # beware of non-real coefficients
327
+ assert unchanged(log, sqrt(2-sqrt(5))*(1 + I))
328
+
329
+
330
+ def test_log_base():
331
+ assert log(1, 2) == 0
332
+ assert log(2, 2) == 1
333
+ assert log(3, 2) == log(3)/log(2)
334
+ assert log(6, 2) == 1 + log(3)/log(2)
335
+ assert log(6, 3) == 1 + log(2)/log(3)
336
+ assert log(2**3, 2) == 3
337
+ assert log(3**3, 3) == 3
338
+ assert log(5, 1) is zoo
339
+ assert log(1, 1) is nan
340
+ assert log(Rational(2, 3), 10) == log(Rational(2, 3))/log(10)
341
+ assert log(Rational(2, 3), Rational(1, 3)) == -log(2)/log(3) + 1
342
+ assert log(Rational(2, 3), Rational(2, 5)) == \
343
+ log(Rational(2, 3))/log(Rational(2, 5))
344
+ # issue 17148
345
+ assert log(Rational(8, 3), 2) == -log(3)/log(2) + 3
346
+
347
+
348
+ def test_log_symbolic():
349
+ assert log(x, exp(1)) == log(x)
350
+ assert log(exp(x)) != x
351
+
352
+ assert log(x, exp(1)) == log(x)
353
+ assert log(x*y) != log(x) + log(y)
354
+ assert log(x/y).expand() != log(x) - log(y)
355
+ assert log(x/y).expand(force=True) == log(x) - log(y)
356
+ assert log(x**y).expand() != y*log(x)
357
+ assert log(x**y).expand(force=True) == y*log(x)
358
+
359
+ assert log(x, 2) == log(x)/log(2)
360
+ assert log(E, 2) == 1/log(2)
361
+
362
+ p, q = symbols('p,q', positive=True)
363
+ r = Symbol('r', real=True)
364
+
365
+ assert log(p**2) != 2*log(p)
366
+ assert log(p**2).expand() == 2*log(p)
367
+ assert log(x**2).expand() != 2*log(x)
368
+ assert log(p**q) != q*log(p)
369
+ assert log(exp(p)) == p
370
+ assert log(p*q) != log(p) + log(q)
371
+ assert log(p*q).expand() == log(p) + log(q)
372
+
373
+ assert log(-sqrt(3)) == log(sqrt(3)) + I*pi
374
+ assert log(-exp(p)) != p + I*pi
375
+ assert log(-exp(x)).expand() != x + I*pi
376
+ assert log(-exp(r)).expand() == r + I*pi
377
+
378
+ assert log(x**y) != y*log(x)
379
+
380
+ assert (log(x**-5)**-1).expand() != -1/log(x)/5
381
+ assert (log(p**-5)**-1).expand() == -1/log(p)/5
382
+ assert log(-x).func is log and log(-x).args[0] == -x
383
+ assert log(-p).func is log and log(-p).args[0] == -p
384
+
385
+
386
+ def test_log_exp():
387
+ assert log(exp(4*I*pi)) == 0 # exp evaluates
388
+ assert log(exp(-5*I*pi)) == I*pi # exp evaluates
389
+ assert log(exp(I*pi*Rational(19, 4))) == I*pi*Rational(3, 4)
390
+ assert log(exp(I*pi*Rational(25, 7))) == I*pi*Rational(-3, 7)
391
+ assert log(exp(-5*I)) == -5*I + 2*I*pi
392
+
393
+
394
+ @_both_exp_pow
395
+ def test_exp_assumptions():
396
+ r = Symbol('r', real=True)
397
+ i = Symbol('i', imaginary=True)
398
+ for e in exp, exp_polar:
399
+ assert e(x).is_real is None
400
+ assert e(x).is_imaginary is None
401
+ assert e(i).is_real is None
402
+ assert e(i).is_imaginary is None
403
+ assert e(r).is_real is True
404
+ assert e(r).is_imaginary is False
405
+ assert e(re(x)).is_extended_real is True
406
+ assert e(re(x)).is_imaginary is False
407
+
408
+ assert Pow(E, I*pi, evaluate=False).is_imaginary == False
409
+ assert Pow(E, 2*I*pi, evaluate=False).is_imaginary == False
410
+ assert Pow(E, I*pi/2, evaluate=False).is_imaginary == True
411
+ assert Pow(E, I*pi/3, evaluate=False).is_imaginary is None
412
+
413
+ assert exp(0, evaluate=False).is_algebraic
414
+
415
+ a = Symbol('a', algebraic=True)
416
+ an = Symbol('an', algebraic=True, nonzero=True)
417
+ r = Symbol('r', rational=True)
418
+ rn = Symbol('rn', rational=True, nonzero=True)
419
+ assert exp(a).is_algebraic is None
420
+ assert exp(an).is_algebraic is False
421
+ assert exp(pi*r).is_algebraic is None
422
+ assert exp(pi*rn).is_algebraic is False
423
+
424
+ assert exp(0, evaluate=False).is_algebraic is True
425
+ assert exp(I*pi/3, evaluate=False).is_algebraic is True
426
+ assert exp(I*pi*r, evaluate=False).is_algebraic is True
427
+
428
+
429
+ @_both_exp_pow
430
+ def test_exp_AccumBounds():
431
+ assert exp(AccumBounds(1, 2)) == AccumBounds(E, E**2)
432
+
433
+
434
+ def test_log_assumptions():
435
+ p = symbols('p', positive=True)
436
+ n = symbols('n', negative=True)
437
+ z = symbols('z', zero=True)
438
+ x = symbols('x', infinite=True, extended_positive=True)
439
+
440
+ assert log(z).is_positive is False
441
+ assert log(x).is_extended_positive is True
442
+ assert log(2) > 0
443
+ assert log(1, evaluate=False).is_zero
444
+ assert log(1 + z).is_zero
445
+ assert log(p).is_zero is None
446
+ assert log(n).is_zero is False
447
+ assert log(0.5).is_negative is True
448
+ assert log(exp(p) + 1).is_positive
449
+
450
+ assert log(1, evaluate=False).is_algebraic
451
+ assert log(42, evaluate=False).is_algebraic is False
452
+
453
+ assert log(1 + z).is_rational
454
+
455
+
456
+ def test_log_hashing():
457
+ assert x != log(log(x))
458
+ assert hash(x) != hash(log(log(x)))
459
+ assert log(x) != log(log(log(x)))
460
+
461
+ e = 1/log(log(x) + log(log(x)))
462
+ assert e.base.func is log
463
+ e = 1/log(log(x) + log(log(log(x))))
464
+ assert e.base.func is log
465
+
466
+ e = log(log(x))
467
+ assert e.func is log
468
+ assert x.func is not log
469
+ assert hash(log(log(x))) != hash(x)
470
+ assert e != x
471
+
472
+
473
+ def test_log_sign():
474
+ assert sign(log(2)) == 1
475
+
476
+
477
+ def test_log_expand_complex():
478
+ assert log(1 + I).expand(complex=True) == log(2)/2 + I*pi/4
479
+ assert log(1 - sqrt(2)).expand(complex=True) == log(sqrt(2) - 1) + I*pi
480
+
481
+
482
+ def test_log_apply_evalf():
483
+ value = (log(3)/log(2) - 1).evalf()
484
+ assert value.epsilon_eq(Float("0.58496250072115618145373"))
485
+
486
+
487
+ def test_log_leading_term():
488
+ p = Symbol('p')
489
+
490
+ # Test for STEP 3
491
+ assert log(1 + x + x**2).as_leading_term(x, cdir=1) == x
492
+ # Test for STEP 4
493
+ assert log(2*x).as_leading_term(x, cdir=1) == log(x) + log(2)
494
+ assert log(2*x).as_leading_term(x, cdir=-1) == log(x) + log(2)
495
+ assert log(-2*x).as_leading_term(x, cdir=1, logx=p) == p + log(2) + I*pi
496
+ assert log(-2*x).as_leading_term(x, cdir=-1, logx=p) == p + log(2) - I*pi
497
+ # Test for STEP 5
498
+ assert log(-2*x + (3 - I)*x**2).as_leading_term(x, cdir=1) == log(x) + log(2) - I*pi
499
+ assert log(-2*x + (3 - I)*x**2).as_leading_term(x, cdir=-1) == log(x) + log(2) - I*pi
500
+ assert log(2*x + (3 - I)*x**2).as_leading_term(x, cdir=1) == log(x) + log(2)
501
+ assert log(2*x + (3 - I)*x**2).as_leading_term(x, cdir=-1) == log(x) + log(2) - 2*I*pi
502
+ assert log(-1 + x - I*x**2 + I*x**3).as_leading_term(x, cdir=1) == -I*pi
503
+ assert log(-1 + x - I*x**2 + I*x**3).as_leading_term(x, cdir=-1) == -I*pi
504
+ assert log(-1/(1 - x)).as_leading_term(x, cdir=1) == I*pi
505
+ assert log(-1/(1 - x)).as_leading_term(x, cdir=-1) == I*pi
506
+
507
+
508
+ def test_log_nseries():
509
+ p = Symbol('p')
510
+ assert log(1/x)._eval_nseries(x, 4, logx=-p, cdir=1) == p
511
+ assert log(1/x)._eval_nseries(x, 4, logx=-p, cdir=-1) == p + 2*I*pi
512
+ assert log(x - 1)._eval_nseries(x, 4, None, I) == I*pi - x - x**2/2 - x**3/3 + O(x**4)
513
+ assert log(x - 1)._eval_nseries(x, 4, None, -I) == -I*pi - x - x**2/2 - x**3/3 + O(x**4)
514
+ assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x + x**2/2 + O(x**3)
515
+ assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == -I*pi - I*x + x**2/2 + O(x**3)
516
+ assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x**2 + O(x**3)
517
+ assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == I*pi - I*x**2 + O(x**3)
518
+ assert log(2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, 1) == log(2) + log(x) + \
519
+ x*(S(3)/2 - I/2) + x**2*(-1 + 3*I/4) + O(x**3)
520
+ assert log(2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, -1) == -2*I*pi + log(2) + \
521
+ log(x) - x*(-S(3)/2 + I/2) + x**2*(-1 + 3*I/4) + O(x**3)
522
+ assert log(-2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, 1) == -I*pi + log(2) + log(x) + \
523
+ x*(-S(3)/2 + I/2) + x**2*(-1 + 3*I/4) + O(x**3)
524
+ assert log(-2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, -1) == -I*pi + log(2) + log(x) - \
525
+ x*(S(3)/2 - I/2) + x**2*(-1 + 3*I/4) + O(x**3)
526
+ assert log(sqrt(-I*x**2 - 3)*sqrt(-I*x**2 - 1) - 2)._eval_nseries(x, 3, None, 1) == -I*pi + \
527
+ log(sqrt(3) + 2) + I*x**2*(-2 + 4*sqrt(3)/3) + O(x**3)
528
+ assert log(-1/(1 - x))._eval_nseries(x, 3, None, 1) == I*pi + x + x**2/2 + O(x**3)
529
+ assert log(-1/(1 - x))._eval_nseries(x, 3, None, -1) == I*pi + x + x**2/2 + O(x**3)
530
+
531
+
532
+ def test_log_series():
533
+ # Note Series at infinities other than oo/-oo were introduced as a part of
534
+ # pull request 23798. Refer https://github.com/sympy/sympy/pull/23798 for
535
+ # more information.
536
+ expr1 = log(1 + x)
537
+ expr2 = log(x + sqrt(x**2 + 1))
538
+
539
+ assert expr1.series(x, x0=I*oo, n=4) == 1/(3*x**3) - 1/(2*x**2) + 1/x + \
540
+ I*pi/2 - log(I/x) + O(x**(-4), (x, oo*I))
541
+ assert expr1.series(x, x0=-I*oo, n=4) == 1/(3*x**3) - 1/(2*x**2) + 1/x - \
542
+ I*pi/2 - log(-I/x) + O(x**(-4), (x, -oo*I))
543
+ assert expr2.series(x, x0=I*oo, n=4) == 1/(4*x**2) + I*pi/2 + log(2) - \
544
+ log(I/x) + O(x**(-4), (x, oo*I))
545
+ assert expr2.series(x, x0=-I*oo, n=4) == -1/(4*x**2) - I*pi/2 - log(2) + \
546
+ log(-I/x) + O(x**(-4), (x, -oo*I))
547
+
548
+
549
+ def test_log_expand():
550
+ w = Symbol("w", positive=True)
551
+ e = log(w**(log(5)/log(3)))
552
+ assert e.expand() == log(5)/log(3) * log(w)
553
+ x, y, z = symbols('x,y,z', positive=True)
554
+ assert log(x*(y + z)).expand(mul=False) == log(x) + log(y + z)
555
+ assert log(log(x**2)*log(y*z)).expand() in [log(2*log(x)*log(y) +
556
+ 2*log(x)*log(z)), log(log(x)*log(z) + log(y)*log(x)) + log(2),
557
+ log((log(y) + log(z))*log(x)) + log(2)]
558
+ assert log(x**log(x**2)).expand(deep=False) == log(x)*log(x**2)
559
+ assert log(x**log(x**2)).expand() == 2*log(x)**2
560
+ x, y = symbols('x,y')
561
+ assert log(x*y).expand(force=True) == log(x) + log(y)
562
+ assert log(x**y).expand(force=True) == y*log(x)
563
+ assert log(exp(x)).expand(force=True) == x
564
+
565
+ # there's generally no need to expand out logs since this requires
566
+ # factoring and if simplification is sought, it's cheaper to put
567
+ # logs together than it is to take them apart.
568
+ assert log(2*3**2).expand() != 2*log(3) + log(2)
569
+
570
+
571
+ @XFAIL
572
+ def test_log_expand_fail():
573
+ x, y, z = symbols('x,y,z', positive=True)
574
+ assert (log(x*(y + z))*(x + y)).expand(mul=True, log=True) == y*log(
575
+ x) + y*log(y + z) + z*log(x) + z*log(y + z)
576
+
577
+
578
+ def test_log_simplify():
579
+ x = Symbol("x", positive=True)
580
+ assert log(x**2).expand() == 2*log(x)
581
+ assert expand_log(log(x**(2 + log(2)))) == (2 + log(2))*log(x)
582
+
583
+ z = Symbol('z')
584
+ assert log(sqrt(z)).expand() == log(z)/2
585
+ assert expand_log(log(z**(log(2) - 1))) == (log(2) - 1)*log(z)
586
+ assert log(z**(-1)).expand() != -log(z)
587
+ assert log(z**(x/(x+1))).expand() == x*log(z)/(x + 1)
588
+
589
+
590
+ def test_log_AccumBounds():
591
+ assert log(AccumBounds(1, E)) == AccumBounds(0, 1)
592
+ assert log(AccumBounds(0, E)) == AccumBounds(-oo, 1)
593
+ assert log(AccumBounds(-1, E)) == S.NaN
594
+ assert log(AccumBounds(0, oo)) == AccumBounds(-oo, oo)
595
+ assert log(AccumBounds(-oo, 0)) == S.NaN
596
+ assert log(AccumBounds(-oo, oo)) == S.NaN
597
+
598
+
599
+ @_both_exp_pow
600
+ def test_lambertw():
601
+ k = Symbol('k')
602
+
603
+ assert LambertW(x, 0) == LambertW(x)
604
+ assert LambertW(x, 0, evaluate=False) != LambertW(x)
605
+ assert LambertW(0) == 0
606
+ assert LambertW(E) == 1
607
+ assert LambertW(-1/E) == -1
608
+ assert LambertW(-log(2)/2) == -log(2)
609
+ assert LambertW(oo) is oo
610
+ assert LambertW(0, 1) is -oo
611
+ assert LambertW(0, 42) is -oo
612
+ assert LambertW(-pi/2, -1) == -I*pi/2
613
+ assert LambertW(-1/E, -1) == -1
614
+ assert LambertW(-2*exp(-2), -1) == -2
615
+ assert LambertW(2*log(2)) == log(2)
616
+ assert LambertW(-pi/2) == I*pi/2
617
+ assert LambertW(exp(1 + E)) == E
618
+
619
+ assert LambertW(x**2).diff(x) == 2*LambertW(x**2)/x/(1 + LambertW(x**2))
620
+ assert LambertW(x, k).diff(x) == LambertW(x, k)/x/(1 + LambertW(x, k))
621
+
622
+ assert LambertW(sqrt(2)).evalf(30).epsilon_eq(
623
+ Float("0.701338383413663009202120278965", 30), 1e-29)
624
+ assert re(LambertW(2, -1)).evalf().epsilon_eq(Float("-0.834310366631110"))
625
+
626
+ assert LambertW(-1).is_real is False # issue 5215
627
+ assert LambertW(2, evaluate=False).is_real
628
+ p = Symbol('p', positive=True)
629
+ assert LambertW(p, evaluate=False).is_real
630
+ assert LambertW(p - 1, evaluate=False).is_real is None
631
+ assert LambertW(-p - 2/S.Exp1, evaluate=False).is_real is False
632
+ assert LambertW(S.Half, -1, evaluate=False).is_real is False
633
+ assert LambertW(Rational(-1, 10), -1, evaluate=False).is_real
634
+ assert LambertW(-10, -1, evaluate=False).is_real is False
635
+ assert LambertW(-2, 2, evaluate=False).is_real is False
636
+
637
+ assert LambertW(0, evaluate=False).is_algebraic
638
+ na = Symbol('na', nonzero=True, algebraic=True)
639
+ assert LambertW(na).is_algebraic is False
640
+ assert LambertW(p).is_zero is False
641
+ n = Symbol('n', negative=True)
642
+ assert LambertW(n).is_zero is False
643
+
644
+
645
+ def test_issue_5673():
646
+ e = LambertW(-1)
647
+ assert e.is_comparable is False
648
+ assert e.is_positive is not True
649
+ e2 = 1 - 1/(1 - exp(-1000))
650
+ assert e2.is_positive is not True
651
+ e3 = -2 + exp(exp(LambertW(log(2)))*LambertW(log(2)))
652
+ assert e3.is_nonzero is not True
653
+
654
+
655
+ def test_log_fdiff():
656
+ x = Symbol('x')
657
+ raises(ArgumentIndexError, lambda: log(x).fdiff(2))
658
+
659
+
660
+ def test_log_taylor_term():
661
+ x = symbols('x')
662
+ assert log(x).taylor_term(0, x) == x
663
+ assert log(x).taylor_term(1, x) == -x**2/2
664
+ assert log(x).taylor_term(4, x) == x**5/5
665
+ assert log(x).taylor_term(-1, x) is S.Zero
666
+
667
+
668
+ def test_exp_expand_NC():
669
+ A, B, C = symbols('A,B,C', commutative=False)
670
+
671
+ assert exp(A + B).expand() == exp(A + B)
672
+ assert exp(A + B + C).expand() == exp(A + B + C)
673
+ assert exp(x + y).expand() == exp(x)*exp(y)
674
+ assert exp(x + y + z).expand() == exp(x)*exp(y)*exp(z)
675
+
676
+
677
+ @_both_exp_pow
678
+ def test_as_numer_denom():
679
+ n = symbols('n', negative=True)
680
+ assert exp(x).as_numer_denom() == (exp(x), 1)
681
+ assert exp(-x).as_numer_denom() == (1, exp(x))
682
+ assert exp(-2*x).as_numer_denom() == (1, exp(2*x))
683
+ assert exp(-2).as_numer_denom() == (1, exp(2))
684
+ assert exp(n).as_numer_denom() == (1, exp(-n))
685
+ assert exp(-n).as_numer_denom() == (exp(-n), 1)
686
+ assert exp(-I*x).as_numer_denom() == (1, exp(I*x))
687
+ assert exp(-I*n).as_numer_denom() == (1, exp(I*n))
688
+ assert exp(-n).as_numer_denom() == (exp(-n), 1)
689
+
690
+
691
+ @_both_exp_pow
692
+ def test_polar():
693
+ x, y = symbols('x y', polar=True)
694
+
695
+ assert abs(exp_polar(I*4)) == 1
696
+ assert abs(exp_polar(0)) == 1
697
+ assert abs(exp_polar(2 + 3*I)) == exp(2)
698
+ assert exp_polar(I*10).n() == exp_polar(I*10)
699
+
700
+ assert log(exp_polar(z)) == z
701
+ assert log(x*y).expand() == log(x) + log(y)
702
+ assert log(x**z).expand() == z*log(x)
703
+
704
+ assert exp_polar(3).exp == 3
705
+
706
+ # Compare exp(1.0*pi*I).
707
+ assert (exp_polar(1.0*pi*I).n(n=5)).as_real_imag()[1] >= 0
708
+
709
+ assert exp_polar(0).is_rational is True # issue 8008
710
+
711
+
712
+ def test_exp_summation():
713
+ w = symbols("w")
714
+ m, n, i, j = symbols("m n i j")
715
+ expr = exp(Sum(w*i, (i, 0, n), (j, 0, m)))
716
+ assert expr.expand() == Product(exp(w*i), (i, 0, n), (j, 0, m))
717
+
718
+
719
+ def test_log_product():
720
+ from sympy.abc import n, m
721
+
722
+ i, j = symbols('i,j', positive=True, integer=True)
723
+ x, y = symbols('x,y', positive=True)
724
+ z = symbols('z', real=True)
725
+ w = symbols('w')
726
+
727
+ expr = log(Product(x**i, (i, 1, n)))
728
+ assert simplify(expr) == expr
729
+ assert expr.expand() == Sum(i*log(x), (i, 1, n))
730
+ expr = log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))
731
+ assert simplify(expr) == expr
732
+ assert expr.expand() == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
733
+
734
+ expr = log(Product(-2, (n, 0, 4)))
735
+ assert simplify(expr) == expr
736
+ assert expr.expand() == expr
737
+ assert expr.expand(force=True) == Sum(log(-2), (n, 0, 4))
738
+
739
+ expr = log(Product(exp(z*i), (i, 0, n)))
740
+ assert expr.expand() == Sum(z*i, (i, 0, n))
741
+
742
+ expr = log(Product(exp(w*i), (i, 0, n)))
743
+ assert expr.expand() == expr
744
+ assert expr.expand(force=True) == Sum(w*i, (i, 0, n))
745
+
746
+ expr = log(Product(i**2*abs(j), (i, 1, n), (j, 1, m)))
747
+ assert expr.expand() == Sum(2*log(i) + log(j), (i, 1, n), (j, 1, m))
748
+
749
+
750
+ @XFAIL
751
+ def test_log_product_simplify_to_sum():
752
+ from sympy.abc import n, m
753
+ i, j = symbols('i,j', positive=True, integer=True)
754
+ x, y = symbols('x,y', positive=True)
755
+ assert simplify(log(Product(x**i, (i, 1, n)))) == Sum(i*log(x), (i, 1, n))
756
+ assert simplify(log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))) == \
757
+ Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
758
+
759
+
760
+ def test_issue_8866():
761
+ assert simplify(log(x, 10, evaluate=False)) == simplify(log(x, 10))
762
+ assert expand_log(log(x, 10, evaluate=False)) == expand_log(log(x, 10))
763
+
764
+ y = Symbol('y', positive=True)
765
+ l1 = log(exp(y), exp(10))
766
+ b1 = log(exp(y), exp(5))
767
+ l2 = log(exp(y), exp(10), evaluate=False)
768
+ b2 = log(exp(y), exp(5), evaluate=False)
769
+ assert simplify(log(l1, b1)) == simplify(log(l2, b2))
770
+ assert expand_log(log(l1, b1)) == expand_log(log(l2, b2))
771
+
772
+
773
+ def test_log_expand_factor():
774
+ assert (log(18)/log(3) - 2).expand(factor=True) == log(2)/log(3)
775
+ assert (log(12)/log(2)).expand(factor=True) == log(3)/log(2) + 2
776
+ assert (log(15)/log(3)).expand(factor=True) == 1 + log(5)/log(3)
777
+ assert (log(2)/(-log(12) + log(24))).expand(factor=True) == 1
778
+
779
+ assert expand_log(log(12), factor=True) == log(3) + 2*log(2)
780
+ assert expand_log(log(21)/log(7), factor=False) == log(3)/log(7) + 1
781
+ assert expand_log(log(45)/log(5) + log(20), factor=False) == \
782
+ 1 + 2*log(3)/log(5) + log(20)
783
+ assert expand_log(log(45)/log(5) + log(26), factor=True) == \
784
+ log(2) + log(13) + (log(5) + 2*log(3))/log(5)
785
+
786
+
787
+ def test_issue_9116():
788
+ n = Symbol('n', positive=True, integer=True)
789
+ assert log(n).is_nonnegative is True
790
+
791
+
792
+ def test_issue_18473():
793
+ assert exp(x*log(cos(1/x))).as_leading_term(x) == S.NaN
794
+ assert exp(x*log(tan(1/x))).as_leading_term(x) == S.NaN
795
+ assert log(cos(1/x)).as_leading_term(x) == S.NaN
796
+ assert log(tan(1/x)).as_leading_term(x) == S.NaN
797
+ assert log(cos(1/x) + 2).as_leading_term(x) == AccumBounds(0, log(3))
798
+ assert exp(x*log(cos(1/x) + 2)).as_leading_term(x) == 1
799
+ assert log(cos(1/x) - 2).as_leading_term(x) == S.NaN
800
+ assert exp(x*log(cos(1/x) - 2)).as_leading_term(x) == S.NaN
801
+ assert log(cos(1/x) + 1).as_leading_term(x) == AccumBounds(-oo, log(2))
802
+ assert exp(x*log(cos(1/x) + 1)).as_leading_term(x) == AccumBounds(0, 1)
803
+ assert log(sin(1/x)**2).as_leading_term(x) == AccumBounds(-oo, 0)
804
+ assert exp(x*log(sin(1/x)**2)).as_leading_term(x) == AccumBounds(0, 1)
805
+ assert log(tan(1/x)**2).as_leading_term(x) == AccumBounds(-oo, oo)
806
+ assert exp(2*x*(log(tan(1/x)**2))).as_leading_term(x) == AccumBounds(0, oo)
llmeval-env/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
llmeval-env/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
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_interface.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This test file tests the SymPy function interface, that people use to create
2
+ # their own new functions. It should be as easy as possible.
3
+ from sympy.core.function import Function
4
+ from sympy.core.sympify import sympify
5
+ from sympy.functions.elementary.hyperbolic import tanh
6
+ from sympy.functions.elementary.trigonometric import (cos, sin)
7
+ from sympy.series.limits import limit
8
+ from sympy.abc import x
9
+
10
+
11
+ def test_function_series1():
12
+ """Create our new "sin" function."""
13
+
14
+ class my_function(Function):
15
+
16
+ def fdiff(self, argindex=1):
17
+ return cos(self.args[0])
18
+
19
+ @classmethod
20
+ def eval(cls, arg):
21
+ arg = sympify(arg)
22
+ if arg == 0:
23
+ return sympify(0)
24
+
25
+ #Test that the taylor series is correct
26
+ assert my_function(x).series(x, 0, 10) == sin(x).series(x, 0, 10)
27
+ assert limit(my_function(x)/x, x, 0) == 1
28
+
29
+
30
+ def test_function_series2():
31
+ """Create our new "cos" function."""
32
+
33
+ class my_function2(Function):
34
+
35
+ def fdiff(self, argindex=1):
36
+ return -sin(self.args[0])
37
+
38
+ @classmethod
39
+ def eval(cls, arg):
40
+ arg = sympify(arg)
41
+ if arg == 0:
42
+ return sympify(1)
43
+
44
+ #Test that the taylor series is correct
45
+ assert my_function2(x).series(x, 0, 10) == cos(x).series(x, 0, 10)
46
+
47
+
48
+ def test_function_series3():
49
+ """
50
+ Test our easy "tanh" function.
51
+
52
+ This test tests two things:
53
+ * that the Function interface works as expected and it's easy to use
54
+ * that the general algorithm for the series expansion works even when the
55
+ derivative is defined recursively in terms of the original function,
56
+ since tanh(x).diff(x) == 1-tanh(x)**2
57
+ """
58
+
59
+ class mytanh(Function):
60
+
61
+ def fdiff(self, argindex=1):
62
+ return 1 - mytanh(self.args[0])**2
63
+
64
+ @classmethod
65
+ def eval(cls, arg):
66
+ arg = sympify(arg)
67
+ if arg == 0:
68
+ return sympify(0)
69
+
70
+ e = tanh(x)
71
+ f = mytanh(x)
72
+ assert e.series(x, 0, 6) == f.series(x, 0, 6)
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_miscellaneous.py ADDED
@@ -0,0 +1,504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools as it
2
+
3
+ from sympy.core.expr import unchanged
4
+ from sympy.core.function import Function
5
+ from sympy.core.numbers import I, oo, Rational
6
+ from sympy.core.power import Pow
7
+ from sympy.core.singleton import S
8
+ from sympy.core.symbol import Symbol
9
+ from sympy.external import import_module
10
+ from sympy.functions.elementary.exponential import log
11
+ from sympy.functions.elementary.integers import floor, ceiling
12
+ from sympy.functions.elementary.miscellaneous import (sqrt, cbrt, root, Min,
13
+ Max, real_root, Rem)
14
+ from sympy.functions.elementary.trigonometric import cos, sin
15
+ from sympy.functions.special.delta_functions import Heaviside
16
+
17
+ from sympy.utilities.lambdify import lambdify
18
+ from sympy.testing.pytest import raises, skip, ignore_warnings
19
+
20
+ def test_Min():
21
+ from sympy.abc import x, y, z
22
+ n = Symbol('n', negative=True)
23
+ n_ = Symbol('n_', negative=True)
24
+ nn = Symbol('nn', nonnegative=True)
25
+ nn_ = Symbol('nn_', nonnegative=True)
26
+ p = Symbol('p', positive=True)
27
+ p_ = Symbol('p_', positive=True)
28
+ np = Symbol('np', nonpositive=True)
29
+ np_ = Symbol('np_', nonpositive=True)
30
+ r = Symbol('r', real=True)
31
+
32
+ assert Min(5, 4) == 4
33
+ assert Min(-oo, -oo) is -oo
34
+ assert Min(-oo, n) is -oo
35
+ assert Min(n, -oo) is -oo
36
+ assert Min(-oo, np) is -oo
37
+ assert Min(np, -oo) is -oo
38
+ assert Min(-oo, 0) is -oo
39
+ assert Min(0, -oo) is -oo
40
+ assert Min(-oo, nn) is -oo
41
+ assert Min(nn, -oo) is -oo
42
+ assert Min(-oo, p) is -oo
43
+ assert Min(p, -oo) is -oo
44
+ assert Min(-oo, oo) is -oo
45
+ assert Min(oo, -oo) is -oo
46
+ assert Min(n, n) == n
47
+ assert unchanged(Min, n, np)
48
+ assert Min(np, n) == Min(n, np)
49
+ assert Min(n, 0) == n
50
+ assert Min(0, n) == n
51
+ assert Min(n, nn) == n
52
+ assert Min(nn, n) == n
53
+ assert Min(n, p) == n
54
+ assert Min(p, n) == n
55
+ assert Min(n, oo) == n
56
+ assert Min(oo, n) == n
57
+ assert Min(np, np) == np
58
+ assert Min(np, 0) == np
59
+ assert Min(0, np) == np
60
+ assert Min(np, nn) == np
61
+ assert Min(nn, np) == np
62
+ assert Min(np, p) == np
63
+ assert Min(p, np) == np
64
+ assert Min(np, oo) == np
65
+ assert Min(oo, np) == np
66
+ assert Min(0, 0) == 0
67
+ assert Min(0, nn) == 0
68
+ assert Min(nn, 0) == 0
69
+ assert Min(0, p) == 0
70
+ assert Min(p, 0) == 0
71
+ assert Min(0, oo) == 0
72
+ assert Min(oo, 0) == 0
73
+ assert Min(nn, nn) == nn
74
+ assert unchanged(Min, nn, p)
75
+ assert Min(p, nn) == Min(nn, p)
76
+ assert Min(nn, oo) == nn
77
+ assert Min(oo, nn) == nn
78
+ assert Min(p, p) == p
79
+ assert Min(p, oo) == p
80
+ assert Min(oo, p) == p
81
+ assert Min(oo, oo) is oo
82
+
83
+ assert Min(n, n_).func is Min
84
+ assert Min(nn, nn_).func is Min
85
+ assert Min(np, np_).func is Min
86
+ assert Min(p, p_).func is Min
87
+
88
+ # lists
89
+ assert Min() is S.Infinity
90
+ assert Min(x) == x
91
+ assert Min(x, y) == Min(y, x)
92
+ assert Min(x, y, z) == Min(z, y, x)
93
+ assert Min(x, Min(y, z)) == Min(z, y, x)
94
+ assert Min(x, Max(y, -oo)) == Min(x, y)
95
+ assert Min(p, oo, n, p, p, p_) == n
96
+ assert Min(p_, n_, p) == n_
97
+ assert Min(n, oo, -7, p, p, 2) == Min(n, -7)
98
+ assert Min(2, x, p, n, oo, n_, p, 2, -2, -2) == Min(-2, x, n, n_)
99
+ assert Min(0, x, 1, y) == Min(0, x, y)
100
+ assert Min(1000, 100, -100, x, p, n) == Min(n, x, -100)
101
+ assert unchanged(Min, sin(x), cos(x))
102
+ assert Min(sin(x), cos(x)) == Min(cos(x), sin(x))
103
+ assert Min(cos(x), sin(x)).subs(x, 1) == cos(1)
104
+ assert Min(cos(x), sin(x)).subs(x, S.Half) == sin(S.Half)
105
+ raises(ValueError, lambda: Min(cos(x), sin(x)).subs(x, I))
106
+ raises(ValueError, lambda: Min(I))
107
+ raises(ValueError, lambda: Min(I, x))
108
+ raises(ValueError, lambda: Min(S.ComplexInfinity, x))
109
+
110
+ assert Min(1, x).diff(x) == Heaviside(1 - x)
111
+ assert Min(x, 1).diff(x) == Heaviside(1 - x)
112
+ assert Min(0, -x, 1 - 2*x).diff(x) == -Heaviside(x + Min(0, -2*x + 1)) \
113
+ - 2*Heaviside(2*x + Min(0, -x) - 1)
114
+
115
+ # issue 7619
116
+ f = Function('f')
117
+ assert Min(1, 2*Min(f(1), 2)) # doesn't fail
118
+
119
+ # issue 7233
120
+ e = Min(0, x)
121
+ assert e.n().args == (0, x)
122
+
123
+ # issue 8643
124
+ m = Min(n, p_, n_, r)
125
+ assert m.is_positive is False
126
+ assert m.is_nonnegative is False
127
+ assert m.is_negative is True
128
+
129
+ m = Min(p, p_)
130
+ assert m.is_positive is True
131
+ assert m.is_nonnegative is True
132
+ assert m.is_negative is False
133
+
134
+ m = Min(p, nn_, p_)
135
+ assert m.is_positive is None
136
+ assert m.is_nonnegative is True
137
+ assert m.is_negative is False
138
+
139
+ m = Min(nn, p, r)
140
+ assert m.is_positive is None
141
+ assert m.is_nonnegative is None
142
+ assert m.is_negative is None
143
+
144
+
145
+ def test_Max():
146
+ from sympy.abc import x, y, z
147
+ n = Symbol('n', negative=True)
148
+ n_ = Symbol('n_', negative=True)
149
+ nn = Symbol('nn', nonnegative=True)
150
+ p = Symbol('p', positive=True)
151
+ p_ = Symbol('p_', positive=True)
152
+ r = Symbol('r', real=True)
153
+
154
+ assert Max(5, 4) == 5
155
+
156
+ # lists
157
+
158
+ assert Max() is S.NegativeInfinity
159
+ assert Max(x) == x
160
+ assert Max(x, y) == Max(y, x)
161
+ assert Max(x, y, z) == Max(z, y, x)
162
+ assert Max(x, Max(y, z)) == Max(z, y, x)
163
+ assert Max(x, Min(y, oo)) == Max(x, y)
164
+ assert Max(n, -oo, n_, p, 2) == Max(p, 2)
165
+ assert Max(n, -oo, n_, p) == p
166
+ assert Max(2, x, p, n, -oo, S.NegativeInfinity, n_, p, 2) == Max(2, x, p)
167
+ assert Max(0, x, 1, y) == Max(1, x, y)
168
+ assert Max(r, r + 1, r - 1) == 1 + r
169
+ assert Max(1000, 100, -100, x, p, n) == Max(p, x, 1000)
170
+ assert Max(cos(x), sin(x)) == Max(sin(x), cos(x))
171
+ assert Max(cos(x), sin(x)).subs(x, 1) == sin(1)
172
+ assert Max(cos(x), sin(x)).subs(x, S.Half) == cos(S.Half)
173
+ raises(ValueError, lambda: Max(cos(x), sin(x)).subs(x, I))
174
+ raises(ValueError, lambda: Max(I))
175
+ raises(ValueError, lambda: Max(I, x))
176
+ raises(ValueError, lambda: Max(S.ComplexInfinity, 1))
177
+ assert Max(n, -oo, n_, p, 2) == Max(p, 2)
178
+ assert Max(n, -oo, n_, p, 1000) == Max(p, 1000)
179
+
180
+ assert Max(1, x).diff(x) == Heaviside(x - 1)
181
+ assert Max(x, 1).diff(x) == Heaviside(x - 1)
182
+ assert Max(x**2, 1 + x, 1).diff(x) == \
183
+ 2*x*Heaviside(x**2 - Max(1, x + 1)) \
184
+ + Heaviside(x - Max(1, x**2) + 1)
185
+
186
+ e = Max(0, x)
187
+ assert e.n().args == (0, x)
188
+
189
+ # issue 8643
190
+ m = Max(p, p_, n, r)
191
+ assert m.is_positive is True
192
+ assert m.is_nonnegative is True
193
+ assert m.is_negative is False
194
+
195
+ m = Max(n, n_)
196
+ assert m.is_positive is False
197
+ assert m.is_nonnegative is False
198
+ assert m.is_negative is True
199
+
200
+ m = Max(n, n_, r)
201
+ assert m.is_positive is None
202
+ assert m.is_nonnegative is None
203
+ assert m.is_negative is None
204
+
205
+ m = Max(n, nn, r)
206
+ assert m.is_positive is None
207
+ assert m.is_nonnegative is True
208
+ assert m.is_negative is False
209
+
210
+
211
+ def test_minmax_assumptions():
212
+ r = Symbol('r', real=True)
213
+ a = Symbol('a', real=True, algebraic=True)
214
+ t = Symbol('t', real=True, transcendental=True)
215
+ q = Symbol('q', rational=True)
216
+ p = Symbol('p', irrational=True)
217
+ n = Symbol('n', rational=True, integer=False)
218
+ i = Symbol('i', integer=True)
219
+ o = Symbol('o', odd=True)
220
+ e = Symbol('e', even=True)
221
+ k = Symbol('k', prime=True)
222
+ reals = [r, a, t, q, p, n, i, o, e, k]
223
+
224
+ for ext in (Max, Min):
225
+ for x, y in it.product(reals, repeat=2):
226
+
227
+ # Must be real
228
+ assert ext(x, y).is_real
229
+
230
+ # Algebraic?
231
+ if x.is_algebraic and y.is_algebraic:
232
+ assert ext(x, y).is_algebraic
233
+ elif x.is_transcendental and y.is_transcendental:
234
+ assert ext(x, y).is_transcendental
235
+ else:
236
+ assert ext(x, y).is_algebraic is None
237
+
238
+ # Rational?
239
+ if x.is_rational and y.is_rational:
240
+ assert ext(x, y).is_rational
241
+ elif x.is_irrational and y.is_irrational:
242
+ assert ext(x, y).is_irrational
243
+ else:
244
+ assert ext(x, y).is_rational is None
245
+
246
+ # Integer?
247
+ if x.is_integer and y.is_integer:
248
+ assert ext(x, y).is_integer
249
+ elif x.is_noninteger and y.is_noninteger:
250
+ assert ext(x, y).is_noninteger
251
+ else:
252
+ assert ext(x, y).is_integer is None
253
+
254
+ # Odd?
255
+ if x.is_odd and y.is_odd:
256
+ assert ext(x, y).is_odd
257
+ elif x.is_odd is False and y.is_odd is False:
258
+ assert ext(x, y).is_odd is False
259
+ else:
260
+ assert ext(x, y).is_odd is None
261
+
262
+ # Even?
263
+ if x.is_even and y.is_even:
264
+ assert ext(x, y).is_even
265
+ elif x.is_even is False and y.is_even is False:
266
+ assert ext(x, y).is_even is False
267
+ else:
268
+ assert ext(x, y).is_even is None
269
+
270
+ # Prime?
271
+ if x.is_prime and y.is_prime:
272
+ assert ext(x, y).is_prime
273
+ elif x.is_prime is False and y.is_prime is False:
274
+ assert ext(x, y).is_prime is False
275
+ else:
276
+ assert ext(x, y).is_prime is None
277
+
278
+
279
+ def test_issue_8413():
280
+ x = Symbol('x', real=True)
281
+ # we can't evaluate in general because non-reals are not
282
+ # comparable: Min(floor(3.2 + I), 3.2 + I) -> ValueError
283
+ assert Min(floor(x), x) == floor(x)
284
+ assert Min(ceiling(x), x) == x
285
+ assert Max(floor(x), x) == x
286
+ assert Max(ceiling(x), x) == ceiling(x)
287
+
288
+
289
+ def test_root():
290
+ from sympy.abc import x
291
+ n = Symbol('n', integer=True)
292
+ k = Symbol('k', integer=True)
293
+
294
+ assert root(2, 2) == sqrt(2)
295
+ assert root(2, 1) == 2
296
+ assert root(2, 3) == 2**Rational(1, 3)
297
+ assert root(2, 3) == cbrt(2)
298
+ assert root(2, -5) == 2**Rational(4, 5)/2
299
+
300
+ assert root(-2, 1) == -2
301
+
302
+ assert root(-2, 2) == sqrt(2)*I
303
+ assert root(-2, 1) == -2
304
+
305
+ assert root(x, 2) == sqrt(x)
306
+ assert root(x, 1) == x
307
+ assert root(x, 3) == x**Rational(1, 3)
308
+ assert root(x, 3) == cbrt(x)
309
+ assert root(x, -5) == x**Rational(-1, 5)
310
+
311
+ assert root(x, n) == x**(1/n)
312
+ assert root(x, -n) == x**(-1/n)
313
+
314
+ assert root(x, n, k) == (-1)**(2*k/n)*x**(1/n)
315
+
316
+
317
+ def test_real_root():
318
+ assert real_root(-8, 3) == -2
319
+ assert real_root(-16, 4) == root(-16, 4)
320
+ r = root(-7, 4)
321
+ assert real_root(r) == r
322
+ r1 = root(-1, 3)
323
+ r2 = r1**2
324
+ r3 = root(-1, 4)
325
+ assert real_root(r1 + r2 + r3) == -1 + r2 + r3
326
+ assert real_root(root(-2, 3)) == -root(2, 3)
327
+ assert real_root(-8., 3) == -2.0
328
+ x = Symbol('x')
329
+ n = Symbol('n')
330
+ g = real_root(x, n)
331
+ assert g.subs({"x": -8, "n": 3}) == -2
332
+ assert g.subs({"x": 8, "n": 3}) == 2
333
+ # give principle root if there is no real root -- if this is not desired
334
+ # then maybe a Root class is needed to raise an error instead
335
+ assert g.subs({"x": I, "n": 3}) == cbrt(I)
336
+ assert g.subs({"x": -8, "n": 2}) == sqrt(-8)
337
+ assert g.subs({"x": I, "n": 2}) == sqrt(I)
338
+
339
+
340
+ def test_issue_11463():
341
+ numpy = import_module('numpy')
342
+ if not numpy:
343
+ skip("numpy not installed.")
344
+ x = Symbol('x')
345
+ f = lambdify(x, real_root((log(x/(x-2))), 3), 'numpy')
346
+ # numpy.select evaluates all options before considering conditions,
347
+ # so it raises a warning about root of negative number which does
348
+ # not affect the outcome. This warning is suppressed here
349
+ with ignore_warnings(RuntimeWarning):
350
+ assert f(numpy.array(-1)) < -1
351
+
352
+
353
+ def test_rewrite_MaxMin_as_Heaviside():
354
+ from sympy.abc import x
355
+ assert Max(0, x).rewrite(Heaviside) == x*Heaviside(x)
356
+ assert Max(3, x).rewrite(Heaviside) == x*Heaviside(x - 3) + \
357
+ 3*Heaviside(-x + 3)
358
+ assert Max(0, x+2, 2*x).rewrite(Heaviside) == \
359
+ 2*x*Heaviside(2*x)*Heaviside(x - 2) + \
360
+ (x + 2)*Heaviside(-x + 2)*Heaviside(x + 2)
361
+
362
+ assert Min(0, x).rewrite(Heaviside) == x*Heaviside(-x)
363
+ assert Min(3, x).rewrite(Heaviside) == x*Heaviside(-x + 3) + \
364
+ 3*Heaviside(x - 3)
365
+ assert Min(x, -x, -2).rewrite(Heaviside) == \
366
+ x*Heaviside(-2*x)*Heaviside(-x - 2) - \
367
+ x*Heaviside(2*x)*Heaviside(x - 2) \
368
+ - 2*Heaviside(-x + 2)*Heaviside(x + 2)
369
+
370
+
371
+ def test_rewrite_MaxMin_as_Piecewise():
372
+ from sympy.core.symbol import symbols
373
+ from sympy.functions.elementary.piecewise import Piecewise
374
+ x, y, z, a, b = symbols('x y z a b', real=True)
375
+ vx, vy, va = symbols('vx vy va')
376
+ assert Max(a, b).rewrite(Piecewise) == Piecewise((a, a >= b), (b, True))
377
+ assert Max(x, y, z).rewrite(Piecewise) == Piecewise((x, (x >= y) & (x >= z)), (y, y >= z), (z, True))
378
+ assert Max(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a >= b) & (a >= x) & (a >= y)),
379
+ (b, (b >= x) & (b >= y)), (x, x >= y), (y, True))
380
+ assert Min(a, b).rewrite(Piecewise) == Piecewise((a, a <= b), (b, True))
381
+ assert Min(x, y, z).rewrite(Piecewise) == Piecewise((x, (x <= y) & (x <= z)), (y, y <= z), (z, True))
382
+ assert Min(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a <= b) & (a <= x) & (a <= y)),
383
+ (b, (b <= x) & (b <= y)), (x, x <= y), (y, True))
384
+
385
+ # Piecewise rewriting of Min/Max does also takes place for not explicitly real arguments
386
+ assert Max(vx, vy).rewrite(Piecewise) == Piecewise((vx, vx >= vy), (vy, True))
387
+ assert Min(va, vx, vy).rewrite(Piecewise) == Piecewise((va, (va <= vx) & (va <= vy)), (vx, vx <= vy), (vy, True))
388
+
389
+
390
+ def test_issue_11099():
391
+ from sympy.abc import x, y
392
+ # some fixed value tests
393
+ fixed_test_data = {x: -2, y: 3}
394
+ assert Min(x, y).evalf(subs=fixed_test_data) == \
395
+ Min(x, y).subs(fixed_test_data).evalf()
396
+ assert Max(x, y).evalf(subs=fixed_test_data) == \
397
+ Max(x, y).subs(fixed_test_data).evalf()
398
+ # randomly generate some test data
399
+ from sympy.core.random import randint
400
+ for i in range(20):
401
+ random_test_data = {x: randint(-100, 100), y: randint(-100, 100)}
402
+ assert Min(x, y).evalf(subs=random_test_data) == \
403
+ Min(x, y).subs(random_test_data).evalf()
404
+ assert Max(x, y).evalf(subs=random_test_data) == \
405
+ Max(x, y).subs(random_test_data).evalf()
406
+
407
+
408
+ def test_issue_12638():
409
+ from sympy.abc import a, b, c
410
+ assert Min(a, b, c, Max(a, b)) == Min(a, b, c)
411
+ assert Min(a, b, Max(a, b, c)) == Min(a, b)
412
+ assert Min(a, b, Max(a, c)) == Min(a, b)
413
+
414
+ def test_issue_21399():
415
+ from sympy.abc import a, b, c
416
+ assert Max(Min(a, b), Min(a, b, c)) == Min(a, b)
417
+
418
+
419
+ def test_instantiation_evaluation():
420
+ from sympy.abc import v, w, x, y, z
421
+ assert Min(1, Max(2, x)) == 1
422
+ assert Max(3, Min(2, x)) == 3
423
+ assert Min(Max(x, y), Max(x, z)) == Max(x, Min(y, z))
424
+ assert set(Min(Max(w, x), Max(y, z)).args) == {
425
+ Max(w, x), Max(y, z)}
426
+ assert Min(Max(x, y), Max(x, z), w) == Min(
427
+ w, Max(x, Min(y, z)))
428
+ A, B = Min, Max
429
+ for i in range(2):
430
+ assert A(x, B(x, y)) == x
431
+ assert A(x, B(y, A(x, w, z))) == A(x, B(y, A(w, z)))
432
+ A, B = B, A
433
+ assert Min(w, Max(x, y), Max(v, x, z)) == Min(
434
+ w, Max(x, Min(y, Max(v, z))))
435
+
436
+ def test_rewrite_as_Abs():
437
+ from itertools import permutations
438
+ from sympy.functions.elementary.complexes import Abs
439
+ from sympy.abc import x, y, z, w
440
+ def test(e):
441
+ free = e.free_symbols
442
+ a = e.rewrite(Abs)
443
+ assert not a.has(Min, Max)
444
+ for i in permutations(range(len(free))):
445
+ reps = dict(zip(free, i))
446
+ assert a.xreplace(reps) == e.xreplace(reps)
447
+ test(Min(x, y))
448
+ test(Max(x, y))
449
+ test(Min(x, y, z))
450
+ test(Min(Max(w, x), Max(y, z)))
451
+
452
+ def test_issue_14000():
453
+ assert isinstance(sqrt(4, evaluate=False), Pow) == True
454
+ assert isinstance(cbrt(3.5, evaluate=False), Pow) == True
455
+ assert isinstance(root(16, 4, evaluate=False), Pow) == True
456
+
457
+ assert sqrt(4, evaluate=False) == Pow(4, S.Half, evaluate=False)
458
+ assert cbrt(3.5, evaluate=False) == Pow(3.5, Rational(1, 3), evaluate=False)
459
+ assert root(4, 2, evaluate=False) == Pow(4, S.Half, evaluate=False)
460
+
461
+ assert root(16, 4, 2, evaluate=False).has(Pow) == True
462
+ assert real_root(-8, 3, evaluate=False).has(Pow) == True
463
+
464
+ def test_issue_6899():
465
+ from sympy.core.function import Lambda
466
+ x = Symbol('x')
467
+ eqn = Lambda(x, x)
468
+ assert eqn.func(*eqn.args) == eqn
469
+
470
+ def test_Rem():
471
+ from sympy.abc import x, y
472
+ assert Rem(5, 3) == 2
473
+ assert Rem(-5, 3) == -2
474
+ assert Rem(5, -3) == 2
475
+ assert Rem(-5, -3) == -2
476
+ assert Rem(x**3, y) == Rem(x**3, y)
477
+ assert Rem(Rem(-5, 3) + 3, 3) == 1
478
+
479
+
480
+ def test_minmax_no_evaluate():
481
+ from sympy import evaluate
482
+ p = Symbol('p', positive=True)
483
+
484
+ assert Max(1, 3) == 3
485
+ assert Max(1, 3).args == ()
486
+ assert Max(0, p) == p
487
+ assert Max(0, p).args == ()
488
+ assert Min(0, p) == 0
489
+ assert Min(0, p).args == ()
490
+
491
+ assert Max(1, 3, evaluate=False) != 3
492
+ assert Max(1, 3, evaluate=False).args == (1, 3)
493
+ assert Max(0, p, evaluate=False) != p
494
+ assert Max(0, p, evaluate=False).args == (0, p)
495
+ assert Min(0, p, evaluate=False) != 0
496
+ assert Min(0, p, evaluate=False).args == (0, p)
497
+
498
+ with evaluate(False):
499
+ assert Max(1, 3) != 3
500
+ assert Max(1, 3).args == (1, 3)
501
+ assert Max(0, p) != p
502
+ assert Max(0, p).args == (0, p)
503
+ assert Min(0, p) != 0
504
+ assert Min(0, p).args == (0, p)
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_piecewise.py ADDED
@@ -0,0 +1,1606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.add import Add
3
+ from sympy.core.basic import Basic
4
+ from sympy.core.containers import Tuple
5
+ from sympy.core.expr import unchanged
6
+ from sympy.core.function import (Function, diff, expand)
7
+ from sympy.core.mul import Mul
8
+ from sympy.core.mod import Mod
9
+ from sympy.core.numbers import (Float, I, Rational, oo, pi, zoo)
10
+ from sympy.core.relational import (Eq, Ge, Gt, Ne)
11
+ from sympy.core.singleton import S
12
+ from sympy.core.symbol import (Symbol, symbols)
13
+ from sympy.functions.combinatorial.factorials import factorial
14
+ from sympy.functions.elementary.complexes import (Abs, adjoint, arg, conjugate, im, re, transpose)
15
+ from sympy.functions.elementary.exponential import (exp, log)
16
+ from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
17
+ from sympy.functions.elementary.piecewise import (Piecewise,
18
+ piecewise_fold, piecewise_exclusive, Undefined, ExprCondPair)
19
+ from sympy.functions.elementary.trigonometric import (cos, sin)
20
+ from sympy.functions.special.delta_functions import (DiracDelta, Heaviside)
21
+ from sympy.functions.special.tensor_functions import KroneckerDelta
22
+ from sympy.integrals.integrals import (Integral, integrate)
23
+ from sympy.logic.boolalg import (And, ITE, Not, Or)
24
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
25
+ from sympy.printing import srepr
26
+ from sympy.sets.contains import Contains
27
+ from sympy.sets.sets import Interval
28
+ from sympy.solvers.solvers import solve
29
+ from sympy.testing.pytest import raises, slow
30
+ from sympy.utilities.lambdify import lambdify
31
+
32
+ a, b, c, d, x, y = symbols('a:d, x, y')
33
+ z = symbols('z', nonzero=True)
34
+
35
+
36
+ def test_piecewise1():
37
+
38
+ # Test canonicalization
39
+ assert unchanged(Piecewise, ExprCondPair(x, x < 1), ExprCondPair(0, True))
40
+ assert Piecewise((x, x < 1), (0, True)) == Piecewise(ExprCondPair(x, x < 1),
41
+ ExprCondPair(0, True))
42
+ assert Piecewise((x, x < 1), (0, True), (1, True)) == \
43
+ Piecewise((x, x < 1), (0, True))
44
+ assert Piecewise((x, x < 1), (0, False), (-1, 1 > 2)) == \
45
+ Piecewise((x, x < 1))
46
+ assert Piecewise((x, x < 1), (0, x < 1), (0, True)) == \
47
+ Piecewise((x, x < 1), (0, True))
48
+ assert Piecewise((x, x < 1), (0, x < 2), (0, True)) == \
49
+ Piecewise((x, x < 1), (0, True))
50
+ assert Piecewise((x, x < 1), (x, x < 2), (0, True)) == \
51
+ Piecewise((x, Or(x < 1, x < 2)), (0, True))
52
+ assert Piecewise((x, x < 1), (x, x < 2), (x, True)) == x
53
+ assert Piecewise((x, True)) == x
54
+ # Explicitly constructed empty Piecewise not accepted
55
+ raises(TypeError, lambda: Piecewise())
56
+ # False condition is never retained
57
+ assert Piecewise((2*x, x < 0), (x, False)) == \
58
+ Piecewise((2*x, x < 0), (x, False), evaluate=False) == \
59
+ Piecewise((2*x, x < 0))
60
+ assert Piecewise((x, False)) == Undefined
61
+ raises(TypeError, lambda: Piecewise(x))
62
+ assert Piecewise((x, 1)) == x # 1 and 0 are accepted as True/False
63
+ raises(TypeError, lambda: Piecewise((x, 2)))
64
+ raises(TypeError, lambda: Piecewise((x, x**2)))
65
+ raises(TypeError, lambda: Piecewise(([1], True)))
66
+ assert Piecewise(((1, 2), True)) == Tuple(1, 2)
67
+ cond = (Piecewise((1, x < 0), (2, True)) < y)
68
+ assert Piecewise((1, cond)
69
+ ) == Piecewise((1, ITE(x < 0, y > 1, y > 2)))
70
+
71
+ assert Piecewise((1, x > 0), (2, And(x <= 0, x > -1))
72
+ ) == Piecewise((1, x > 0), (2, x > -1))
73
+ assert Piecewise((1, x <= 0), (2, (x < 0) & (x > -1))
74
+ ) == Piecewise((1, x <= 0))
75
+
76
+ # test for supporting Contains in Piecewise
77
+ pwise = Piecewise(
78
+ (1, And(x <= 6, x > 1, Contains(x, S.Integers))),
79
+ (0, True))
80
+ assert pwise.subs(x, pi) == 0
81
+ assert pwise.subs(x, 2) == 1
82
+ assert pwise.subs(x, 7) == 0
83
+
84
+ # Test subs
85
+ p = Piecewise((-1, x < -1), (x**2, x < 0), (log(x), x >= 0))
86
+ p_x2 = Piecewise((-1, x**2 < -1), (x**4, x**2 < 0), (log(x**2), x**2 >= 0))
87
+ assert p.subs(x, x**2) == p_x2
88
+ assert p.subs(x, -5) == -1
89
+ assert p.subs(x, -1) == 1
90
+ assert p.subs(x, 1) == log(1)
91
+
92
+ # More subs tests
93
+ p2 = Piecewise((1, x < pi), (-1, x < 2*pi), (0, x > 2*pi))
94
+ p3 = Piecewise((1, Eq(x, 0)), (1/x, True))
95
+ p4 = Piecewise((1, Eq(x, 0)), (2, 1/x>2))
96
+ assert p2.subs(x, 2) == 1
97
+ assert p2.subs(x, 4) == -1
98
+ assert p2.subs(x, 10) == 0
99
+ assert p3.subs(x, 0.0) == 1
100
+ assert p4.subs(x, 0.0) == 1
101
+
102
+
103
+ f, g, h = symbols('f,g,h', cls=Function)
104
+ pf = Piecewise((f(x), x < -1), (f(x) + h(x) + 2, x <= 1))
105
+ pg = Piecewise((g(x), x < -1), (g(x) + h(x) + 2, x <= 1))
106
+ assert pg.subs(g, f) == pf
107
+
108
+ assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 0) == 1
109
+ assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 1) == 0
110
+ assert Piecewise((1, Eq(x, y)), (0, True)).subs(x, y) == 1
111
+ assert Piecewise((1, Eq(x, z)), (0, True)).subs(x, z) == 1
112
+ assert Piecewise((1, Eq(exp(x), cos(z))), (0, True)).subs(x, z) == \
113
+ Piecewise((1, Eq(exp(z), cos(z))), (0, True))
114
+
115
+ p5 = Piecewise( (0, Eq(cos(x) + y, 0)), (1, True))
116
+ assert p5.subs(y, 0) == Piecewise( (0, Eq(cos(x), 0)), (1, True))
117
+
118
+ assert Piecewise((-1, y < 1), (0, x < 0), (1, Eq(x, 0)), (2, True)
119
+ ).subs(x, 1) == Piecewise((-1, y < 1), (2, True))
120
+ assert Piecewise((1, Eq(x**2, -1)), (2, x < 0)).subs(x, I) == 1
121
+
122
+ p6 = Piecewise((x, x > 0))
123
+ n = symbols('n', negative=True)
124
+ assert p6.subs(x, n) == Undefined
125
+
126
+ # Test evalf
127
+ assert p.evalf() == Piecewise((-1.0, x < -1), (x**2, x < 0), (log(x), True))
128
+ assert p.evalf(subs={x: -2}) == -1.0
129
+ assert p.evalf(subs={x: -1}) == 1.0
130
+ assert p.evalf(subs={x: 1}) == log(1)
131
+ assert p6.evalf(subs={x: -5}) == Undefined
132
+
133
+ # Test doit
134
+ f_int = Piecewise((Integral(x, (x, 0, 1)), x < 1))
135
+ assert f_int.doit() == Piecewise( (S.Half, x < 1) )
136
+
137
+ # Test differentiation
138
+ f = x
139
+ fp = x*p
140
+ dp = Piecewise((0, x < -1), (2*x, x < 0), (1/x, x >= 0))
141
+ fp_dx = x*dp + p
142
+ assert diff(p, x) == dp
143
+ assert diff(f*p, x) == fp_dx
144
+
145
+ # Test simple arithmetic
146
+ assert x*p == fp
147
+ assert x*p + p == p + x*p
148
+ assert p + f == f + p
149
+ assert p + dp == dp + p
150
+ assert p - dp == -(dp - p)
151
+
152
+ # Test power
153
+ dp2 = Piecewise((0, x < -1), (4*x**2, x < 0), (1/x**2, x >= 0))
154
+ assert dp**2 == dp2
155
+
156
+ # Test _eval_interval
157
+ f1 = x*y + 2
158
+ f2 = x*y**2 + 3
159
+ peval = Piecewise((f1, x < 0), (f2, x > 0))
160
+ peval_interval = f1.subs(
161
+ x, 0) - f1.subs(x, -1) + f2.subs(x, 1) - f2.subs(x, 0)
162
+ assert peval._eval_interval(x, 0, 0) == 0
163
+ assert peval._eval_interval(x, -1, 1) == peval_interval
164
+ peval2 = Piecewise((f1, x < 0), (f2, True))
165
+ assert peval2._eval_interval(x, 0, 0) == 0
166
+ assert peval2._eval_interval(x, 1, -1) == -peval_interval
167
+ assert peval2._eval_interval(x, -1, -2) == f1.subs(x, -2) - f1.subs(x, -1)
168
+ assert peval2._eval_interval(x, -1, 1) == peval_interval
169
+ assert peval2._eval_interval(x, None, 0) == peval2.subs(x, 0)
170
+ assert peval2._eval_interval(x, -1, None) == -peval2.subs(x, -1)
171
+
172
+ # Test integration
173
+ assert p.integrate() == Piecewise(
174
+ (-x, x < -1),
175
+ (x**3/3 + Rational(4, 3), x < 0),
176
+ (x*log(x) - x + Rational(4, 3), True))
177
+ p = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x))
178
+ assert integrate(p, (x, -2, 2)) == Rational(5, 6)
179
+ assert integrate(p, (x, 2, -2)) == Rational(-5, 6)
180
+ p = Piecewise((0, x < 0), (1, x < 1), (0, x < 2), (1, x < 3), (0, True))
181
+ assert integrate(p, (x, -oo, oo)) == 2
182
+ p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x))
183
+ assert integrate(p, (x, -2, 2)) == Undefined
184
+
185
+ # Test commutativity
186
+ assert isinstance(p, Piecewise) and p.is_commutative is True
187
+
188
+
189
+ def test_piecewise_free_symbols():
190
+ f = Piecewise((x, a < 0), (y, True))
191
+ assert f.free_symbols == {x, y, a}
192
+
193
+
194
+ def test_piecewise_integrate1():
195
+ x, y = symbols('x y', real=True)
196
+
197
+ f = Piecewise(((x - 2)**2, x >= 0), (1, True))
198
+ assert integrate(f, (x, -2, 2)) == Rational(14, 3)
199
+
200
+ g = Piecewise(((x - 5)**5, x >= 4), (f, True))
201
+ assert integrate(g, (x, -2, 2)) == Rational(14, 3)
202
+ assert integrate(g, (x, -2, 5)) == Rational(43, 6)
203
+
204
+ assert g == Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
205
+
206
+ g = Piecewise(((x - 5)**5, 2 <= x), (f, x < 2))
207
+ assert integrate(g, (x, -2, 2)) == Rational(14, 3)
208
+ assert integrate(g, (x, -2, 5)) == Rational(-701, 6)
209
+
210
+ assert g == Piecewise(((x - 5)**5, 2 <= x), (f, True))
211
+
212
+ g = Piecewise(((x - 5)**5, 2 <= x), (2*f, True))
213
+ assert integrate(g, (x, -2, 2)) == Rational(28, 3)
214
+ assert integrate(g, (x, -2, 5)) == Rational(-673, 6)
215
+
216
+
217
+ def test_piecewise_integrate1b():
218
+ g = Piecewise((1, x > 0), (0, Eq(x, 0)), (-1, x < 0))
219
+ assert integrate(g, (x, -1, 1)) == 0
220
+
221
+ g = Piecewise((1, x - y < 0), (0, True))
222
+ assert integrate(g, (y, -oo, 0)) == -Min(0, x)
223
+ assert g.subs(x, -3).integrate((y, -oo, 0)) == 3
224
+ assert integrate(g, (y, 0, -oo)) == Min(0, x)
225
+ assert integrate(g, (y, 0, oo)) == -Max(0, x) + oo
226
+ assert integrate(g, (y, -oo, 42)) == -Min(42, x) + 42
227
+ assert integrate(g, (y, -oo, oo)) == -x + oo
228
+
229
+ g = Piecewise((0, x < 0), (x, x <= 1), (1, True))
230
+ gy1 = g.integrate((x, y, 1))
231
+ g1y = g.integrate((x, 1, y))
232
+ for yy in (-1, S.Half, 2):
233
+ assert g.integrate((x, yy, 1)) == gy1.subs(y, yy)
234
+ assert g.integrate((x, 1, yy)) == g1y.subs(y, yy)
235
+ assert gy1 == Piecewise(
236
+ (-Min(1, Max(0, y))**2/2 + S.Half, y < 1),
237
+ (-y + 1, True))
238
+ assert g1y == Piecewise(
239
+ (Min(1, Max(0, y))**2/2 - S.Half, y < 1),
240
+ (y - 1, True))
241
+
242
+
243
+ @slow
244
+ def test_piecewise_integrate1ca():
245
+ y = symbols('y', real=True)
246
+ g = Piecewise(
247
+ (1 - x, Interval(0, 1).contains(x)),
248
+ (1 + x, Interval(-1, 0).contains(x)),
249
+ (0, True)
250
+ )
251
+ gy1 = g.integrate((x, y, 1))
252
+ g1y = g.integrate((x, 1, y))
253
+
254
+ assert g.integrate((x, -2, 1)) == gy1.subs(y, -2)
255
+ assert g.integrate((x, 1, -2)) == g1y.subs(y, -2)
256
+ assert g.integrate((x, 0, 1)) == gy1.subs(y, 0)
257
+ assert g.integrate((x, 1, 0)) == g1y.subs(y, 0)
258
+ assert g.integrate((x, 2, 1)) == gy1.subs(y, 2)
259
+ assert g.integrate((x, 1, 2)) == g1y.subs(y, 2)
260
+ assert piecewise_fold(gy1.rewrite(Piecewise)
261
+ ).simplify() == Piecewise(
262
+ (1, y <= -1),
263
+ (-y**2/2 - y + S.Half, y <= 0),
264
+ (y**2/2 - y + S.Half, y < 1),
265
+ (0, True))
266
+ assert piecewise_fold(g1y.rewrite(Piecewise)
267
+ ).simplify() == Piecewise(
268
+ (-1, y <= -1),
269
+ (y**2/2 + y - S.Half, y <= 0),
270
+ (-y**2/2 + y - S.Half, y < 1),
271
+ (0, True))
272
+ assert gy1 == Piecewise(
273
+ (
274
+ -Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) +
275
+ Min(1, Max(0, y))**2 + S.Half, y < 1),
276
+ (0, True)
277
+ )
278
+ assert g1y == Piecewise(
279
+ (
280
+ Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) -
281
+ Min(1, Max(0, y))**2 - S.Half, y < 1),
282
+ (0, True))
283
+
284
+
285
+ @slow
286
+ def test_piecewise_integrate1cb():
287
+ y = symbols('y', real=True)
288
+ g = Piecewise(
289
+ (0, Or(x <= -1, x >= 1)),
290
+ (1 - x, x > 0),
291
+ (1 + x, True)
292
+ )
293
+ gy1 = g.integrate((x, y, 1))
294
+ g1y = g.integrate((x, 1, y))
295
+
296
+ assert g.integrate((x, -2, 1)) == gy1.subs(y, -2)
297
+ assert g.integrate((x, 1, -2)) == g1y.subs(y, -2)
298
+ assert g.integrate((x, 0, 1)) == gy1.subs(y, 0)
299
+ assert g.integrate((x, 1, 0)) == g1y.subs(y, 0)
300
+ assert g.integrate((x, 2, 1)) == gy1.subs(y, 2)
301
+ assert g.integrate((x, 1, 2)) == g1y.subs(y, 2)
302
+
303
+ assert piecewise_fold(gy1.rewrite(Piecewise)
304
+ ).simplify() == Piecewise(
305
+ (1, y <= -1),
306
+ (-y**2/2 - y + S.Half, y <= 0),
307
+ (y**2/2 - y + S.Half, y < 1),
308
+ (0, True))
309
+ assert piecewise_fold(g1y.rewrite(Piecewise)
310
+ ).simplify() == Piecewise(
311
+ (-1, y <= -1),
312
+ (y**2/2 + y - S.Half, y <= 0),
313
+ (-y**2/2 + y - S.Half, y < 1),
314
+ (0, True))
315
+
316
+ # g1y and gy1 should simplify if the condition that y < 1
317
+ # is applied, e.g. Min(1, Max(-1, y)) --> Max(-1, y)
318
+ assert gy1 == Piecewise(
319
+ (
320
+ -Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) +
321
+ Min(1, Max(0, y))**2 + S.Half, y < 1),
322
+ (0, True)
323
+ )
324
+ assert g1y == Piecewise(
325
+ (
326
+ Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) -
327
+ Min(1, Max(0, y))**2 - S.Half, y < 1),
328
+ (0, True))
329
+
330
+
331
+ def test_piecewise_integrate2():
332
+ from itertools import permutations
333
+ lim = Tuple(x, c, d)
334
+ p = Piecewise((1, x < a), (2, x > b), (3, True))
335
+ q = p.integrate(lim)
336
+ assert q == Piecewise(
337
+ (-c + 2*d - 2*Min(d, Max(a, c)) + Min(d, Max(a, b, c)), c < d),
338
+ (-2*c + d + 2*Min(c, Max(a, d)) - Min(c, Max(a, b, d)), True))
339
+ for v in permutations((1, 2, 3, 4)):
340
+ r = dict(zip((a, b, c, d), v))
341
+ assert p.subs(r).integrate(lim.subs(r)) == q.subs(r)
342
+
343
+
344
+ def test_meijer_bypass():
345
+ # totally bypass meijerg machinery when dealing
346
+ # with Piecewise in integrate
347
+ assert Piecewise((1, x < 4), (0, True)).integrate((x, oo, 1)) == -3
348
+
349
+
350
+ def test_piecewise_integrate3_inequality_conditions():
351
+ from sympy.utilities.iterables import cartes
352
+ lim = (x, 0, 5)
353
+ # set below includes two pts below range, 2 pts in range,
354
+ # 2 pts above range, and the boundaries
355
+ N = (-2, -1, 0, 1, 2, 5, 6, 7)
356
+
357
+ p = Piecewise((1, x > a), (2, x > b), (0, True))
358
+ ans = p.integrate(lim)
359
+ for i, j in cartes(N, repeat=2):
360
+ reps = dict(zip((a, b), (i, j)))
361
+ assert ans.subs(reps) == p.subs(reps).integrate(lim)
362
+ assert ans.subs(a, 4).subs(b, 1) == 0 + 2*3 + 1
363
+
364
+ p = Piecewise((1, x > a), (2, x < b), (0, True))
365
+ ans = p.integrate(lim)
366
+ for i, j in cartes(N, repeat=2):
367
+ reps = dict(zip((a, b), (i, j)))
368
+ assert ans.subs(reps) == p.subs(reps).integrate(lim)
369
+
370
+ # delete old tests that involved c1 and c2 since those
371
+ # reduce to the above except that a value of 0 was used
372
+ # for two expressions whereas the above uses 3 different
373
+ # values
374
+
375
+
376
+ @slow
377
+ def test_piecewise_integrate4_symbolic_conditions():
378
+ a = Symbol('a', real=True)
379
+ b = Symbol('b', real=True)
380
+ x = Symbol('x', real=True)
381
+ y = Symbol('y', real=True)
382
+ p0 = Piecewise((0, Or(x < a, x > b)), (1, True))
383
+ p1 = Piecewise((0, x < a), (0, x > b), (1, True))
384
+ p2 = Piecewise((0, x > b), (0, x < a), (1, True))
385
+ p3 = Piecewise((0, x < a), (1, x < b), (0, True))
386
+ p4 = Piecewise((0, x > b), (1, x > a), (0, True))
387
+ p5 = Piecewise((1, And(a < x, x < b)), (0, True))
388
+
389
+ # check values of a=1, b=3 (and reversed) with values
390
+ # of y of 0, 1, 2, 3, 4
391
+ lim = Tuple(x, -oo, y)
392
+ for p in (p0, p1, p2, p3, p4, p5):
393
+ ans = p.integrate(lim)
394
+ for i in range(5):
395
+ reps = {a:1, b:3, y:i}
396
+ assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
397
+ reps = {a: 3, b:1, y:i}
398
+ assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
399
+ lim = Tuple(x, y, oo)
400
+ for p in (p0, p1, p2, p3, p4, p5):
401
+ ans = p.integrate(lim)
402
+ for i in range(5):
403
+ reps = {a:1, b:3, y:i}
404
+ assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
405
+ reps = {a:3, b:1, y:i}
406
+ assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
407
+
408
+ ans = Piecewise(
409
+ (0, x <= Min(a, b)),
410
+ (x - Min(a, b), x <= b),
411
+ (b - Min(a, b), True))
412
+ for i in (p0, p1, p2, p4):
413
+ assert i.integrate(x) == ans
414
+ assert p3.integrate(x) == Piecewise(
415
+ (0, x < a),
416
+ (-a + x, x <= Max(a, b)),
417
+ (-a + Max(a, b), True))
418
+ assert p5.integrate(x) == Piecewise(
419
+ (0, x <= a),
420
+ (-a + x, x <= Max(a, b)),
421
+ (-a + Max(a, b), True))
422
+
423
+ p1 = Piecewise((0, x < a), (S.Half, x > b), (1, True))
424
+ p2 = Piecewise((S.Half, x > b), (0, x < a), (1, True))
425
+ p3 = Piecewise((0, x < a), (1, x < b), (S.Half, True))
426
+ p4 = Piecewise((S.Half, x > b), (1, x > a), (0, True))
427
+ p5 = Piecewise((1, And(a < x, x < b)), (S.Half, x > b), (0, True))
428
+
429
+ # check values of a=1, b=3 (and reversed) with values
430
+ # of y of 0, 1, 2, 3, 4
431
+ lim = Tuple(x, -oo, y)
432
+ for p in (p1, p2, p3, p4, p5):
433
+ ans = p.integrate(lim)
434
+ for i in range(5):
435
+ reps = {a:1, b:3, y:i}
436
+ assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
437
+ reps = {a: 3, b:1, y:i}
438
+ assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps))
439
+
440
+
441
+ def test_piecewise_integrate5_independent_conditions():
442
+ p = Piecewise((0, Eq(y, 0)), (x*y, True))
443
+ assert integrate(p, (x, 1, 3)) == Piecewise((0, Eq(y, 0)), (4*y, True))
444
+
445
+
446
+ def test_issue_22917():
447
+ p = (Piecewise((0, ITE((x - y > 1) | (2 * x - 2 * y > 1), False,
448
+ ITE(x - y > 1, 2 * y - 2 < -1, 2 * x - 2 * y > 1))),
449
+ (Piecewise((0, ITE(x - y > 1, True, 2 * x - 2 * y > 1)),
450
+ (2 * Piecewise((0, x - y > 1), (y, True)), True)), True))
451
+ + 2 * Piecewise((1, ITE((x - y > 1) | (2 * x - 2 * y > 1), False,
452
+ ITE(x - y > 1, 2 * y - 2 < -1, 2 * x - 2 * y > 1))),
453
+ (Piecewise((1, ITE(x - y > 1, True, 2 * x - 2 * y > 1)),
454
+ (2 * Piecewise((1, x - y > 1), (x, True)), True)), True)))
455
+ assert piecewise_fold(p) == Piecewise((2, (x - y > S.Half) | (x - y > 1)),
456
+ (2*y + 4, x - y > 1),
457
+ (4*x + 2*y, True))
458
+ assert piecewise_fold(p > 1).rewrite(ITE) == ITE((x - y > S.Half) | (x - y > 1), True,
459
+ ITE(x - y > 1, 2*y + 4 > 1, 4*x + 2*y > 1))
460
+
461
+
462
+ def test_piecewise_simplify():
463
+ p = Piecewise(((x**2 + 1)/x**2, Eq(x*(1 + x) - x**2, 0)),
464
+ ((-1)**x*(-1), True))
465
+ assert p.simplify() == \
466
+ Piecewise((zoo, Eq(x, 0)), ((-1)**(x + 1), True))
467
+ # simplify when there are Eq in conditions
468
+ assert Piecewise(
469
+ (a, And(Eq(a, 0), Eq(a + b, 0))), (1, True)).simplify(
470
+ ) == Piecewise(
471
+ (0, And(Eq(a, 0), Eq(b, 0))), (1, True))
472
+ assert Piecewise((2*x*factorial(a)/(factorial(y)*factorial(-y + a)),
473
+ Eq(y, 0) & Eq(-y + a, 0)), (2*factorial(a)/(factorial(y)*factorial(-y
474
+ + a)), Eq(y, 0) & Eq(-y + a, 1)), (0, True)).simplify(
475
+ ) == Piecewise(
476
+ (2*x, And(Eq(a, 0), Eq(y, 0))),
477
+ (2, And(Eq(a, 1), Eq(y, 0))),
478
+ (0, True))
479
+ args = (2, And(Eq(x, 2), Ge(y, 0))), (x, True)
480
+ assert Piecewise(*args).simplify() == Piecewise(*args)
481
+ args = (1, Eq(x, 0)), (sin(x)/x, True)
482
+ assert Piecewise(*args).simplify() == Piecewise(*args)
483
+ assert Piecewise((2 + y, And(Eq(x, 2), Eq(y, 0))), (x, True)
484
+ ).simplify() == x
485
+ # check that x or f(x) are recognized as being Symbol-like for lhs
486
+ args = Tuple((1, Eq(x, 0)), (sin(x) + 1 + x, True))
487
+ ans = x + sin(x) + 1
488
+ f = Function('f')
489
+ assert Piecewise(*args).simplify() == ans
490
+ assert Piecewise(*args.subs(x, f(x))).simplify() == ans.subs(x, f(x))
491
+
492
+ # issue 18634
493
+ d = Symbol("d", integer=True)
494
+ n = Symbol("n", integer=True)
495
+ t = Symbol("t", positive=True)
496
+ expr = Piecewise((-d + 2*n, Eq(1/t, 1)), (t**(1 - 4*n)*t**(4*n - 1)*(-d + 2*n), True))
497
+ assert expr.simplify() == -d + 2*n
498
+
499
+ # issue 22747
500
+ p = Piecewise((0, (t < -2) & (t < -1) & (t < 0)), ((t/2 + 1)*(t +
501
+ 1)*(t + 2), (t < -1) & (t < 0)), ((S.Half - t/2)*(1 - t)*(t + 1),
502
+ (t < -2) & (t < -1) & (t < 1)), ((t + 1)*(-t*(t/2 + 1) + (S.Half
503
+ - t/2)*(1 - t)), (t < -2) & (t < -1) & (t < 0) & (t < 1)), ((t +
504
+ 1)*((S.Half - t/2)*(1 - t) + (t/2 + 1)*(t + 2)), (t < -1) & (t <
505
+ 1)), ((t + 1)*(-t*(t/2 + 1) + (S.Half - t/2)*(1 - t)), (t < -1) &
506
+ (t < 0) & (t < 1)), (0, (t < -2) & (t < -1)), ((t/2 + 1)*(t +
507
+ 1)*(t + 2), t < -1), ((t + 1)*(-t*(t/2 + 1) + (S.Half - t/2)*(t +
508
+ 1)), (t < 0) & ((t < -2) | (t < 0))), ((S.Half - t/2)*(1 - t)*(t
509
+ + 1), (t < 1) & ((t < -2) | (t < 1))), (0, True)) + Piecewise((0,
510
+ (t < -1) & (t < 0) & (t < 1)), ((1 - t)*(t/2 + S.Half)*(t + 1),
511
+ (t < 0) & (t < 1)), ((1 - t)*(1 - t/2)*(2 - t), (t < -1) & (t <
512
+ 0) & (t < 2)), ((1 - t)*((1 - t)*(t/2 + S.Half) + (1 - t/2)*(2 -
513
+ t)), (t < -1) & (t < 0) & (t < 1) & (t < 2)), ((1 - t)*((1 -
514
+ t/2)*(2 - t) + (t/2 + S.Half)*(t + 1)), (t < 0) & (t < 2)), ((1 -
515
+ t)*((1 - t)*(t/2 + S.Half) + (1 - t/2)*(2 - t)), (t < 0) & (t <
516
+ 1) & (t < 2)), (0, (t < -1) & (t < 0)), ((1 - t)*(t/2 +
517
+ S.Half)*(t + 1), t < 0), ((1 - t)*(t*(1 - t/2) + (1 - t)*(t/2 +
518
+ S.Half)), (t < 1) & ((t < -1) | (t < 1))), ((1 - t)*(1 - t/2)*(2
519
+ - t), (t < 2) & ((t < -1) | (t < 2))), (0, True))
520
+ assert p.simplify() == Piecewise(
521
+ (0, t < -2), ((t + 1)*(t + 2)**2/2, t < -1), (-3*t**3/2
522
+ - 5*t**2/2 + 1, t < 0), (3*t**3/2 - 5*t**2/2 + 1, t < 1), ((1 -
523
+ t)*(t - 2)**2/2, t < 2), (0, True))
524
+
525
+ # coverage
526
+ nan = Undefined
527
+ covered = Piecewise((1, x > 3), (2, x < 2), (3, x > 1))
528
+ assert covered.simplify().args == covered.args
529
+ assert Piecewise((1, x < 2), (2, x < 1), (3, True)).simplify(
530
+ ) == Piecewise((1, x < 2), (3, True))
531
+ assert Piecewise((1, x > 2)).simplify() == Piecewise((1, x > 2),
532
+ (nan, True))
533
+ assert Piecewise((1, (x >= 2) & (x < oo))
534
+ ).simplify() == Piecewise((1, (x >= 2) & (x < oo)), (nan, True))
535
+ assert Piecewise((1, x < 2), (2, (x > 1) & (x < 3)), (3, True)
536
+ ). simplify() == Piecewise((1, x < 2), (2, x < 3), (3, True))
537
+ assert Piecewise((1, x < 2), (2, (x <= 3) & (x > 1)), (3, True)
538
+ ).simplify() == Piecewise((1, x < 2), (2, x <= 3), (3, True))
539
+ assert Piecewise((1, x < 2), (2, (x > 2) & (x < 3)), (3, True)
540
+ ).simplify() == Piecewise((1, x < 2), (2, (x > 2) & (x < 3)),
541
+ (3, True))
542
+ assert Piecewise((1, x < 2), (2, (x >= 1) & (x <= 3)), (3, True)
543
+ ).simplify() == Piecewise((1, x < 2), (2, x <= 3), (3, True))
544
+ assert Piecewise((1, x < 1), (2, (x >= 2) & (x <= 3)), (3, True)
545
+ ).simplify() == Piecewise((1, x < 1), (2, (x >= 2) & (x <= 3)),
546
+ (3, True))
547
+
548
+
549
+ def test_piecewise_solve():
550
+ abs2 = Piecewise((-x, x <= 0), (x, x > 0))
551
+ f = abs2.subs(x, x - 2)
552
+ assert solve(f, x) == [2]
553
+ assert solve(f - 1, x) == [1, 3]
554
+
555
+ f = Piecewise(((x - 2)**2, x >= 0), (1, True))
556
+ assert solve(f, x) == [2]
557
+
558
+ g = Piecewise(((x - 5)**5, x >= 4), (f, True))
559
+ assert solve(g, x) == [2, 5]
560
+
561
+ g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4))
562
+ assert solve(g, x) == [2, 5]
563
+
564
+ g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2))
565
+ assert solve(g, x) == [5]
566
+
567
+ g = Piecewise(((x - 5)**5, x >= 2), (f, True))
568
+ assert solve(g, x) == [5]
569
+
570
+ g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False))
571
+ assert solve(g, x) == [5]
572
+
573
+ g = Piecewise(((x - 5)**5, x >= 2),
574
+ (-x + 2, x - 2 <= 0), (x - 2, x - 2 > 0))
575
+ assert solve(g, x) == [5]
576
+
577
+ # if no symbol is given the piecewise detection must still work
578
+ assert solve(Piecewise((x - 2, x > 2), (2 - x, True)) - 3) == [-1, 5]
579
+
580
+ f = Piecewise(((x - 2)**2, x >= 0), (0, True))
581
+ raises(NotImplementedError, lambda: solve(f, x))
582
+
583
+ def nona(ans):
584
+ return list(filter(lambda x: x is not S.NaN, ans))
585
+ p = Piecewise((x**2 - 4, x < y), (x - 2, True))
586
+ ans = solve(p, x)
587
+ assert nona([i.subs(y, -2) for i in ans]) == [2]
588
+ assert nona([i.subs(y, 2) for i in ans]) == [-2, 2]
589
+ assert nona([i.subs(y, 3) for i in ans]) == [-2, 2]
590
+ assert ans == [
591
+ Piecewise((-2, y > -2), (S.NaN, True)),
592
+ Piecewise((2, y <= 2), (S.NaN, True)),
593
+ Piecewise((2, y > 2), (S.NaN, True))]
594
+
595
+ # issue 6060
596
+ absxm3 = Piecewise(
597
+ (x - 3, 0 <= x - 3),
598
+ (3 - x, 0 > x - 3)
599
+ )
600
+ assert solve(absxm3 - y, x) == [
601
+ Piecewise((-y + 3, -y < 0), (S.NaN, True)),
602
+ Piecewise((y + 3, y >= 0), (S.NaN, True))]
603
+ p = Symbol('p', positive=True)
604
+ assert solve(absxm3 - p, x) == [-p + 3, p + 3]
605
+
606
+ # issue 6989
607
+ f = Function('f')
608
+ assert solve(Eq(-f(x), Piecewise((1, x > 0), (0, True))), f(x)) == \
609
+ [Piecewise((-1, x > 0), (0, True))]
610
+
611
+ # issue 8587
612
+ f = Piecewise((2*x**2, And(0 < x, x < 1)), (2, True))
613
+ assert solve(f - 1) == [1/sqrt(2)]
614
+
615
+
616
+ def test_piecewise_fold():
617
+ p = Piecewise((x, x < 1), (1, 1 <= x))
618
+
619
+ assert piecewise_fold(x*p) == Piecewise((x**2, x < 1), (x, 1 <= x))
620
+ assert piecewise_fold(p + p) == Piecewise((2*x, x < 1), (2, 1 <= x))
621
+ assert piecewise_fold(Piecewise((1, x < 0), (2, True))
622
+ + Piecewise((10, x < 0), (-10, True))) == \
623
+ Piecewise((11, x < 0), (-8, True))
624
+
625
+ p1 = Piecewise((0, x < 0), (x, x <= 1), (0, True))
626
+ p2 = Piecewise((0, x < 0), (1 - x, x <= 1), (0, True))
627
+
628
+ p = 4*p1 + 2*p2
629
+ assert integrate(
630
+ piecewise_fold(p), (x, -oo, oo)) == integrate(2*x + 2, (x, 0, 1))
631
+
632
+ assert piecewise_fold(
633
+ Piecewise((1, y <= 0), (-Piecewise((2, y >= 0)), True)
634
+ )) == Piecewise((1, y <= 0), (-2, y >= 0))
635
+
636
+ assert piecewise_fold(Piecewise((x, ITE(x > 0, y < 1, y > 1)))
637
+ ) == Piecewise((x, ((x <= 0) | (y < 1)) & ((x > 0) | (y > 1))))
638
+
639
+ a, b = (Piecewise((2, Eq(x, 0)), (0, True)),
640
+ Piecewise((x, Eq(-x + y, 0)), (1, Eq(-x + y, 1)), (0, True)))
641
+ assert piecewise_fold(Mul(a, b, evaluate=False)
642
+ ) == piecewise_fold(Mul(b, a, evaluate=False))
643
+
644
+
645
+ def test_piecewise_fold_piecewise_in_cond():
646
+ p1 = Piecewise((cos(x), x < 0), (0, True))
647
+ p2 = Piecewise((0, Eq(p1, 0)), (p1 / Abs(p1), True))
648
+ assert p2.subs(x, -pi/2) == 0
649
+ assert p2.subs(x, 1) == 0
650
+ assert p2.subs(x, -pi/4) == 1
651
+ p4 = Piecewise((0, Eq(p1, 0)), (1,True))
652
+ ans = piecewise_fold(p4)
653
+ for i in range(-1, 1):
654
+ assert ans.subs(x, i) == p4.subs(x, i)
655
+
656
+ r1 = 1 < Piecewise((1, x < 1), (3, True))
657
+ ans = piecewise_fold(r1)
658
+ for i in range(2):
659
+ assert ans.subs(x, i) == r1.subs(x, i)
660
+
661
+ p5 = Piecewise((1, x < 0), (3, True))
662
+ p6 = Piecewise((1, x < 1), (3, True))
663
+ p7 = Piecewise((1, p5 < p6), (0, True))
664
+ ans = piecewise_fold(p7)
665
+ for i in range(-1, 2):
666
+ assert ans.subs(x, i) == p7.subs(x, i)
667
+
668
+
669
+ def test_piecewise_fold_piecewise_in_cond_2():
670
+ p1 = Piecewise((cos(x), x < 0), (0, True))
671
+ p2 = Piecewise((0, Eq(p1, 0)), (1 / p1, True))
672
+ p3 = Piecewise(
673
+ (0, (x >= 0) | Eq(cos(x), 0)),
674
+ (1/cos(x), x < 0),
675
+ (zoo, True)) # redundant b/c all x are already covered
676
+ assert(piecewise_fold(p2) == p3)
677
+
678
+
679
+ def test_piecewise_fold_expand():
680
+ p1 = Piecewise((1, Interval(0, 1, False, True).contains(x)), (0, True))
681
+
682
+ p2 = piecewise_fold(expand((1 - x)*p1))
683
+ cond = ((x >= 0) & (x < 1))
684
+ assert piecewise_fold(expand((1 - x)*p1), evaluate=False
685
+ ) == Piecewise((1 - x, cond), (-x, cond), (1, cond), (0, True), evaluate=False)
686
+ assert piecewise_fold(expand((1 - x)*p1), evaluate=None
687
+ ) == Piecewise((1 - x, cond), (0, True))
688
+ assert p2 == Piecewise((1 - x, cond), (0, True))
689
+ assert p2 == expand(piecewise_fold((1 - x)*p1))
690
+
691
+
692
+ def test_piecewise_duplicate():
693
+ p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x))
694
+ assert p == Piecewise(*p.args)
695
+
696
+
697
+ def test_doit():
698
+ p1 = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x))
699
+ p2 = Piecewise((x, x < 1), (Integral(2 * x), -1 <= x), (x, 3 < x))
700
+ assert p2.doit() == p1
701
+ assert p2.doit(deep=False) == p2
702
+ # issue 17165
703
+ p1 = Sum(y**x, (x, -1, oo)).doit()
704
+ assert p1.doit() == p1
705
+
706
+
707
+ def test_piecewise_interval():
708
+ p1 = Piecewise((x, Interval(0, 1).contains(x)), (0, True))
709
+ assert p1.subs(x, -0.5) == 0
710
+ assert p1.subs(x, 0.5) == 0.5
711
+ assert p1.diff(x) == Piecewise((1, Interval(0, 1).contains(x)), (0, True))
712
+ assert integrate(p1, x) == Piecewise(
713
+ (0, x <= 0),
714
+ (x**2/2, x <= 1),
715
+ (S.Half, True))
716
+
717
+
718
+ def test_piecewise_exclusive():
719
+ p = Piecewise((0, x < 0), (S.Half, x <= 0), (1, True))
720
+ assert piecewise_exclusive(p) == Piecewise((0, x < 0), (S.Half, Eq(x, 0)),
721
+ (1, x > 0), evaluate=False)
722
+ assert piecewise_exclusive(p + 2) == Piecewise((0, x < 0), (S.Half, Eq(x, 0)),
723
+ (1, x > 0), evaluate=False) + 2
724
+ assert piecewise_exclusive(Piecewise((1, y <= 0),
725
+ (-Piecewise((2, y >= 0)), True))) == \
726
+ Piecewise((1, y <= 0),
727
+ (-Piecewise((2, y >= 0),
728
+ (S.NaN, y < 0), evaluate=False), y > 0), evaluate=False)
729
+ assert piecewise_exclusive(Piecewise((1, x > y))) == Piecewise((1, x > y),
730
+ (S.NaN, x <= y),
731
+ evaluate=False)
732
+ assert piecewise_exclusive(Piecewise((1, x > y)),
733
+ skip_nan=True) == Piecewise((1, x > y))
734
+
735
+ xr, yr = symbols('xr, yr', real=True)
736
+
737
+ p1 = Piecewise((1, xr < 0), (2, True), evaluate=False)
738
+ p1x = Piecewise((1, xr < 0), (2, xr >= 0), evaluate=False)
739
+
740
+ p2 = Piecewise((p1, yr < 0), (3, True), evaluate=False)
741
+ p2x = Piecewise((p1, yr < 0), (3, yr >= 0), evaluate=False)
742
+ p2xx = Piecewise((p1x, yr < 0), (3, yr >= 0), evaluate=False)
743
+
744
+ assert piecewise_exclusive(p2) == p2xx
745
+ assert piecewise_exclusive(p2, deep=False) == p2x
746
+
747
+
748
+ def test_piecewise_collapse():
749
+ assert Piecewise((x, True)) == x
750
+ a = x < 1
751
+ assert Piecewise((x, a), (x + 1, a)) == Piecewise((x, a))
752
+ assert Piecewise((x, a), (x + 1, a.reversed)) == Piecewise((x, a))
753
+ b = x < 5
754
+ def canonical(i):
755
+ if isinstance(i, Piecewise):
756
+ return Piecewise(*i.args)
757
+ return i
758
+ for args in [
759
+ ((1, a), (Piecewise((2, a), (3, b)), b)),
760
+ ((1, a), (Piecewise((2, a), (3, b.reversed)), b)),
761
+ ((1, a), (Piecewise((2, a), (3, b)), b), (4, True)),
762
+ ((1, a), (Piecewise((2, a), (3, b), (4, True)), b)),
763
+ ((1, a), (Piecewise((2, a), (3, b), (4, True)), b), (5, True))]:
764
+ for i in (0, 2, 10):
765
+ assert canonical(
766
+ Piecewise(*args, evaluate=False).subs(x, i)
767
+ ) == canonical(Piecewise(*args).subs(x, i))
768
+ r1, r2, r3, r4 = symbols('r1:5')
769
+ a = x < r1
770
+ b = x < r2
771
+ c = x < r3
772
+ d = x < r4
773
+ assert Piecewise((1, a), (Piecewise(
774
+ (2, a), (3, b), (4, c)), b), (5, c)
775
+ ) == Piecewise((1, a), (3, b), (5, c))
776
+ assert Piecewise((1, a), (Piecewise(
777
+ (2, a), (3, b), (4, c), (6, True)), c), (5, d)
778
+ ) == Piecewise((1, a), (Piecewise(
779
+ (3, b), (4, c)), c), (5, d))
780
+ assert Piecewise((1, Or(a, d)), (Piecewise(
781
+ (2, d), (3, b), (4, c)), b), (5, c)
782
+ ) == Piecewise((1, Or(a, d)), (Piecewise(
783
+ (2, d), (3, b)), b), (5, c))
784
+ assert Piecewise((1, c), (2, ~c), (3, S.true)
785
+ ) == Piecewise((1, c), (2, S.true))
786
+ assert Piecewise((1, c), (2, And(~c, b)), (3,True)
787
+ ) == Piecewise((1, c), (2, b), (3, True))
788
+ assert Piecewise((1, c), (2, Or(~c, b)), (3,True)
789
+ ).subs(dict(zip((r1, r2, r3, r4, x), (1, 2, 3, 4, 3.5)))) == 2
790
+ assert Piecewise((1, c), (2, ~c)) == Piecewise((1, c), (2, True))
791
+
792
+
793
+ def test_piecewise_lambdify():
794
+ p = Piecewise(
795
+ (x**2, x < 0),
796
+ (x, Interval(0, 1, False, True).contains(x)),
797
+ (2 - x, x >= 1),
798
+ (0, True)
799
+ )
800
+
801
+ f = lambdify(x, p)
802
+ assert f(-2.0) == 4.0
803
+ assert f(0.0) == 0.0
804
+ assert f(0.5) == 0.5
805
+ assert f(2.0) == 0.0
806
+
807
+
808
+ def test_piecewise_series():
809
+ from sympy.series.order import O
810
+ p1 = Piecewise((sin(x), x < 0), (cos(x), x > 0))
811
+ p2 = Piecewise((x + O(x**2), x < 0), (1 + O(x**2), x > 0))
812
+ assert p1.nseries(x, n=2) == p2
813
+
814
+
815
+ def test_piecewise_as_leading_term():
816
+ p1 = Piecewise((1/x, x > 1), (0, True))
817
+ p2 = Piecewise((x, x > 1), (0, True))
818
+ p3 = Piecewise((1/x, x > 1), (x, True))
819
+ p4 = Piecewise((x, x > 1), (1/x, True))
820
+ p5 = Piecewise((1/x, x > 1), (x, True))
821
+ p6 = Piecewise((1/x, x < 1), (x, True))
822
+ p7 = Piecewise((x, x < 1), (1/x, True))
823
+ p8 = Piecewise((x, x > 1), (1/x, True))
824
+ assert p1.as_leading_term(x) == 0
825
+ assert p2.as_leading_term(x) == 0
826
+ assert p3.as_leading_term(x) == x
827
+ assert p4.as_leading_term(x) == 1/x
828
+ assert p5.as_leading_term(x) == x
829
+ assert p6.as_leading_term(x) == 1/x
830
+ assert p7.as_leading_term(x) == x
831
+ assert p8.as_leading_term(x) == 1/x
832
+
833
+
834
+ def test_piecewise_complex():
835
+ p1 = Piecewise((2, x < 0), (1, 0 <= x))
836
+ p2 = Piecewise((2*I, x < 0), (I, 0 <= x))
837
+ p3 = Piecewise((I*x, x > 1), (1 + I, True))
838
+ p4 = Piecewise((-I*conjugate(x), x > 1), (1 - I, True))
839
+
840
+ assert conjugate(p1) == p1
841
+ assert conjugate(p2) == piecewise_fold(-p2)
842
+ assert conjugate(p3) == p4
843
+
844
+ assert p1.is_imaginary is False
845
+ assert p1.is_real is True
846
+ assert p2.is_imaginary is True
847
+ assert p2.is_real is False
848
+ assert p3.is_imaginary is None
849
+ assert p3.is_real is None
850
+
851
+ assert p1.as_real_imag() == (p1, 0)
852
+ assert p2.as_real_imag() == (0, -I*p2)
853
+
854
+
855
+ def test_conjugate_transpose():
856
+ A, B = symbols("A B", commutative=False)
857
+ p = Piecewise((A*B**2, x > 0), (A**2*B, True))
858
+ assert p.adjoint() == \
859
+ Piecewise((adjoint(A*B**2), x > 0), (adjoint(A**2*B), True))
860
+ assert p.conjugate() == \
861
+ Piecewise((conjugate(A*B**2), x > 0), (conjugate(A**2*B), True))
862
+ assert p.transpose() == \
863
+ Piecewise((transpose(A*B**2), x > 0), (transpose(A**2*B), True))
864
+
865
+
866
+ def test_piecewise_evaluate():
867
+ assert Piecewise((x, True)) == x
868
+ assert Piecewise((x, True), evaluate=True) == x
869
+ assert Piecewise((1, Eq(1, x))).args == ((1, Eq(x, 1)),)
870
+ assert Piecewise((1, Eq(1, x)), evaluate=False).args == (
871
+ (1, Eq(1, x)),)
872
+ # like the additive and multiplicative identities that
873
+ # cannot be kept in Add/Mul, we also do not keep a single True
874
+ p = Piecewise((x, True), evaluate=False)
875
+ assert p == x
876
+
877
+
878
+ def test_as_expr_set_pairs():
879
+ assert Piecewise((x, x > 0), (-x, x <= 0)).as_expr_set_pairs() == \
880
+ [(x, Interval(0, oo, True, True)), (-x, Interval(-oo, 0))]
881
+
882
+ assert Piecewise(((x - 2)**2, x >= 0), (0, True)).as_expr_set_pairs() == \
883
+ [((x - 2)**2, Interval(0, oo)), (0, Interval(-oo, 0, True, True))]
884
+
885
+
886
+ def test_S_srepr_is_identity():
887
+ p = Piecewise((10, Eq(x, 0)), (12, True))
888
+ q = S(srepr(p))
889
+ assert p == q
890
+
891
+
892
+ def test_issue_12587():
893
+ # sort holes into intervals
894
+ p = Piecewise((1, x > 4), (2, Not((x <= 3) & (x > -1))), (3, True))
895
+ assert p.integrate((x, -5, 5)) == 23
896
+ p = Piecewise((1, x > 1), (2, x < y), (3, True))
897
+ lim = x, -3, 3
898
+ ans = p.integrate(lim)
899
+ for i in range(-1, 3):
900
+ assert ans.subs(y, i) == p.subs(y, i).integrate(lim)
901
+
902
+
903
+ def test_issue_11045():
904
+ assert integrate(1/(x*sqrt(x**2 - 1)), (x, 1, 2)) == pi/3
905
+
906
+ # handle And with Or arguments
907
+ assert Piecewise((1, And(Or(x < 1, x > 3), x < 2)), (0, True)
908
+ ).integrate((x, 0, 3)) == 1
909
+
910
+ # hidden false
911
+ assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)
912
+ ).integrate((x, 0, 3)) == 5
913
+ # targetcond is Eq
914
+ assert Piecewise((1, x > 1), (2, Eq(1, x)), (3, True)
915
+ ).integrate((x, 0, 4)) == 6
916
+ # And has Relational needing to be solved
917
+ assert Piecewise((1, And(2*x > x + 1, x < 2)), (0, True)
918
+ ).integrate((x, 0, 3)) == 1
919
+ # Or has Relational needing to be solved
920
+ assert Piecewise((1, Or(2*x > x + 2, x < 1)), (0, True)
921
+ ).integrate((x, 0, 3)) == 2
922
+ # ignore hidden false (handled in canonicalization)
923
+ assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)
924
+ ).integrate((x, 0, 3)) == 5
925
+ # watch for hidden True Piecewise
926
+ assert Piecewise((2, Eq(1 - x, x*(1/x - 1))), (0, True)
927
+ ).integrate((x, 0, 3)) == 6
928
+
929
+ # overlapping conditions of targetcond are recognized and ignored;
930
+ # the condition x > 3 will be pre-empted by the first condition
931
+ assert Piecewise((1, Or(x < 1, x > 2)), (2, x > 3), (3, True)
932
+ ).integrate((x, 0, 4)) == 6
933
+
934
+ # convert Ne to Or
935
+ assert Piecewise((1, Ne(x, 0)), (2, True)
936
+ ).integrate((x, -1, 1)) == 2
937
+
938
+ # no default but well defined
939
+ assert Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))
940
+ ).integrate((x, 1, 4)) == 5
941
+
942
+ p = Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4)))
943
+ nan = Undefined
944
+ i = p.integrate((x, 1, y))
945
+ assert i == Piecewise(
946
+ (y - 1, y < 1),
947
+ (Min(3, y)**2/2 - Min(3, y) + Min(4, y) - S.Half,
948
+ y <= Min(4, y)),
949
+ (nan, True))
950
+ assert p.integrate((x, 1, -1)) == i.subs(y, -1)
951
+ assert p.integrate((x, 1, 4)) == 5
952
+ assert p.integrate((x, 1, 5)) is nan
953
+
954
+ # handle Not
955
+ p = Piecewise((1, x > 1), (2, Not(And(x > 1, x< 3))), (3, True))
956
+ assert p.integrate((x, 0, 3)) == 4
957
+
958
+ # handle updating of int_expr when there is overlap
959
+ p = Piecewise(
960
+ (1, And(5 > x, x > 1)),
961
+ (2, Or(x < 3, x > 7)),
962
+ (4, x < 8))
963
+ assert p.integrate((x, 0, 10)) == 20
964
+
965
+ # And with Eq arg handling
966
+ assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1))
967
+ ).integrate((x, 0, 3)) is S.NaN
968
+ assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)), (3, True)
969
+ ).integrate((x, 0, 3)) == 7
970
+ assert Piecewise((1, x < 0), (2, And(Eq(x, 3), x < 1)), (3, True)
971
+ ).integrate((x, -1, 1)) == 4
972
+ # middle condition doesn't matter: it's a zero width interval
973
+ assert Piecewise((1, x < 1), (2, Eq(x, 3) & (y < x)), (3, True)
974
+ ).integrate((x, 0, 3)) == 7
975
+
976
+
977
+ def test_holes():
978
+ nan = Undefined
979
+ assert Piecewise((1, x < 2)).integrate(x) == Piecewise(
980
+ (x, x < 2), (nan, True))
981
+ assert Piecewise((1, And(x > 1, x < 2))).integrate(x) == Piecewise(
982
+ (nan, x < 1), (x, x < 2), (nan, True))
983
+ assert Piecewise((1, And(x > 1, x < 2))).integrate((x, 0, 3)) is nan
984
+ assert Piecewise((1, And(x > 0, x < 4))).integrate((x, 1, 3)) == 2
985
+
986
+ # this also tests that the integrate method is used on non-Piecwise
987
+ # arguments in _eval_integral
988
+ A, B = symbols("A B")
989
+ a, b = symbols('a b', real=True)
990
+ assert Piecewise((A, And(x < 0, a < 1)), (B, Or(x < 1, a > 2))
991
+ ).integrate(x) == Piecewise(
992
+ (B*x, (a > 2)),
993
+ (Piecewise((A*x, x < 0), (B*x, x < 1), (nan, True)), a < 1),
994
+ (Piecewise((B*x, x < 1), (nan, True)), True))
995
+
996
+
997
+ def test_issue_11922():
998
+ def f(x):
999
+ return Piecewise((0, x < -1), (1 - x**2, x < 1), (0, True))
1000
+ autocorr = lambda k: (
1001
+ f(x) * f(x + k)).integrate((x, -1, 1))
1002
+ assert autocorr(1.9) > 0
1003
+ k = symbols('k')
1004
+ good_autocorr = lambda k: (
1005
+ (1 - x**2) * f(x + k)).integrate((x, -1, 1))
1006
+ a = good_autocorr(k)
1007
+ assert a.subs(k, 3) == 0
1008
+ k = symbols('k', positive=True)
1009
+ a = good_autocorr(k)
1010
+ assert a.subs(k, 3) == 0
1011
+ assert Piecewise((0, x < 1), (10, (x >= 1))
1012
+ ).integrate() == Piecewise((0, x < 1), (10*x - 10, True))
1013
+
1014
+
1015
+ def test_issue_5227():
1016
+ f = 0.0032513612725229*Piecewise((0, x < -80.8461538461539),
1017
+ (-0.0160799238820171*x + 1.33215984776403, x < 2),
1018
+ (Piecewise((0.3, x > 123), (0.7, True)) +
1019
+ Piecewise((0.4, x > 2), (0.6, True)), x <=
1020
+ 123), (-0.00817409766454352*x + 2.10541401273885, x <
1021
+ 380.571428571429), (0, True))
1022
+ i = integrate(f, (x, -oo, oo))
1023
+ assert i == Integral(f, (x, -oo, oo)).doit()
1024
+ assert str(i) == '1.00195081676351'
1025
+ assert Piecewise((1, x - y < 0), (0, True)
1026
+ ).integrate(y) == Piecewise((0, y <= x), (-x + y, True))
1027
+
1028
+
1029
+ def test_issue_10137():
1030
+ a = Symbol('a', real=True)
1031
+ b = Symbol('b', real=True)
1032
+ x = Symbol('x', real=True)
1033
+ y = Symbol('y', real=True)
1034
+ p0 = Piecewise((0, Or(x < a, x > b)), (1, True))
1035
+ p1 = Piecewise((0, Or(a > x, b < x)), (1, True))
1036
+ assert integrate(p0, (x, y, oo)) == integrate(p1, (x, y, oo))
1037
+ p3 = Piecewise((1, And(0 < x, x < a)), (0, True))
1038
+ p4 = Piecewise((1, And(a > x, x > 0)), (0, True))
1039
+ ip3 = integrate(p3, x)
1040
+ assert ip3 == Piecewise(
1041
+ (0, x <= 0),
1042
+ (x, x <= Max(0, a)),
1043
+ (Max(0, a), True))
1044
+ ip4 = integrate(p4, x)
1045
+ assert ip4 == ip3
1046
+ assert p3.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2
1047
+ assert p4.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2
1048
+
1049
+
1050
+ def test_stackoverflow_43852159():
1051
+ f = lambda x: Piecewise((1, (x >= -1) & (x <= 1)), (0, True))
1052
+ Conv = lambda x: integrate(f(x - y)*f(y), (y, -oo, +oo))
1053
+ cx = Conv(x)
1054
+ assert cx.subs(x, -1.5) == cx.subs(x, 1.5)
1055
+ assert cx.subs(x, 3) == 0
1056
+ assert piecewise_fold(f(x - y)*f(y)) == Piecewise(
1057
+ (1, (y >= -1) & (y <= 1) & (x - y >= -1) & (x - y <= 1)),
1058
+ (0, True))
1059
+
1060
+
1061
+ def test_issue_12557():
1062
+ '''
1063
+ # 3200 seconds to compute the fourier part of issue
1064
+ import sympy as sym
1065
+ x,y,z,t = sym.symbols('x y z t')
1066
+ k = sym.symbols("k", integer=True)
1067
+ fourier = sym.fourier_series(sym.cos(k*x)*sym.sqrt(x**2),
1068
+ (x, -sym.pi, sym.pi))
1069
+ assert fourier == FourierSeries(
1070
+ sqrt(x**2)*cos(k*x), (x, -pi, pi), (Piecewise((pi**2,
1071
+ Eq(k, 0)), (2*(-1)**k/k**2 - 2/k**2, True))/(2*pi),
1072
+ SeqFormula(Piecewise((pi**2, (Eq(_n, 0) & Eq(k, 0)) | (Eq(_n, 0) &
1073
+ Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(k, 0) & Eq(_n, -k)) | (Eq(_n,
1074
+ 0) & Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), (pi**2/2, Eq(_n, k) | Eq(_n,
1075
+ -k) | (Eq(_n, 0) & Eq(_n, k)) | (Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) &
1076
+ Eq(_n, -k)) | (Eq(_n, k) & Eq(_n, -k)) | (Eq(k, 0) & Eq(_n, -k)) |
1077
+ (Eq(_n, 0) & Eq(_n, k) & Eq(_n, -k)) | (Eq(_n, k) & Eq(k, 0) & Eq(_n,
1078
+ -k))), ((-1)**k*pi**2*_n**3*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
1079
+ pi*k**4) - (-1)**k*pi**2*_n**3*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2
1080
+ - pi*k**4) + (-1)**k*pi*_n**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
1081
+ pi*k**4) - (-1)**k*pi*_n**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
1082
+ pi*k**4) - (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(pi*_n**4 -
1083
+ 2*pi*_n**2*k**2 + pi*k**4) +
1084
+ (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
1085
+ pi*k**4) + (-1)**k*pi*k**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
1086
+ pi*k**4) - (-1)**k*pi*k**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
1087
+ pi*k**4) - (2*_n**2 + 2*k**2)/(_n**4 - 2*_n**2*k**2 + k**4),
1088
+ True))*cos(_n*x)/pi, (_n, 1, oo)), SeqFormula(0, (_k, 1, oo))))
1089
+ '''
1090
+ x = symbols("x", real=True)
1091
+ k = symbols('k', integer=True, finite=True)
1092
+ abs2 = lambda x: Piecewise((-x, x <= 0), (x, x > 0))
1093
+ assert integrate(abs2(x), (x, -pi, pi)) == pi**2
1094
+ func = cos(k*x)*sqrt(x**2)
1095
+ assert integrate(func, (x, -pi, pi)) == Piecewise(
1096
+ (2*(-1)**k/k**2 - 2/k**2, Ne(k, 0)), (pi**2, True))
1097
+
1098
+ def test_issue_6900():
1099
+ from itertools import permutations
1100
+ t0, t1, T, t = symbols('t0, t1 T t')
1101
+ f = Piecewise((0, t < t0), (x, And(t0 <= t, t < t1)), (0, t >= t1))
1102
+ g = f.integrate(t)
1103
+ assert g == Piecewise(
1104
+ (0, t <= t0),
1105
+ (t*x - t0*x, t <= Max(t0, t1)),
1106
+ (-t0*x + x*Max(t0, t1), True))
1107
+ for i in permutations(range(2)):
1108
+ reps = dict(zip((t0,t1), i))
1109
+ for tt in range(-1,3):
1110
+ assert (g.xreplace(reps).subs(t,tt) ==
1111
+ f.xreplace(reps).integrate(t).subs(t,tt))
1112
+ lim = Tuple(t, t0, T)
1113
+ g = f.integrate(lim)
1114
+ ans = Piecewise(
1115
+ (-t0*x + x*Min(T, Max(t0, t1)), T > t0),
1116
+ (0, True))
1117
+ for i in permutations(range(3)):
1118
+ reps = dict(zip((t0,t1,T), i))
1119
+ tru = f.xreplace(reps).integrate(lim.xreplace(reps))
1120
+ assert tru == ans.xreplace(reps)
1121
+ assert g == ans
1122
+
1123
+
1124
+ def test_issue_10122():
1125
+ assert solve(abs(x) + abs(x - 1) - 1 > 0, x
1126
+ ) == Or(And(-oo < x, x < S.Zero), And(S.One < x, x < oo))
1127
+
1128
+
1129
+ def test_issue_4313():
1130
+ u = Piecewise((0, x <= 0), (1, x >= a), (x/a, True))
1131
+ e = (u - u.subs(x, y))**2/(x - y)**2
1132
+ M = Max(0, a)
1133
+ assert integrate(e, x).expand() == Piecewise(
1134
+ (Piecewise(
1135
+ (0, x <= 0),
1136
+ (-y**2/(a**2*x - a**2*y) + x/a**2 - 2*y*log(-y)/a**2 +
1137
+ 2*y*log(x - y)/a**2 - y/a**2, x <= M),
1138
+ (-y**2/(-a**2*y + a**2*M) + 1/(-y + M) -
1139
+ 1/(x - y) - 2*y*log(-y)/a**2 + 2*y*log(-y +
1140
+ M)/a**2 - y/a**2 + M/a**2, True)),
1141
+ ((a <= y) & (y <= 0)) | ((y <= 0) & (y > -oo))),
1142
+ (Piecewise(
1143
+ (-1/(x - y), x <= 0),
1144
+ (-a**2/(a**2*x - a**2*y) + 2*a*y/(a**2*x - a**2*y) -
1145
+ y**2/(a**2*x - a**2*y) + 2*log(-y)/a - 2*log(x - y)/a +
1146
+ 2/a + x/a**2 - 2*y*log(-y)/a**2 + 2*y*log(x - y)/a**2 -
1147
+ y/a**2, x <= M),
1148
+ (-a**2/(-a**2*y + a**2*M) + 2*a*y/(-a**2*y +
1149
+ a**2*M) - y**2/(-a**2*y + a**2*M) +
1150
+ 2*log(-y)/a - 2*log(-y + M)/a + 2/a -
1151
+ 2*y*log(-y)/a**2 + 2*y*log(-y + M)/a**2 -
1152
+ y/a**2 + M/a**2, True)),
1153
+ a <= y),
1154
+ (Piecewise(
1155
+ (-y**2/(a**2*x - a**2*y), x <= 0),
1156
+ (x/a**2 + y/a**2, x <= M),
1157
+ (a**2/(-a**2*y + a**2*M) -
1158
+ a**2/(a**2*x - a**2*y) - 2*a*y/(-a**2*y + a**2*M) +
1159
+ 2*a*y/(a**2*x - a**2*y) + y**2/(-a**2*y + a**2*M) -
1160
+ y**2/(a**2*x - a**2*y) + y/a**2 + M/a**2, True)),
1161
+ True))
1162
+
1163
+
1164
+ def test__intervals():
1165
+ assert Piecewise((x + 2, Eq(x, 3)))._intervals(x) == (True, [])
1166
+ assert Piecewise(
1167
+ (1, x > x + 1),
1168
+ (Piecewise((1, x < x + 1)), 2*x < 2*x + 1),
1169
+ (1, True))._intervals(x) == (True, [(-oo, oo, 1, 1)])
1170
+ assert Piecewise((1, Ne(x, I)), (0, True))._intervals(x) == (True,
1171
+ [(-oo, oo, 1, 0)])
1172
+ assert Piecewise((-cos(x), sin(x) >= 0), (cos(x), True)
1173
+ )._intervals(x) == (True,
1174
+ [(0, pi, -cos(x), 0), (-oo, oo, cos(x), 1)])
1175
+ # the following tests that duplicates are removed and that non-Eq
1176
+ # generated zero-width intervals are removed
1177
+ assert Piecewise((1, Abs(x**(-2)) > 1), (0, True)
1178
+ )._intervals(x) == (True,
1179
+ [(-1, 0, 1, 0), (0, 1, 1, 0), (-oo, oo, 0, 1)])
1180
+
1181
+
1182
+ def test_containment():
1183
+ a, b, c, d, e = [1, 2, 3, 4, 5]
1184
+ p = (Piecewise((d, x > 1), (e, True))*
1185
+ Piecewise((a, Abs(x - 1) < 1), (b, Abs(x - 2) < 2), (c, True)))
1186
+ assert p.integrate(x).diff(x) == Piecewise(
1187
+ (c*e, x <= 0),
1188
+ (a*e, x <= 1),
1189
+ (a*d, x < 2), # this is what we want to get right
1190
+ (b*d, x < 4),
1191
+ (c*d, True))
1192
+
1193
+
1194
+ def test_piecewise_with_DiracDelta():
1195
+ d1 = DiracDelta(x - 1)
1196
+ assert integrate(d1, (x, -oo, oo)) == 1
1197
+ assert integrate(d1, (x, 0, 2)) == 1
1198
+ assert Piecewise((d1, Eq(x, 2)), (0, True)).integrate(x) == 0
1199
+ assert Piecewise((d1, x < 2), (0, True)).integrate(x) == Piecewise(
1200
+ (Heaviside(x - 1), x < 2), (1, True))
1201
+ # TODO raise error if function is discontinuous at limit of
1202
+ # integration, e.g. integrate(d1, (x, -2, 1)) or Piecewise(
1203
+ # (d1, Eq(x, 1)
1204
+
1205
+
1206
+ def test_issue_10258():
1207
+ assert Piecewise((0, x < 1), (1, True)).is_zero is None
1208
+ assert Piecewise((-1, x < 1), (1, True)).is_zero is False
1209
+ a = Symbol('a', zero=True)
1210
+ assert Piecewise((0, x < 1), (a, True)).is_zero
1211
+ assert Piecewise((1, x < 1), (a, x < 3)).is_zero is None
1212
+ a = Symbol('a')
1213
+ assert Piecewise((0, x < 1), (a, True)).is_zero is None
1214
+ assert Piecewise((0, x < 1), (1, True)).is_nonzero is None
1215
+ assert Piecewise((1, x < 1), (2, True)).is_nonzero
1216
+ assert Piecewise((0, x < 1), (oo, True)).is_finite is None
1217
+ assert Piecewise((0, x < 1), (1, True)).is_finite
1218
+ b = Basic()
1219
+ assert Piecewise((b, x < 1)).is_finite is None
1220
+
1221
+ # 10258
1222
+ c = Piecewise((1, x < 0), (2, True)) < 3
1223
+ assert c != True
1224
+ assert piecewise_fold(c) == True
1225
+
1226
+
1227
+ def test_issue_10087():
1228
+ a, b = Piecewise((x, x > 1), (2, True)), Piecewise((x, x > 3), (3, True))
1229
+ m = a*b
1230
+ f = piecewise_fold(m)
1231
+ for i in (0, 2, 4):
1232
+ assert m.subs(x, i) == f.subs(x, i)
1233
+ m = a + b
1234
+ f = piecewise_fold(m)
1235
+ for i in (0, 2, 4):
1236
+ assert m.subs(x, i) == f.subs(x, i)
1237
+
1238
+
1239
+ def test_issue_8919():
1240
+ c = symbols('c:5')
1241
+ x = symbols("x")
1242
+ f1 = Piecewise((c[1], x < 1), (c[2], True))
1243
+ f2 = Piecewise((c[3], x < Rational(1, 3)), (c[4], True))
1244
+ assert integrate(f1*f2, (x, 0, 2)
1245
+ ) == c[1]*c[3]/3 + 2*c[1]*c[4]/3 + c[2]*c[4]
1246
+ f1 = Piecewise((0, x < 1), (2, True))
1247
+ f2 = Piecewise((3, x < 2), (0, True))
1248
+ assert integrate(f1*f2, (x, 0, 3)) == 6
1249
+
1250
+ y = symbols("y", positive=True)
1251
+ a, b, c, x, z = symbols("a,b,c,x,z", real=True)
1252
+ I = Integral(Piecewise(
1253
+ (0, (x >= y) | (x < 0) | (b > c)),
1254
+ (a, True)), (x, 0, z))
1255
+ ans = I.doit()
1256
+ assert ans == Piecewise((0, b > c), (a*Min(y, z) - a*Min(0, z), True))
1257
+ for cond in (True, False):
1258
+ for yy in range(1, 3):
1259
+ for zz in range(-yy, 0, yy):
1260
+ reps = [(b > c, cond), (y, yy), (z, zz)]
1261
+ assert ans.subs(reps) == I.subs(reps).doit()
1262
+
1263
+
1264
+ def test_unevaluated_integrals():
1265
+ f = Function('f')
1266
+ p = Piecewise((1, Eq(f(x) - 1, 0)), (2, x - 10 < 0), (0, True))
1267
+ assert p.integrate(x) == Integral(p, x)
1268
+ assert p.integrate((x, 0, 5)) == Integral(p, (x, 0, 5))
1269
+ # test it by replacing f(x) with x%2 which will not
1270
+ # affect the answer: the integrand is essentially 2 over
1271
+ # the domain of integration
1272
+ assert Integral(p, (x, 0, 5)).subs(f(x), x%2).n() == 10.0
1273
+
1274
+ # this is a test of using _solve_inequality when
1275
+ # solve_univariate_inequality fails
1276
+ assert p.integrate(y) == Piecewise(
1277
+ (y, Eq(f(x), 1) | ((x < 10) & Eq(f(x), 1))),
1278
+ (2*y, (x > -oo) & (x < 10)), (0, True))
1279
+
1280
+
1281
+ def test_conditions_as_alternate_booleans():
1282
+ a, b, c = symbols('a:c')
1283
+ assert Piecewise((x, Piecewise((y < 1, x > 0), (y > 1, True)))
1284
+ ) == Piecewise((x, ITE(x > 0, y < 1, y > 1)))
1285
+
1286
+
1287
+ def test_Piecewise_rewrite_as_ITE():
1288
+ a, b, c, d = symbols('a:d')
1289
+
1290
+ def _ITE(*args):
1291
+ return Piecewise(*args).rewrite(ITE)
1292
+
1293
+ assert _ITE((a, x < 1), (b, x >= 1)) == ITE(x < 1, a, b)
1294
+ assert _ITE((a, x < 1), (b, x < oo)) == ITE(x < 1, a, b)
1295
+ assert _ITE((a, x < 1), (b, Or(y < 1, x < oo)), (c, y > 0)
1296
+ ) == ITE(x < 1, a, b)
1297
+ assert _ITE((a, x < 1), (b, True)) == ITE(x < 1, a, b)
1298
+ assert _ITE((a, x < 1), (b, x < 2), (c, True)
1299
+ ) == ITE(x < 1, a, ITE(x < 2, b, c))
1300
+ assert _ITE((a, x < 1), (b, y < 2), (c, True)
1301
+ ) == ITE(x < 1, a, ITE(y < 2, b, c))
1302
+ assert _ITE((a, x < 1), (b, x < oo), (c, y < 1)
1303
+ ) == ITE(x < 1, a, b)
1304
+ assert _ITE((a, x < 1), (c, y < 1), (b, x < oo), (d, True)
1305
+ ) == ITE(x < 1, a, ITE(y < 1, c, b))
1306
+ assert _ITE((a, x < 0), (b, Or(x < oo, y < 1))
1307
+ ) == ITE(x < 0, a, b)
1308
+ raises(TypeError, lambda: _ITE((x + 1, x < 1), (x, True)))
1309
+ # if `a` in the following were replaced with y then the coverage
1310
+ # is complete but something other than as_set would need to be
1311
+ # used to detect this
1312
+ raises(NotImplementedError, lambda: _ITE((x, x < y), (y, x >= a)))
1313
+ raises(ValueError, lambda: _ITE((a, x < 2), (b, x > 3)))
1314
+
1315
+
1316
+ def test_issue_14052():
1317
+ assert integrate(abs(sin(x)), (x, 0, 2*pi)) == 4
1318
+
1319
+
1320
+ def test_issue_14240():
1321
+ assert piecewise_fold(
1322
+ Piecewise((1, a), (2, b), (4, True)) +
1323
+ Piecewise((8, a), (16, True))
1324
+ ) == Piecewise((9, a), (18, b), (20, True))
1325
+ assert piecewise_fold(
1326
+ Piecewise((2, a), (3, b), (5, True)) *
1327
+ Piecewise((7, a), (11, True))
1328
+ ) == Piecewise((14, a), (33, b), (55, True))
1329
+ # these will hang if naive folding is used
1330
+ assert piecewise_fold(Add(*[
1331
+ Piecewise((i, a), (0, True)) for i in range(40)])
1332
+ ) == Piecewise((780, a), (0, True))
1333
+ assert piecewise_fold(Mul(*[
1334
+ Piecewise((i, a), (0, True)) for i in range(1, 41)])
1335
+ ) == Piecewise((factorial(40), a), (0, True))
1336
+
1337
+
1338
+ def test_issue_14787():
1339
+ x = Symbol('x')
1340
+ f = Piecewise((x, x < 1), ((S(58) / 7), True))
1341
+ assert str(f.evalf()) == "Piecewise((x, x < 1), (8.28571428571429, True))"
1342
+
1343
+ def test_issue_21481():
1344
+ b, e = symbols('b e')
1345
+ C = Piecewise(
1346
+ (2,
1347
+ ((b > 1) & (e > 0)) |
1348
+ ((b > 0) & (b < 1) & (e < 0)) |
1349
+ ((e >= 2) & (b < -1) & Eq(Mod(e, 2), 0)) |
1350
+ ((e <= -2) & (b > -1) & (b < 0) & Eq(Mod(e, 2), 0))),
1351
+ (S.Half,
1352
+ ((b > 1) & (e < 0)) |
1353
+ ((b > 0) & (e > 0) & (b < 1)) |
1354
+ ((e <= -2) & (b < -1) & Eq(Mod(e, 2), 0)) |
1355
+ ((e >= 2) & (b > -1) & (b < 0) & Eq(Mod(e, 2), 0))),
1356
+ (-S.Half,
1357
+ Eq(Mod(e, 2), 1) &
1358
+ (((e <= -1) & (b < -1)) | ((e >= 1) & (b > -1) & (b < 0)))),
1359
+ (-2,
1360
+ ((e >= 1) & (b < -1) & Eq(Mod(e, 2), 1)) |
1361
+ ((e <= -1) & (b > -1) & (b < 0) & Eq(Mod(e, 2), 1)))
1362
+ )
1363
+ A = Piecewise(
1364
+ (1, Eq(b, 1) | Eq(e, 0) | (Eq(b, -1) & Eq(Mod(e, 2), 0))),
1365
+ (0, Eq(b, 0) & (e > 0)),
1366
+ (-1, Eq(b, -1) & Eq(Mod(e, 2), 1)),
1367
+ (C, Eq(im(b), 0) & Eq(im(e), 0))
1368
+ )
1369
+
1370
+ B = piecewise_fold(A)
1371
+ sa = A.simplify()
1372
+ sb = B.simplify()
1373
+ v = (-2, -1, -S.Half, 0, S.Half, 1, 2)
1374
+ for i in v:
1375
+ for j in v:
1376
+ r = {b:i, e:j}
1377
+ ok = [k.xreplace(r) for k in (A, B, sa, sb)]
1378
+ assert len(set(ok)) == 1
1379
+
1380
+
1381
+ def test_issue_8458():
1382
+ x, y = symbols('x y')
1383
+ # Original issue
1384
+ p1 = Piecewise((0, Eq(x, 0)), (sin(x), True))
1385
+ assert p1.simplify() == sin(x)
1386
+ # Slightly larger variant
1387
+ p2 = Piecewise((x, Eq(x, 0)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True))
1388
+ assert p2.simplify() == sin(x)
1389
+ # Test for problem highlighted during review
1390
+ p3 = Piecewise((x+1, Eq(x, -1)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True))
1391
+ assert p3.simplify() == Piecewise((0, Eq(x, -1)), (sin(x), True))
1392
+
1393
+
1394
+ def test_issue_16417():
1395
+ z = Symbol('z')
1396
+ assert unchanged(Piecewise, (1, Or(Eq(im(z), 0), Gt(re(z), 0))), (2, True))
1397
+
1398
+ x = Symbol('x')
1399
+ assert unchanged(Piecewise, (S.Pi, re(x) < 0),
1400
+ (0, Or(re(x) > 0, Ne(im(x), 0))),
1401
+ (S.NaN, True))
1402
+ r = Symbol('r', real=True)
1403
+ p = Piecewise((S.Pi, re(r) < 0),
1404
+ (0, Or(re(r) > 0, Ne(im(r), 0))),
1405
+ (S.NaN, True))
1406
+ assert p == Piecewise((S.Pi, r < 0),
1407
+ (0, r > 0),
1408
+ (S.NaN, True), evaluate=False)
1409
+ # Does not work since imaginary != 0...
1410
+ #i = Symbol('i', imaginary=True)
1411
+ #p = Piecewise((S.Pi, re(i) < 0),
1412
+ # (0, Or(re(i) > 0, Ne(im(i), 0))),
1413
+ # (S.NaN, True))
1414
+ #assert p == Piecewise((0, Ne(im(i), 0)),
1415
+ # (S.NaN, True), evaluate=False)
1416
+ i = I*r
1417
+ p = Piecewise((S.Pi, re(i) < 0),
1418
+ (0, Or(re(i) > 0, Ne(im(i), 0))),
1419
+ (S.NaN, True))
1420
+ assert p == Piecewise((0, Ne(im(i), 0)),
1421
+ (S.NaN, True), evaluate=False)
1422
+ assert p == Piecewise((0, Ne(r, 0)),
1423
+ (S.NaN, True), evaluate=False)
1424
+
1425
+
1426
+ def test_eval_rewrite_as_KroneckerDelta():
1427
+ x, y, z, n, t, m = symbols('x y z n t m')
1428
+ K = KroneckerDelta
1429
+ f = lambda p: expand(p.rewrite(K))
1430
+
1431
+ p1 = Piecewise((0, Eq(x, y)), (1, True))
1432
+ assert f(p1) == 1 - K(x, y)
1433
+
1434
+ p2 = Piecewise((x, Eq(y,0)), (z, Eq(t,0)), (n, True))
1435
+ assert f(p2) == n*K(0, t)*K(0, y) - n*K(0, t) - n*K(0, y) + n + \
1436
+ x*K(0, y) - z*K(0, t)*K(0, y) + z*K(0, t)
1437
+
1438
+ p3 = Piecewise((1, Ne(x, y)), (0, True))
1439
+ assert f(p3) == 1 - K(x, y)
1440
+
1441
+ p4 = Piecewise((1, Eq(x, 3)), (4, True), (5, True))
1442
+ assert f(p4) == 4 - 3*K(3, x)
1443
+
1444
+ p5 = Piecewise((3, Ne(x, 2)), (4, Eq(y, 2)), (5, True))
1445
+ assert f(p5) == -K(2, x)*K(2, y) + 2*K(2, x) + 3
1446
+
1447
+ p6 = Piecewise((0, Ne(x, 1) & Ne(y, 4)), (1, True))
1448
+ assert f(p6) == -K(1, x)*K(4, y) + K(1, x) + K(4, y)
1449
+
1450
+ p7 = Piecewise((2, Eq(y, 3) & Ne(x, 2)), (1, True))
1451
+ assert f(p7) == -K(2, x)*K(3, y) + K(3, y) + 1
1452
+
1453
+ p8 = Piecewise((4, Eq(x, 3) & Ne(y, 2)), (1, True))
1454
+ assert f(p8) == -3*K(2, y)*K(3, x) + 3*K(3, x) + 1
1455
+
1456
+ p9 = Piecewise((6, Eq(x, 4) & Eq(y, 1)), (1, True))
1457
+ assert f(p9) == 5 * K(1, y) * K(4, x) + 1
1458
+
1459
+ p10 = Piecewise((4, Ne(x, -4) | Ne(y, 1)), (1, True))
1460
+ assert f(p10) == -3 * K(-4, x) * K(1, y) + 4
1461
+
1462
+ p11 = Piecewise((1, Eq(y, 2) | Ne(x, -3)), (2, True))
1463
+ assert f(p11) == -K(-3, x)*K(2, y) + K(-3, x) + 1
1464
+
1465
+ p12 = Piecewise((-1, Eq(x, 1) | Ne(y, 3)), (1, True))
1466
+ assert f(p12) == -2*K(1, x)*K(3, y) + 2*K(3, y) - 1
1467
+
1468
+ p13 = Piecewise((3, Eq(x, 2) | Eq(y, 4)), (1, True))
1469
+ assert f(p13) == -2*K(2, x)*K(4, y) + 2*K(2, x) + 2*K(4, y) + 1
1470
+
1471
+ p14 = Piecewise((1, Ne(x, 0) | Ne(y, 1)), (3, True))
1472
+ assert f(p14) == 2 * K(0, x) * K(1, y) + 1
1473
+
1474
+ p15 = Piecewise((2, Eq(x, 3) | Ne(y, 2)), (3, Eq(x, 4) & Eq(y, 5)), (1, True))
1475
+ assert f(p15) == -2*K(2, y)*K(3, x)*K(4, x)*K(5, y) + K(2, y)*K(3, x) + \
1476
+ 2*K(2, y)*K(4, x)*K(5, y) - K(2, y) + 2
1477
+
1478
+ p16 = Piecewise((0, Ne(m, n)), (1, True))*Piecewise((0, Ne(n, t)), (1, True))\
1479
+ *Piecewise((0, Ne(n, x)), (1, True)) - Piecewise((0, Ne(t, x)), (1, True))
1480
+ assert f(p16) == K(m, n)*K(n, t)*K(n, x) - K(t, x)
1481
+
1482
+ p17 = Piecewise((0, Ne(t, x) & (Ne(m, n) | Ne(n, t) | Ne(n, x))),
1483
+ (1, Ne(t, x)), (-1, Ne(m, n) | Ne(n, t) | Ne(n, x)), (0, True))
1484
+ assert f(p17) == K(m, n)*K(n, t)*K(n, x) - K(t, x)
1485
+
1486
+ p18 = Piecewise((-4, Eq(y, 1) | (Eq(x, -5) & Eq(x, z))), (4, True))
1487
+ assert f(p18) == 8*K(-5, x)*K(1, y)*K(x, z) - 8*K(-5, x)*K(x, z) - 8*K(1, y) + 4
1488
+
1489
+ p19 = Piecewise((0, x > 2), (1, True))
1490
+ assert f(p19) == p19
1491
+
1492
+ p20 = Piecewise((0, And(x < 2, x > -5)), (1, True))
1493
+ assert f(p20) == p20
1494
+
1495
+ p21 = Piecewise((0, Or(x > 1, x < 0)), (1, True))
1496
+ assert f(p21) == p21
1497
+
1498
+ p22 = Piecewise((0, ~((Eq(y, -1) | Ne(x, 0)) & (Ne(x, 1) | Ne(y, -1)))), (1, True))
1499
+ assert f(p22) == K(-1, y)*K(0, x) - K(-1, y)*K(1, x) - K(0, x) + 1
1500
+
1501
+
1502
+ @slow
1503
+ def test_identical_conds_issue():
1504
+ from sympy.stats import Uniform, density
1505
+ u1 = Uniform('u1', 0, 1)
1506
+ u2 = Uniform('u2', 0, 1)
1507
+ # Result is quite big, so not really important here (and should ideally be
1508
+ # simpler). Should not give an exception though.
1509
+ density(u1 + u2)
1510
+
1511
+
1512
+ def test_issue_7370():
1513
+ f = Piecewise((1, x <= 2400))
1514
+ v = integrate(f, (x, 0, Float("252.4", 30)))
1515
+ assert str(v) == '252.400000000000000000000000000'
1516
+
1517
+
1518
+ def test_issue_14933():
1519
+ x = Symbol('x')
1520
+ y = Symbol('y')
1521
+
1522
+ inp = MatrixSymbol('inp', 1, 1)
1523
+ rep_dict = {y: inp[0, 0], x: inp[0, 0]}
1524
+
1525
+ p = Piecewise((1, ITE(y > 0, x < 0, True)))
1526
+ assert p.xreplace(rep_dict) == Piecewise((1, ITE(inp[0, 0] > 0, inp[0, 0] < 0, True)))
1527
+
1528
+
1529
+ def test_issue_16715():
1530
+ raises(NotImplementedError, lambda: Piecewise((x, x<0), (0, y>1)).as_expr_set_pairs())
1531
+
1532
+
1533
+ def test_issue_20360():
1534
+ t, tau = symbols("t tau", real=True)
1535
+ n = symbols("n", integer=True)
1536
+ lam = pi * (n - S.Half)
1537
+ eq = integrate(exp(lam * tau), (tau, 0, t))
1538
+ assert eq.simplify() == (2*exp(pi*t*(2*n - 1)/2) - 2)/(pi*(2*n - 1))
1539
+
1540
+
1541
+ def test_piecewise_eval():
1542
+ # XXX these tests might need modification if this
1543
+ # simplification is moved out of eval and into
1544
+ # boolalg or Piecewise simplification functions
1545
+ f = lambda x: x.args[0].cond
1546
+ # unsimplified
1547
+ assert f(Piecewise((x, (x > -oo) & (x < 3)))
1548
+ ) == ((x > -oo) & (x < 3))
1549
+ assert f(Piecewise((x, (x > -oo) & (x < oo)))
1550
+ ) == ((x > -oo) & (x < oo))
1551
+ assert f(Piecewise((x, (x > -3) & (x < 3)))
1552
+ ) == ((x > -3) & (x < 3))
1553
+ assert f(Piecewise((x, (x > -3) & (x < oo)))
1554
+ ) == ((x > -3) & (x < oo))
1555
+ assert f(Piecewise((x, (x <= 3) & (x > -oo)))
1556
+ ) == ((x <= 3) & (x > -oo))
1557
+ assert f(Piecewise((x, (x <= 3) & (x > -3)))
1558
+ ) == ((x <= 3) & (x > -3))
1559
+ assert f(Piecewise((x, (x >= -3) & (x < 3)))
1560
+ ) == ((x >= -3) & (x < 3))
1561
+ assert f(Piecewise((x, (x >= -3) & (x < oo)))
1562
+ ) == ((x >= -3) & (x < oo))
1563
+ assert f(Piecewise((x, (x >= -3) & (x <= 3)))
1564
+ ) == ((x >= -3) & (x <= 3))
1565
+ # could simplify by keeping only the first
1566
+ # arg of result
1567
+ assert f(Piecewise((x, (x <= oo) & (x > -oo)))
1568
+ ) == (x > -oo) & (x <= oo)
1569
+ assert f(Piecewise((x, (x <= oo) & (x > -3)))
1570
+ ) == (x > -3) & (x <= oo)
1571
+ assert f(Piecewise((x, (x >= -oo) & (x < 3)))
1572
+ ) == (x < 3) & (x >= -oo)
1573
+ assert f(Piecewise((x, (x >= -oo) & (x < oo)))
1574
+ ) == (x < oo) & (x >= -oo)
1575
+ assert f(Piecewise((x, (x >= -oo) & (x <= 3)))
1576
+ ) == (x <= 3) & (x >= -oo)
1577
+ assert f(Piecewise((x, (x >= -oo) & (x <= oo)))
1578
+ ) == (x <= oo) & (x >= -oo) # but cannot be True unless x is real
1579
+ assert f(Piecewise((x, (x >= -3) & (x <= oo)))
1580
+ ) == (x >= -3) & (x <= oo)
1581
+ assert f(Piecewise((x, (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1)))
1582
+ ) == (Abs(arg(a)) <= 1) | (Abs(arg(a)) < 1)
1583
+
1584
+
1585
+ def test_issue_22533():
1586
+ x = Symbol('x', real=True)
1587
+ f = Piecewise((-1 / x, x <= 0), (1 / x, True))
1588
+ assert integrate(f, x) == Piecewise((-log(x), x <= 0), (log(x), True))
1589
+
1590
+
1591
+ def test_issue_24072():
1592
+ assert Piecewise((1, x > 1), (2, x <= 1), (3, x <= 1)
1593
+ ) == Piecewise((1, x > 1), (2, True))
1594
+
1595
+
1596
+ def test_piecewise__eval_is_meromorphic():
1597
+ """ Issue 24127: Tests eval_is_meromorphic auxiliary method """
1598
+ x = symbols('x', real=True)
1599
+ f = Piecewise((1, x < 0), (sqrt(1 - x), True))
1600
+ assert f.is_meromorphic(x, I) is None
1601
+ assert f.is_meromorphic(x, -1) == True
1602
+ assert f.is_meromorphic(x, 0) == None
1603
+ assert f.is_meromorphic(x, 1) == False
1604
+ assert f.is_meromorphic(x, 2) == True
1605
+ assert f.is_meromorphic(x, Symbol('a')) == None
1606
+ assert f.is_meromorphic(x, Symbol('a', real=True)) == None
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_trigonometric.py ADDED
@@ -0,0 +1,2162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.calculus.accumulationbounds import AccumBounds
2
+ from sympy.core.add import Add
3
+ from sympy.core.function import (Lambda, diff)
4
+ from sympy.core.mod import Mod
5
+ from sympy.core.mul import Mul
6
+ from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
7
+ from sympy.core.power import Pow
8
+ from sympy.core.singleton import S
9
+ from sympy.core.symbol import (Symbol, symbols)
10
+ from sympy.functions.elementary.complexes import (arg, conjugate, im, re)
11
+ from sympy.functions.elementary.exponential import (exp, log)
12
+ from sympy.functions.elementary.hyperbolic import (acoth, asinh, atanh, cosh, coth, sinh, tanh)
13
+ from sympy.functions.elementary.miscellaneous import sqrt
14
+ from sympy.functions.elementary.trigonometric import (acos, acot, acsc, asec, asin, atan, atan2,
15
+ cos, cot, csc, sec, sin, sinc, tan)
16
+ from sympy.functions.special.bessel import (besselj, jn)
17
+ from sympy.functions.special.delta_functions import Heaviside
18
+ from sympy.matrices.dense import Matrix
19
+ from sympy.polys.polytools import (cancel, gcd)
20
+ from sympy.series.limits import limit
21
+ from sympy.series.order import O
22
+ from sympy.series.series import series
23
+ from sympy.sets.fancysets import ImageSet
24
+ from sympy.sets.sets import (FiniteSet, Interval)
25
+ from sympy.simplify.simplify import simplify
26
+ from sympy.core.expr import unchanged
27
+ from sympy.core.function import ArgumentIndexError
28
+ from sympy.core.relational import Ne, Eq
29
+ from sympy.functions.elementary.piecewise import Piecewise
30
+ from sympy.sets.setexpr import SetExpr
31
+ from sympy.testing.pytest import XFAIL, slow, raises
32
+
33
+
34
+ x, y, z = symbols('x y z')
35
+ r = Symbol('r', real=True)
36
+ k, m = symbols('k m', integer=True)
37
+ p = Symbol('p', positive=True)
38
+ n = Symbol('n', negative=True)
39
+ np = Symbol('p', nonpositive=True)
40
+ nn = Symbol('n', nonnegative=True)
41
+ nz = Symbol('nz', nonzero=True)
42
+ ep = Symbol('ep', extended_positive=True)
43
+ en = Symbol('en', extended_negative=True)
44
+ enp = Symbol('ep', extended_nonpositive=True)
45
+ enn = Symbol('en', extended_nonnegative=True)
46
+ enz = Symbol('enz', extended_nonzero=True)
47
+ a = Symbol('a', algebraic=True)
48
+ na = Symbol('na', nonzero=True, algebraic=True)
49
+
50
+
51
+ def test_sin():
52
+ x, y = symbols('x y')
53
+ z = symbols('z', imaginary=True)
54
+
55
+ assert sin.nargs == FiniteSet(1)
56
+ assert sin(nan) is nan
57
+ assert sin(zoo) is nan
58
+
59
+ assert sin(oo) == AccumBounds(-1, 1)
60
+ assert sin(oo) - sin(oo) == AccumBounds(-2, 2)
61
+ assert sin(oo*I) == oo*I
62
+ assert sin(-oo*I) == -oo*I
63
+ assert 0*sin(oo) is S.Zero
64
+ assert 0/sin(oo) is S.Zero
65
+ assert 0 + sin(oo) == AccumBounds(-1, 1)
66
+ assert 5 + sin(oo) == AccumBounds(4, 6)
67
+
68
+ assert sin(0) == 0
69
+
70
+ assert sin(z*I) == I*sinh(z)
71
+ assert sin(asin(x)) == x
72
+ assert sin(atan(x)) == x / sqrt(1 + x**2)
73
+ assert sin(acos(x)) == sqrt(1 - x**2)
74
+ assert sin(acot(x)) == 1 / (sqrt(1 + 1 / x**2) * x)
75
+ assert sin(acsc(x)) == 1 / x
76
+ assert sin(asec(x)) == sqrt(1 - 1 / x**2)
77
+ assert sin(atan2(y, x)) == y / sqrt(x**2 + y**2)
78
+
79
+ assert sin(pi*I) == sinh(pi)*I
80
+ assert sin(-pi*I) == -sinh(pi)*I
81
+ assert sin(-2*I) == -sinh(2)*I
82
+
83
+ assert sin(pi) == 0
84
+ assert sin(-pi) == 0
85
+ assert sin(2*pi) == 0
86
+ assert sin(-2*pi) == 0
87
+ assert sin(-3*10**73*pi) == 0
88
+ assert sin(7*10**103*pi) == 0
89
+
90
+ assert sin(pi/2) == 1
91
+ assert sin(-pi/2) == -1
92
+ assert sin(pi*Rational(5, 2)) == 1
93
+ assert sin(pi*Rational(7, 2)) == -1
94
+
95
+ ne = symbols('ne', integer=True, even=False)
96
+ e = symbols('e', even=True)
97
+ assert sin(pi*ne/2) == (-1)**(ne/2 - S.Half)
98
+ assert sin(pi*k/2).func == sin
99
+ assert sin(pi*e/2) == 0
100
+ assert sin(pi*k) == 0
101
+ assert sin(pi*k).subs(k, 3) == sin(pi*k/2).subs(k, 6) # issue 8298
102
+
103
+ assert sin(pi/3) == S.Half*sqrt(3)
104
+ assert sin(pi*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3)
105
+
106
+ assert sin(pi/4) == S.Half*sqrt(2)
107
+ assert sin(-pi/4) == Rational(-1, 2)*sqrt(2)
108
+ assert sin(pi*Rational(17, 4)) == S.Half*sqrt(2)
109
+ assert sin(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
110
+
111
+ assert sin(pi/6) == S.Half
112
+ assert sin(-pi/6) == Rational(-1, 2)
113
+ assert sin(pi*Rational(7, 6)) == Rational(-1, 2)
114
+ assert sin(pi*Rational(-5, 6)) == Rational(-1, 2)
115
+
116
+ assert sin(pi*Rational(1, 5)) == sqrt((5 - sqrt(5)) / 8)
117
+ assert sin(pi*Rational(2, 5)) == sqrt((5 + sqrt(5)) / 8)
118
+ assert sin(pi*Rational(3, 5)) == sin(pi*Rational(2, 5))
119
+ assert sin(pi*Rational(4, 5)) == sin(pi*Rational(1, 5))
120
+ assert sin(pi*Rational(6, 5)) == -sin(pi*Rational(1, 5))
121
+ assert sin(pi*Rational(8, 5)) == -sin(pi*Rational(2, 5))
122
+
123
+ assert sin(pi*Rational(-1273, 5)) == -sin(pi*Rational(2, 5))
124
+
125
+ assert sin(pi/8) == sqrt((2 - sqrt(2))/4)
126
+
127
+ assert sin(pi/10) == Rational(-1, 4) + sqrt(5)/4
128
+
129
+ assert sin(pi/12) == -sqrt(2)/4 + sqrt(6)/4
130
+ assert sin(pi*Rational(5, 12)) == sqrt(2)/4 + sqrt(6)/4
131
+ assert sin(pi*Rational(-7, 12)) == -sqrt(2)/4 - sqrt(6)/4
132
+ assert sin(pi*Rational(-11, 12)) == sqrt(2)/4 - sqrt(6)/4
133
+
134
+ assert sin(pi*Rational(104, 105)) == sin(pi/105)
135
+ assert sin(pi*Rational(106, 105)) == -sin(pi/105)
136
+
137
+ assert sin(pi*Rational(-104, 105)) == -sin(pi/105)
138
+ assert sin(pi*Rational(-106, 105)) == sin(pi/105)
139
+
140
+ assert sin(x*I) == sinh(x)*I
141
+
142
+ assert sin(k*pi) == 0
143
+ assert sin(17*k*pi) == 0
144
+ assert sin(2*k*pi + 4) == sin(4)
145
+ assert sin(2*k*pi + m*pi + 1) == (-1)**(m + 2*k)*sin(1)
146
+
147
+ assert sin(k*pi*I) == sinh(k*pi)*I
148
+
149
+ assert sin(r).is_real is True
150
+
151
+ assert sin(0, evaluate=False).is_algebraic
152
+ assert sin(a).is_algebraic is None
153
+ assert sin(na).is_algebraic is False
154
+ q = Symbol('q', rational=True)
155
+ assert sin(pi*q).is_algebraic
156
+ qn = Symbol('qn', rational=True, nonzero=True)
157
+ assert sin(qn).is_rational is False
158
+ assert sin(q).is_rational is None # issue 8653
159
+
160
+ assert isinstance(sin( re(x) - im(y)), sin) is True
161
+ assert isinstance(sin(-re(x) + im(y)), sin) is False
162
+
163
+ assert sin(SetExpr(Interval(0, 1))) == SetExpr(ImageSet(Lambda(x, sin(x)),
164
+ Interval(0, 1)))
165
+
166
+ for d in list(range(1, 22)) + [60, 85]:
167
+ for n in range(d*2 + 1):
168
+ x = n*pi/d
169
+ e = abs( float(sin(x)) - sin(float(x)) )
170
+ assert e < 1e-12
171
+
172
+ assert sin(0, evaluate=False).is_zero is True
173
+ assert sin(k*pi, evaluate=False).is_zero is True
174
+
175
+ assert sin(Add(1, -1, evaluate=False), evaluate=False).is_zero is True
176
+
177
+
178
+ def test_sin_cos():
179
+ for d in [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 24, 30, 40, 60, 120]: # list is not exhaustive...
180
+ for n in range(-2*d, d*2):
181
+ x = n*pi/d
182
+ assert sin(x + pi/2) == cos(x), "fails for %d*pi/%d" % (n, d)
183
+ assert sin(x - pi/2) == -cos(x), "fails for %d*pi/%d" % (n, d)
184
+ assert sin(x) == cos(x - pi/2), "fails for %d*pi/%d" % (n, d)
185
+ assert -sin(x) == cos(x + pi/2), "fails for %d*pi/%d" % (n, d)
186
+
187
+
188
+ def test_sin_series():
189
+ assert sin(x).series(x, 0, 9) == \
190
+ x - x**3/6 + x**5/120 - x**7/5040 + O(x**9)
191
+
192
+
193
+ def test_sin_rewrite():
194
+ assert sin(x).rewrite(exp) == -I*(exp(I*x) - exp(-I*x))/2
195
+ assert sin(x).rewrite(tan) == 2*tan(x/2)/(1 + tan(x/2)**2)
196
+ assert sin(x).rewrite(cot) == \
197
+ Piecewise((0, Eq(im(x), 0) & Eq(Mod(x, pi), 0)),
198
+ (2*cot(x/2)/(cot(x/2)**2 + 1), True))
199
+ assert sin(sinh(x)).rewrite(
200
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sinh(3)).n()
201
+ assert sin(cosh(x)).rewrite(
202
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cosh(3)).n()
203
+ assert sin(tanh(x)).rewrite(
204
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tanh(3)).n()
205
+ assert sin(coth(x)).rewrite(
206
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, coth(3)).n()
207
+ assert sin(sin(x)).rewrite(
208
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sin(3)).n()
209
+ assert sin(cos(x)).rewrite(
210
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cos(3)).n()
211
+ assert sin(tan(x)).rewrite(
212
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tan(3)).n()
213
+ assert sin(cot(x)).rewrite(
214
+ exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cot(3)).n()
215
+ assert sin(log(x)).rewrite(Pow) == I*x**-I / 2 - I*x**I /2
216
+ assert sin(x).rewrite(csc) == 1/csc(x)
217
+ assert sin(x).rewrite(cos) == cos(x - pi / 2, evaluate=False)
218
+ assert sin(x).rewrite(sec) == 1 / sec(x - pi / 2, evaluate=False)
219
+ assert sin(cos(x)).rewrite(Pow) == sin(cos(x))
220
+
221
+
222
+ def _test_extrig(f, i, e):
223
+ from sympy.core.function import expand_trig
224
+ assert unchanged(f, i)
225
+ assert expand_trig(f(i)) == f(i)
226
+ # testing directly instead of with .expand(trig=True)
227
+ # because the other expansions undo the unevaluated Mul
228
+ assert expand_trig(f(Mul(i, 1, evaluate=False))) == e
229
+ assert abs(f(i) - e).n() < 1e-10
230
+
231
+
232
+ def test_sin_expansion():
233
+ # Note: these formulas are not unique. The ones here come from the
234
+ # Chebyshev formulas.
235
+ assert sin(x + y).expand(trig=True) == sin(x)*cos(y) + cos(x)*sin(y)
236
+ assert sin(x - y).expand(trig=True) == sin(x)*cos(y) - cos(x)*sin(y)
237
+ assert sin(y - x).expand(trig=True) == cos(x)*sin(y) - sin(x)*cos(y)
238
+ assert sin(2*x).expand(trig=True) == 2*sin(x)*cos(x)
239
+ assert sin(3*x).expand(trig=True) == -4*sin(x)**3 + 3*sin(x)
240
+ assert sin(4*x).expand(trig=True) == -8*sin(x)**3*cos(x) + 4*sin(x)*cos(x)
241
+ _test_extrig(sin, 2, 2*sin(1)*cos(1))
242
+ _test_extrig(sin, 3, -4*sin(1)**3 + 3*sin(1))
243
+
244
+
245
+ def test_sin_AccumBounds():
246
+ assert sin(AccumBounds(-oo, oo)) == AccumBounds(-1, 1)
247
+ assert sin(AccumBounds(0, oo)) == AccumBounds(-1, 1)
248
+ assert sin(AccumBounds(-oo, 0)) == AccumBounds(-1, 1)
249
+ assert sin(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1)
250
+ assert sin(AccumBounds(0, S.Pi*Rational(3, 4))) == AccumBounds(0, 1)
251
+ assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(7, 4))) == AccumBounds(-1, sin(S.Pi*Rational(3, 4)))
252
+ assert sin(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(sin(S.Pi/4), sin(S.Pi/3))
253
+ assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 6))) == AccumBounds(sin(S.Pi*Rational(5, 6)), sin(S.Pi*Rational(3, 4)))
254
+
255
+
256
+ def test_sin_fdiff():
257
+ assert sin(x).fdiff() == cos(x)
258
+ raises(ArgumentIndexError, lambda: sin(x).fdiff(2))
259
+
260
+
261
+ def test_trig_symmetry():
262
+ assert sin(-x) == -sin(x)
263
+ assert cos(-x) == cos(x)
264
+ assert tan(-x) == -tan(x)
265
+ assert cot(-x) == -cot(x)
266
+ assert sin(x + pi) == -sin(x)
267
+ assert sin(x + 2*pi) == sin(x)
268
+ assert sin(x + 3*pi) == -sin(x)
269
+ assert sin(x + 4*pi) == sin(x)
270
+ assert sin(x - 5*pi) == -sin(x)
271
+ assert cos(x + pi) == -cos(x)
272
+ assert cos(x + 2*pi) == cos(x)
273
+ assert cos(x + 3*pi) == -cos(x)
274
+ assert cos(x + 4*pi) == cos(x)
275
+ assert cos(x - 5*pi) == -cos(x)
276
+ assert tan(x + pi) == tan(x)
277
+ assert tan(x - 3*pi) == tan(x)
278
+ assert cot(x + pi) == cot(x)
279
+ assert cot(x - 3*pi) == cot(x)
280
+ assert sin(pi/2 - x) == cos(x)
281
+ assert sin(pi*Rational(3, 2) - x) == -cos(x)
282
+ assert sin(pi*Rational(5, 2) - x) == cos(x)
283
+ assert cos(pi/2 - x) == sin(x)
284
+ assert cos(pi*Rational(3, 2) - x) == -sin(x)
285
+ assert cos(pi*Rational(5, 2) - x) == sin(x)
286
+ assert tan(pi/2 - x) == cot(x)
287
+ assert tan(pi*Rational(3, 2) - x) == cot(x)
288
+ assert tan(pi*Rational(5, 2) - x) == cot(x)
289
+ assert cot(pi/2 - x) == tan(x)
290
+ assert cot(pi*Rational(3, 2) - x) == tan(x)
291
+ assert cot(pi*Rational(5, 2) - x) == tan(x)
292
+ assert sin(pi/2 + x) == cos(x)
293
+ assert cos(pi/2 + x) == -sin(x)
294
+ assert tan(pi/2 + x) == -cot(x)
295
+ assert cot(pi/2 + x) == -tan(x)
296
+
297
+
298
+ def test_cos():
299
+ x, y = symbols('x y')
300
+
301
+ assert cos.nargs == FiniteSet(1)
302
+ assert cos(nan) is nan
303
+
304
+ assert cos(oo) == AccumBounds(-1, 1)
305
+ assert cos(oo) - cos(oo) == AccumBounds(-2, 2)
306
+ assert cos(oo*I) is oo
307
+ assert cos(-oo*I) is oo
308
+ assert cos(zoo) is nan
309
+
310
+ assert cos(0) == 1
311
+
312
+ assert cos(acos(x)) == x
313
+ assert cos(atan(x)) == 1 / sqrt(1 + x**2)
314
+ assert cos(asin(x)) == sqrt(1 - x**2)
315
+ assert cos(acot(x)) == 1 / sqrt(1 + 1 / x**2)
316
+ assert cos(acsc(x)) == sqrt(1 - 1 / x**2)
317
+ assert cos(asec(x)) == 1 / x
318
+ assert cos(atan2(y, x)) == x / sqrt(x**2 + y**2)
319
+
320
+ assert cos(pi*I) == cosh(pi)
321
+ assert cos(-pi*I) == cosh(pi)
322
+ assert cos(-2*I) == cosh(2)
323
+
324
+ assert cos(pi/2) == 0
325
+ assert cos(-pi/2) == 0
326
+ assert cos(pi/2) == 0
327
+ assert cos(-pi/2) == 0
328
+ assert cos((-3*10**73 + 1)*pi/2) == 0
329
+ assert cos((7*10**103 + 1)*pi/2) == 0
330
+
331
+ n = symbols('n', integer=True, even=False)
332
+ e = symbols('e', even=True)
333
+ assert cos(pi*n/2) == 0
334
+ assert cos(pi*e/2) == (-1)**(e/2)
335
+
336
+ assert cos(pi) == -1
337
+ assert cos(-pi) == -1
338
+ assert cos(2*pi) == 1
339
+ assert cos(5*pi) == -1
340
+ assert cos(8*pi) == 1
341
+
342
+ assert cos(pi/3) == S.Half
343
+ assert cos(pi*Rational(-2, 3)) == Rational(-1, 2)
344
+
345
+ assert cos(pi/4) == S.Half*sqrt(2)
346
+ assert cos(-pi/4) == S.Half*sqrt(2)
347
+ assert cos(pi*Rational(11, 4)) == Rational(-1, 2)*sqrt(2)
348
+ assert cos(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
349
+
350
+ assert cos(pi/6) == S.Half*sqrt(3)
351
+ assert cos(-pi/6) == S.Half*sqrt(3)
352
+ assert cos(pi*Rational(7, 6)) == Rational(-1, 2)*sqrt(3)
353
+ assert cos(pi*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3)
354
+
355
+ assert cos(pi*Rational(1, 5)) == (sqrt(5) + 1)/4
356
+ assert cos(pi*Rational(2, 5)) == (sqrt(5) - 1)/4
357
+ assert cos(pi*Rational(3, 5)) == -cos(pi*Rational(2, 5))
358
+ assert cos(pi*Rational(4, 5)) == -cos(pi*Rational(1, 5))
359
+ assert cos(pi*Rational(6, 5)) == -cos(pi*Rational(1, 5))
360
+ assert cos(pi*Rational(8, 5)) == cos(pi*Rational(2, 5))
361
+
362
+ assert cos(pi*Rational(-1273, 5)) == -cos(pi*Rational(2, 5))
363
+
364
+ assert cos(pi/8) == sqrt((2 + sqrt(2))/4)
365
+
366
+ assert cos(pi/12) == sqrt(2)/4 + sqrt(6)/4
367
+ assert cos(pi*Rational(5, 12)) == -sqrt(2)/4 + sqrt(6)/4
368
+ assert cos(pi*Rational(7, 12)) == sqrt(2)/4 - sqrt(6)/4
369
+ assert cos(pi*Rational(11, 12)) == -sqrt(2)/4 - sqrt(6)/4
370
+
371
+ assert cos(pi*Rational(104, 105)) == -cos(pi/105)
372
+ assert cos(pi*Rational(106, 105)) == -cos(pi/105)
373
+
374
+ assert cos(pi*Rational(-104, 105)) == -cos(pi/105)
375
+ assert cos(pi*Rational(-106, 105)) == -cos(pi/105)
376
+
377
+ assert cos(x*I) == cosh(x)
378
+ assert cos(k*pi*I) == cosh(k*pi)
379
+
380
+ assert cos(r).is_real is True
381
+
382
+ assert cos(0, evaluate=False).is_algebraic
383
+ assert cos(a).is_algebraic is None
384
+ assert cos(na).is_algebraic is False
385
+ q = Symbol('q', rational=True)
386
+ assert cos(pi*q).is_algebraic
387
+ assert cos(pi*Rational(2, 7)).is_algebraic
388
+
389
+ assert cos(k*pi) == (-1)**k
390
+ assert cos(2*k*pi) == 1
391
+ assert cos(0, evaluate=False).is_zero is False
392
+ assert cos(Rational(1, 2)).is_zero is False
393
+ # The following test will return None as the result, but really it should
394
+ # be True even if it is not always possible to resolve an assumptions query.
395
+ assert cos(asin(-1, evaluate=False), evaluate=False).is_zero is None
396
+ for d in list(range(1, 22)) + [60, 85]:
397
+ for n in range(2*d + 1):
398
+ x = n*pi/d
399
+ e = abs( float(cos(x)) - cos(float(x)) )
400
+ assert e < 1e-12
401
+
402
+
403
+ def test_issue_6190():
404
+ c = Float('123456789012345678901234567890.25', '')
405
+ for cls in [sin, cos, tan, cot]:
406
+ assert cls(c*pi) == cls(pi/4)
407
+ assert cls(4.125*pi) == cls(pi/8)
408
+ assert cls(4.7*pi) == cls((4.7 % 2)*pi)
409
+
410
+
411
+ def test_cos_series():
412
+ assert cos(x).series(x, 0, 9) == \
413
+ 1 - x**2/2 + x**4/24 - x**6/720 + x**8/40320 + O(x**9)
414
+
415
+
416
+ def test_cos_rewrite():
417
+ assert cos(x).rewrite(exp) == exp(I*x)/2 + exp(-I*x)/2
418
+ assert cos(x).rewrite(tan) == (1 - tan(x/2)**2)/(1 + tan(x/2)**2)
419
+ assert cos(x).rewrite(cot) == \
420
+ Piecewise((1, Eq(im(x), 0) & Eq(Mod(x, 2*pi), 0)),
421
+ ((cot(x/2)**2 - 1)/(cot(x/2)**2 + 1), True))
422
+ assert cos(sinh(x)).rewrite(
423
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sinh(3)).n()
424
+ assert cos(cosh(x)).rewrite(
425
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cosh(3)).n()
426
+ assert cos(tanh(x)).rewrite(
427
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tanh(3)).n()
428
+ assert cos(coth(x)).rewrite(
429
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, coth(3)).n()
430
+ assert cos(sin(x)).rewrite(
431
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sin(3)).n()
432
+ assert cos(cos(x)).rewrite(
433
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cos(3)).n()
434
+ assert cos(tan(x)).rewrite(
435
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tan(3)).n()
436
+ assert cos(cot(x)).rewrite(
437
+ exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cot(3)).n()
438
+ assert cos(log(x)).rewrite(Pow) == x**I/2 + x**-I/2
439
+ assert cos(x).rewrite(sec) == 1/sec(x)
440
+ assert cos(x).rewrite(sin) == sin(x + pi/2, evaluate=False)
441
+ assert cos(x).rewrite(csc) == 1/csc(-x + pi/2, evaluate=False)
442
+ assert cos(sin(x)).rewrite(Pow) == cos(sin(x))
443
+
444
+
445
+ def test_cos_expansion():
446
+ assert cos(x + y).expand(trig=True) == cos(x)*cos(y) - sin(x)*sin(y)
447
+ assert cos(x - y).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y)
448
+ assert cos(y - x).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y)
449
+ assert cos(2*x).expand(trig=True) == 2*cos(x)**2 - 1
450
+ assert cos(3*x).expand(trig=True) == 4*cos(x)**3 - 3*cos(x)
451
+ assert cos(4*x).expand(trig=True) == 8*cos(x)**4 - 8*cos(x)**2 + 1
452
+ _test_extrig(cos, 2, 2*cos(1)**2 - 1)
453
+ _test_extrig(cos, 3, 4*cos(1)**3 - 3*cos(1))
454
+
455
+
456
+ def test_cos_AccumBounds():
457
+ assert cos(AccumBounds(-oo, oo)) == AccumBounds(-1, 1)
458
+ assert cos(AccumBounds(0, oo)) == AccumBounds(-1, 1)
459
+ assert cos(AccumBounds(-oo, 0)) == AccumBounds(-1, 1)
460
+ assert cos(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1)
461
+ assert cos(AccumBounds(-S.Pi/3, S.Pi/4)) == AccumBounds(cos(-S.Pi/3), 1)
462
+ assert cos(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 4))) == AccumBounds(-1, cos(S.Pi*Rational(3, 4)))
463
+ assert cos(AccumBounds(S.Pi*Rational(5, 4), S.Pi*Rational(4, 3))) == AccumBounds(cos(S.Pi*Rational(5, 4)), cos(S.Pi*Rational(4, 3)))
464
+ assert cos(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(cos(S.Pi/3), cos(S.Pi/4))
465
+
466
+
467
+ def test_cos_fdiff():
468
+ assert cos(x).fdiff() == -sin(x)
469
+ raises(ArgumentIndexError, lambda: cos(x).fdiff(2))
470
+
471
+
472
+ def test_tan():
473
+ assert tan(nan) is nan
474
+
475
+ assert tan(zoo) is nan
476
+ assert tan(oo) == AccumBounds(-oo, oo)
477
+ assert tan(oo) - tan(oo) == AccumBounds(-oo, oo)
478
+ assert tan.nargs == FiniteSet(1)
479
+ assert tan(oo*I) == I
480
+ assert tan(-oo*I) == -I
481
+
482
+ assert tan(0) == 0
483
+
484
+ assert tan(atan(x)) == x
485
+ assert tan(asin(x)) == x / sqrt(1 - x**2)
486
+ assert tan(acos(x)) == sqrt(1 - x**2) / x
487
+ assert tan(acot(x)) == 1 / x
488
+ assert tan(acsc(x)) == 1 / (sqrt(1 - 1 / x**2) * x)
489
+ assert tan(asec(x)) == sqrt(1 - 1 / x**2) * x
490
+ assert tan(atan2(y, x)) == y/x
491
+
492
+ assert tan(pi*I) == tanh(pi)*I
493
+ assert tan(-pi*I) == -tanh(pi)*I
494
+ assert tan(-2*I) == -tanh(2)*I
495
+
496
+ assert tan(pi) == 0
497
+ assert tan(-pi) == 0
498
+ assert tan(2*pi) == 0
499
+ assert tan(-2*pi) == 0
500
+ assert tan(-3*10**73*pi) == 0
501
+
502
+ assert tan(pi/2) is zoo
503
+ assert tan(pi*Rational(3, 2)) is zoo
504
+
505
+ assert tan(pi/3) == sqrt(3)
506
+ assert tan(pi*Rational(-2, 3)) == sqrt(3)
507
+
508
+ assert tan(pi/4) is S.One
509
+ assert tan(-pi/4) is S.NegativeOne
510
+ assert tan(pi*Rational(17, 4)) is S.One
511
+ assert tan(pi*Rational(-3, 4)) is S.One
512
+
513
+ assert tan(pi/5) == sqrt(5 - 2*sqrt(5))
514
+ assert tan(pi*Rational(2, 5)) == sqrt(5 + 2*sqrt(5))
515
+ assert tan(pi*Rational(18, 5)) == -sqrt(5 + 2*sqrt(5))
516
+ assert tan(pi*Rational(-16, 5)) == -sqrt(5 - 2*sqrt(5))
517
+
518
+ assert tan(pi/6) == 1/sqrt(3)
519
+ assert tan(-pi/6) == -1/sqrt(3)
520
+ assert tan(pi*Rational(7, 6)) == 1/sqrt(3)
521
+ assert tan(pi*Rational(-5, 6)) == 1/sqrt(3)
522
+
523
+ assert tan(pi/8) == -1 + sqrt(2)
524
+ assert tan(pi*Rational(3, 8)) == 1 + sqrt(2) # issue 15959
525
+ assert tan(pi*Rational(5, 8)) == -1 - sqrt(2)
526
+ assert tan(pi*Rational(7, 8)) == 1 - sqrt(2)
527
+
528
+ assert tan(pi/10) == sqrt(1 - 2*sqrt(5)/5)
529
+ assert tan(pi*Rational(3, 10)) == sqrt(1 + 2*sqrt(5)/5)
530
+ assert tan(pi*Rational(17, 10)) == -sqrt(1 + 2*sqrt(5)/5)
531
+ assert tan(pi*Rational(-31, 10)) == -sqrt(1 - 2*sqrt(5)/5)
532
+
533
+ assert tan(pi/12) == -sqrt(3) + 2
534
+ assert tan(pi*Rational(5, 12)) == sqrt(3) + 2
535
+ assert tan(pi*Rational(7, 12)) == -sqrt(3) - 2
536
+ assert tan(pi*Rational(11, 12)) == sqrt(3) - 2
537
+
538
+ assert tan(pi/24).radsimp() == -2 - sqrt(3) + sqrt(2) + sqrt(6)
539
+ assert tan(pi*Rational(5, 24)).radsimp() == -2 + sqrt(3) - sqrt(2) + sqrt(6)
540
+ assert tan(pi*Rational(7, 24)).radsimp() == 2 - sqrt(3) - sqrt(2) + sqrt(6)
541
+ assert tan(pi*Rational(11, 24)).radsimp() == 2 + sqrt(3) + sqrt(2) + sqrt(6)
542
+ assert tan(pi*Rational(13, 24)).radsimp() == -2 - sqrt(3) - sqrt(2) - sqrt(6)
543
+ assert tan(pi*Rational(17, 24)).radsimp() == -2 + sqrt(3) + sqrt(2) - sqrt(6)
544
+ assert tan(pi*Rational(19, 24)).radsimp() == 2 - sqrt(3) + sqrt(2) - sqrt(6)
545
+ assert tan(pi*Rational(23, 24)).radsimp() == 2 + sqrt(3) - sqrt(2) - sqrt(6)
546
+
547
+ assert tan(x*I) == tanh(x)*I
548
+
549
+ assert tan(k*pi) == 0
550
+ assert tan(17*k*pi) == 0
551
+
552
+ assert tan(k*pi*I) == tanh(k*pi)*I
553
+
554
+ assert tan(r).is_real is None
555
+ assert tan(r).is_extended_real is True
556
+
557
+ assert tan(0, evaluate=False).is_algebraic
558
+ assert tan(a).is_algebraic is None
559
+ assert tan(na).is_algebraic is False
560
+
561
+ assert tan(pi*Rational(10, 7)) == tan(pi*Rational(3, 7))
562
+ assert tan(pi*Rational(11, 7)) == -tan(pi*Rational(3, 7))
563
+ assert tan(pi*Rational(-11, 7)) == tan(pi*Rational(3, 7))
564
+
565
+ assert tan(pi*Rational(15, 14)) == tan(pi/14)
566
+ assert tan(pi*Rational(-15, 14)) == -tan(pi/14)
567
+
568
+ assert tan(r).is_finite is None
569
+ assert tan(I*r).is_finite is True
570
+
571
+ # https://github.com/sympy/sympy/issues/21177
572
+ f = tan(pi*(x + S(3)/2))/(3*x)
573
+ assert f.as_leading_term(x) == -1/(3*pi*x**2)
574
+
575
+
576
+ def test_tan_series():
577
+ assert tan(x).series(x, 0, 9) == \
578
+ x + x**3/3 + 2*x**5/15 + 17*x**7/315 + O(x**9)
579
+
580
+
581
+ def test_tan_rewrite():
582
+ neg_exp, pos_exp = exp(-x*I), exp(x*I)
583
+ assert tan(x).rewrite(exp) == I*(neg_exp - pos_exp)/(neg_exp + pos_exp)
584
+ assert tan(x).rewrite(sin) == 2*sin(x)**2/sin(2*x)
585
+ assert tan(x).rewrite(cos) == cos(x - S.Pi/2, evaluate=False)/cos(x)
586
+ assert tan(x).rewrite(cot) == 1/cot(x)
587
+ assert tan(sinh(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sinh(3)).n()
588
+ assert tan(cosh(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cosh(3)).n()
589
+ assert tan(tanh(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tanh(3)).n()
590
+ assert tan(coth(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, coth(3)).n()
591
+ assert tan(sin(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sin(3)).n()
592
+ assert tan(cos(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cos(3)).n()
593
+ assert tan(tan(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tan(3)).n()
594
+ assert tan(cot(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cot(3)).n()
595
+ assert tan(log(x)).rewrite(Pow) == I*(x**-I - x**I)/(x**-I + x**I)
596
+ assert tan(x).rewrite(sec) == sec(x)/sec(x - pi/2, evaluate=False)
597
+ assert tan(x).rewrite(csc) == csc(-x + pi/2, evaluate=False)/csc(x)
598
+ assert tan(sin(x)).rewrite(Pow) == tan(sin(x))
599
+
600
+
601
+ @slow
602
+ def test_tan_rewrite_slow():
603
+ assert 0 == (cos(pi/34)*tan(pi/34) - sin(pi/34)).rewrite(pow)
604
+ assert 0 == (cos(pi/17)*tan(pi/17) - sin(pi/17)).rewrite(pow)
605
+ assert tan(pi/19).rewrite(pow) == tan(pi/19)
606
+ assert tan(pi*Rational(8, 19)).rewrite(sqrt) == tan(pi*Rational(8, 19))
607
+ assert tan(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == sqrt(sqrt(5)/8 +
608
+ Rational(5, 8))/(Rational(-1, 4) + sqrt(5)/4)
609
+
610
+
611
+ def test_tan_subs():
612
+ assert tan(x).subs(tan(x), y) == y
613
+ assert tan(x).subs(x, y) == tan(y)
614
+ assert tan(x).subs(x, S.Pi/2) is zoo
615
+ assert tan(x).subs(x, S.Pi*Rational(3, 2)) is zoo
616
+
617
+
618
+ def test_tan_expansion():
619
+ assert tan(x + y).expand(trig=True) == ((tan(x) + tan(y))/(1 - tan(x)*tan(y))).expand()
620
+ assert tan(x - y).expand(trig=True) == ((tan(x) - tan(y))/(1 + tan(x)*tan(y))).expand()
621
+ assert tan(x + y + z).expand(trig=True) == (
622
+ (tan(x) + tan(y) + tan(z) - tan(x)*tan(y)*tan(z))/
623
+ (1 - tan(x)*tan(y) - tan(x)*tan(z) - tan(y)*tan(z))).expand()
624
+ assert 0 == tan(2*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 7))])*24 - 7
625
+ assert 0 == tan(3*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*55 - 37
626
+ assert 0 == tan(4*x - pi/4).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*239 - 1
627
+ _test_extrig(tan, 2, 2*tan(1)/(1 - tan(1)**2))
628
+ _test_extrig(tan, 3, (-tan(1)**3 + 3*tan(1))/(1 - 3*tan(1)**2))
629
+
630
+
631
+ def test_tan_AccumBounds():
632
+ assert tan(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo)
633
+ assert tan(AccumBounds(S.Pi/3, S.Pi*Rational(2, 3))) == AccumBounds(-oo, oo)
634
+ assert tan(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(tan(S.Pi/6), tan(S.Pi/3))
635
+
636
+
637
+ def test_tan_fdiff():
638
+ assert tan(x).fdiff() == tan(x)**2 + 1
639
+ raises(ArgumentIndexError, lambda: tan(x).fdiff(2))
640
+
641
+
642
+ def test_cot():
643
+ assert cot(nan) is nan
644
+
645
+ assert cot.nargs == FiniteSet(1)
646
+ assert cot(oo*I) == -I
647
+ assert cot(-oo*I) == I
648
+ assert cot(zoo) is nan
649
+
650
+ assert cot(0) is zoo
651
+ assert cot(2*pi) is zoo
652
+
653
+ assert cot(acot(x)) == x
654
+ assert cot(atan(x)) == 1 / x
655
+ assert cot(asin(x)) == sqrt(1 - x**2) / x
656
+ assert cot(acos(x)) == x / sqrt(1 - x**2)
657
+ assert cot(acsc(x)) == sqrt(1 - 1 / x**2) * x
658
+ assert cot(asec(x)) == 1 / (sqrt(1 - 1 / x**2) * x)
659
+ assert cot(atan2(y, x)) == x/y
660
+
661
+ assert cot(pi*I) == -coth(pi)*I
662
+ assert cot(-pi*I) == coth(pi)*I
663
+ assert cot(-2*I) == coth(2)*I
664
+
665
+ assert cot(pi) == cot(2*pi) == cot(3*pi)
666
+ assert cot(-pi) == cot(-2*pi) == cot(-3*pi)
667
+
668
+ assert cot(pi/2) == 0
669
+ assert cot(-pi/2) == 0
670
+ assert cot(pi*Rational(5, 2)) == 0
671
+ assert cot(pi*Rational(7, 2)) == 0
672
+
673
+ assert cot(pi/3) == 1/sqrt(3)
674
+ assert cot(pi*Rational(-2, 3)) == 1/sqrt(3)
675
+
676
+ assert cot(pi/4) is S.One
677
+ assert cot(-pi/4) is S.NegativeOne
678
+ assert cot(pi*Rational(17, 4)) is S.One
679
+ assert cot(pi*Rational(-3, 4)) is S.One
680
+
681
+ assert cot(pi/6) == sqrt(3)
682
+ assert cot(-pi/6) == -sqrt(3)
683
+ assert cot(pi*Rational(7, 6)) == sqrt(3)
684
+ assert cot(pi*Rational(-5, 6)) == sqrt(3)
685
+
686
+ assert cot(pi/8) == 1 + sqrt(2)
687
+ assert cot(pi*Rational(3, 8)) == -1 + sqrt(2)
688
+ assert cot(pi*Rational(5, 8)) == 1 - sqrt(2)
689
+ assert cot(pi*Rational(7, 8)) == -1 - sqrt(2)
690
+
691
+ assert cot(pi/12) == sqrt(3) + 2
692
+ assert cot(pi*Rational(5, 12)) == -sqrt(3) + 2
693
+ assert cot(pi*Rational(7, 12)) == sqrt(3) - 2
694
+ assert cot(pi*Rational(11, 12)) == -sqrt(3) - 2
695
+
696
+ assert cot(pi/24).radsimp() == sqrt(2) + sqrt(3) + 2 + sqrt(6)
697
+ assert cot(pi*Rational(5, 24)).radsimp() == -sqrt(2) - sqrt(3) + 2 + sqrt(6)
698
+ assert cot(pi*Rational(7, 24)).radsimp() == -sqrt(2) + sqrt(3) - 2 + sqrt(6)
699
+ assert cot(pi*Rational(11, 24)).radsimp() == sqrt(2) - sqrt(3) - 2 + sqrt(6)
700
+ assert cot(pi*Rational(13, 24)).radsimp() == -sqrt(2) + sqrt(3) + 2 - sqrt(6)
701
+ assert cot(pi*Rational(17, 24)).radsimp() == sqrt(2) - sqrt(3) + 2 - sqrt(6)
702
+ assert cot(pi*Rational(19, 24)).radsimp() == sqrt(2) + sqrt(3) - 2 - sqrt(6)
703
+ assert cot(pi*Rational(23, 24)).radsimp() == -sqrt(2) - sqrt(3) - 2 - sqrt(6)
704
+
705
+ assert cot(x*I) == -coth(x)*I
706
+ assert cot(k*pi*I) == -coth(k*pi)*I
707
+
708
+ assert cot(r).is_real is None
709
+ assert cot(r).is_extended_real is True
710
+
711
+ assert cot(a).is_algebraic is None
712
+ assert cot(na).is_algebraic is False
713
+
714
+ assert cot(pi*Rational(10, 7)) == cot(pi*Rational(3, 7))
715
+ assert cot(pi*Rational(11, 7)) == -cot(pi*Rational(3, 7))
716
+ assert cot(pi*Rational(-11, 7)) == cot(pi*Rational(3, 7))
717
+
718
+ assert cot(pi*Rational(39, 34)) == cot(pi*Rational(5, 34))
719
+ assert cot(pi*Rational(-41, 34)) == -cot(pi*Rational(7, 34))
720
+
721
+ assert cot(x).is_finite is None
722
+ assert cot(r).is_finite is None
723
+ i = Symbol('i', imaginary=True)
724
+ assert cot(i).is_finite is True
725
+
726
+ assert cot(x).subs(x, 3*pi) is zoo
727
+
728
+ # https://github.com/sympy/sympy/issues/21177
729
+ f = cot(pi*(x + 4))/(3*x)
730
+ assert f.as_leading_term(x) == 1/(3*pi*x**2)
731
+
732
+
733
+ def test_tan_cot_sin_cos_evalf():
734
+ assert abs((tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15)) - 1).evalf()) < 1e-14
735
+ assert abs((cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15)) - 1).evalf()) < 1e-14
736
+
737
+ @XFAIL
738
+ def test_tan_cot_sin_cos_ratsimp():
739
+ assert 1 == (tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15))).ratsimp()
740
+ assert 1 == (cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15))).ratsimp()
741
+
742
+
743
+ def test_cot_series():
744
+ assert cot(x).series(x, 0, 9) == \
745
+ 1/x - x/3 - x**3/45 - 2*x**5/945 - x**7/4725 + O(x**9)
746
+ # issue 6210
747
+ assert cot(x**4 + x**5).series(x, 0, 1) == \
748
+ x**(-4) - 1/x**3 + x**(-2) - 1/x + 1 + O(x)
749
+ assert cot(pi*(1-x)).series(x, 0, 3) == -1/(pi*x) + pi*x/3 + O(x**3)
750
+ assert cot(x).taylor_term(0, x) == 1/x
751
+ assert cot(x).taylor_term(2, x) is S.Zero
752
+ assert cot(x).taylor_term(3, x) == -x**3/45
753
+
754
+
755
+ def test_cot_rewrite():
756
+ neg_exp, pos_exp = exp(-x*I), exp(x*I)
757
+ assert cot(x).rewrite(exp) == I*(pos_exp + neg_exp)/(pos_exp - neg_exp)
758
+ assert cot(x).rewrite(sin) == sin(2*x)/(2*(sin(x)**2))
759
+ assert cot(x).rewrite(cos) == cos(x)/cos(x - pi/2, evaluate=False)
760
+ assert cot(x).rewrite(tan) == 1/tan(x)
761
+ def check(func):
762
+ z = cot(func(x)).rewrite(exp) - cot(x).rewrite(exp).subs(x, func(x))
763
+ assert z.rewrite(exp).expand() == 0
764
+ check(sinh)
765
+ check(cosh)
766
+ check(tanh)
767
+ check(coth)
768
+ check(sin)
769
+ check(cos)
770
+ check(tan)
771
+ assert cot(log(x)).rewrite(Pow) == -I*(x**-I + x**I)/(x**-I - x**I)
772
+ assert cot(x).rewrite(sec) == sec(x - pi / 2, evaluate=False) / sec(x)
773
+ assert cot(x).rewrite(csc) == csc(x) / csc(- x + pi / 2, evaluate=False)
774
+ assert cot(sin(x)).rewrite(Pow) == cot(sin(x))
775
+
776
+
777
+ @slow
778
+ def test_cot_rewrite_slow():
779
+ assert cot(pi*Rational(4, 34)).rewrite(pow).ratsimp() == \
780
+ (cos(pi*Rational(4, 34))/sin(pi*Rational(4, 34))).rewrite(pow).ratsimp()
781
+ assert cot(pi*Rational(4, 17)).rewrite(pow) == \
782
+ (cos(pi*Rational(4, 17))/sin(pi*Rational(4, 17))).rewrite(pow)
783
+ assert cot(pi/19).rewrite(pow) == cot(pi/19)
784
+ assert cot(pi/19).rewrite(sqrt) == cot(pi/19)
785
+ assert cot(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == \
786
+ (Rational(-1, 4) + sqrt(5)/4) / sqrt(sqrt(5)/8 + Rational(5, 8))
787
+
788
+
789
+ def test_cot_subs():
790
+ assert cot(x).subs(cot(x), y) == y
791
+ assert cot(x).subs(x, y) == cot(y)
792
+ assert cot(x).subs(x, 0) is zoo
793
+ assert cot(x).subs(x, S.Pi) is zoo
794
+
795
+
796
+ def test_cot_expansion():
797
+ assert cot(x + y).expand(trig=True).together() == (
798
+ (cot(x)*cot(y) - 1)/(cot(x) + cot(y)))
799
+ assert cot(x - y).expand(trig=True).together() == (
800
+ cot(x)*cot(-y) - 1)/(cot(x) + cot(-y))
801
+ assert cot(x + y + z).expand(trig=True).together() == (
802
+ (cot(x)*cot(y)*cot(z) - cot(x) - cot(y) - cot(z))/
803
+ (-1 + cot(x)*cot(y) + cot(x)*cot(z) + cot(y)*cot(z)))
804
+ assert cot(3*x).expand(trig=True).together() == (
805
+ (cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1))
806
+ assert cot(2*x).expand(trig=True) == cot(x)/2 - 1/(2*cot(x))
807
+ assert cot(3*x).expand(trig=True).together() == (
808
+ cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1)
809
+ assert cot(4*x - pi/4).expand(trig=True).cancel() == (
810
+ -tan(x)**4 + 4*tan(x)**3 + 6*tan(x)**2 - 4*tan(x) - 1
811
+ )/(tan(x)**4 + 4*tan(x)**3 - 6*tan(x)**2 - 4*tan(x) + 1)
812
+ _test_extrig(cot, 2, (-1 + cot(1)**2)/(2*cot(1)))
813
+ _test_extrig(cot, 3, (-3*cot(1) + cot(1)**3)/(-1 + 3*cot(1)**2))
814
+
815
+
816
+ def test_cot_AccumBounds():
817
+ assert cot(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo)
818
+ assert cot(AccumBounds(-S.Pi/3, S.Pi/3)) == AccumBounds(-oo, oo)
819
+ assert cot(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(cot(S.Pi/3), cot(S.Pi/6))
820
+
821
+
822
+ def test_cot_fdiff():
823
+ assert cot(x).fdiff() == -cot(x)**2 - 1
824
+ raises(ArgumentIndexError, lambda: cot(x).fdiff(2))
825
+
826
+
827
+ def test_sinc():
828
+ assert isinstance(sinc(x), sinc)
829
+
830
+ s = Symbol('s', zero=True)
831
+ assert sinc(s) is S.One
832
+ assert sinc(S.Infinity) is S.Zero
833
+ assert sinc(S.NegativeInfinity) is S.Zero
834
+ assert sinc(S.NaN) is S.NaN
835
+ assert sinc(S.ComplexInfinity) is S.NaN
836
+
837
+ n = Symbol('n', integer=True, nonzero=True)
838
+ assert sinc(n*pi) is S.Zero
839
+ assert sinc(-n*pi) is S.Zero
840
+ assert sinc(pi/2) == 2 / pi
841
+ assert sinc(-pi/2) == 2 / pi
842
+ assert sinc(pi*Rational(5, 2)) == 2 / (5*pi)
843
+ assert sinc(pi*Rational(7, 2)) == -2 / (7*pi)
844
+
845
+ assert sinc(-x) == sinc(x)
846
+
847
+ assert sinc(x).diff(x) == cos(x)/x - sin(x)/x**2
848
+ assert sinc(x).diff(x) == (sin(x)/x).diff(x)
849
+ assert sinc(x).diff(x, x) == (-sin(x) - 2*cos(x)/x + 2*sin(x)/x**2)/x
850
+ assert sinc(x).diff(x, x) == (sin(x)/x).diff(x, x)
851
+ assert limit(sinc(x).diff(x), x, 0) == 0
852
+ assert limit(sinc(x).diff(x, x), x, 0) == -S(1)/3
853
+
854
+ # https://github.com/sympy/sympy/issues/11402
855
+ #
856
+ # assert sinc(x).diff(x) == Piecewise(((x*cos(x) - sin(x)) / x**2, Ne(x, 0)), (0, True))
857
+ #
858
+ # assert sinc(x).diff(x).equals(sinc(x).rewrite(sin).diff(x))
859
+ #
860
+ # assert sinc(x).diff(x).subs(x, 0) is S.Zero
861
+
862
+ assert sinc(x).series() == 1 - x**2/6 + x**4/120 + O(x**6)
863
+
864
+ assert sinc(x).rewrite(jn) == jn(0, x)
865
+ assert sinc(x).rewrite(sin) == Piecewise((sin(x)/x, Ne(x, 0)), (1, True))
866
+ assert sinc(pi, evaluate=False).is_zero is True
867
+ assert sinc(0, evaluate=False).is_zero is False
868
+ assert sinc(n*pi, evaluate=False).is_zero is True
869
+ assert sinc(x).is_zero is None
870
+ xr = Symbol('xr', real=True, nonzero=True)
871
+ assert sinc(x).is_real is None
872
+ assert sinc(xr).is_real is True
873
+ assert sinc(I*xr).is_real is True
874
+ assert sinc(I*100).is_real is True
875
+ assert sinc(x).is_finite is None
876
+ assert sinc(xr).is_finite is True
877
+
878
+
879
+ def test_asin():
880
+ assert asin(nan) is nan
881
+
882
+ assert asin.nargs == FiniteSet(1)
883
+ assert asin(oo) == -I*oo
884
+ assert asin(-oo) == I*oo
885
+ assert asin(zoo) is zoo
886
+
887
+ # Note: asin(-x) = - asin(x)
888
+ assert asin(0) == 0
889
+ assert asin(1) == pi/2
890
+ assert asin(-1) == -pi/2
891
+ assert asin(sqrt(3)/2) == pi/3
892
+ assert asin(-sqrt(3)/2) == -pi/3
893
+ assert asin(sqrt(2)/2) == pi/4
894
+ assert asin(-sqrt(2)/2) == -pi/4
895
+ assert asin(sqrt((5 - sqrt(5))/8)) == pi/5
896
+ assert asin(-sqrt((5 - sqrt(5))/8)) == -pi/5
897
+ assert asin(S.Half) == pi/6
898
+ assert asin(Rational(-1, 2)) == -pi/6
899
+ assert asin((sqrt(2 - sqrt(2)))/2) == pi/8
900
+ assert asin(-(sqrt(2 - sqrt(2)))/2) == -pi/8
901
+ assert asin((sqrt(5) - 1)/4) == pi/10
902
+ assert asin(-(sqrt(5) - 1)/4) == -pi/10
903
+ assert asin((sqrt(3) - 1)/sqrt(2**3)) == pi/12
904
+ assert asin(-(sqrt(3) - 1)/sqrt(2**3)) == -pi/12
905
+
906
+ # check round-trip for exact values:
907
+ for d in [5, 6, 8, 10, 12]:
908
+ for n in range(-(d//2), d//2 + 1):
909
+ if gcd(n, d) == 1:
910
+ assert asin(sin(n*pi/d)) == n*pi/d
911
+
912
+ assert asin(x).diff(x) == 1/sqrt(1 - x**2)
913
+
914
+ assert asin(0.2, evaluate=False).is_real is True
915
+ assert asin(-2).is_real is False
916
+ assert asin(r).is_real is None
917
+
918
+ assert asin(-2*I) == -I*asinh(2)
919
+
920
+ assert asin(Rational(1, 7), evaluate=False).is_positive is True
921
+ assert asin(Rational(-1, 7), evaluate=False).is_positive is False
922
+ assert asin(p).is_positive is None
923
+ assert asin(sin(Rational(7, 2))) == Rational(-7, 2) + pi
924
+ assert asin(sin(Rational(-7, 4))) == Rational(7, 4) - pi
925
+ assert unchanged(asin, cos(x))
926
+
927
+
928
+ def test_asin_series():
929
+ assert asin(x).series(x, 0, 9) == \
930
+ x + x**3/6 + 3*x**5/40 + 5*x**7/112 + O(x**9)
931
+ t5 = asin(x).taylor_term(5, x)
932
+ assert t5 == 3*x**5/40
933
+ assert asin(x).taylor_term(7, x, t5, 0) == 5*x**7/112
934
+
935
+
936
+ def test_asin_leading_term():
937
+ assert asin(x).as_leading_term(x) == x
938
+ # Tests concerning branch points
939
+ assert asin(x + 1).as_leading_term(x) == pi/2
940
+ assert asin(x - 1).as_leading_term(x) == -pi/2
941
+ assert asin(1/x).as_leading_term(x, cdir=1) == I*log(x) + pi/2 - I*log(2)
942
+ assert asin(1/x).as_leading_term(x, cdir=-1) == -I*log(x) - 3*pi/2 + I*log(2)
943
+ # Tests concerning points lying on branch cuts
944
+ assert asin(I*x + 2).as_leading_term(x, cdir=1) == pi - asin(2)
945
+ assert asin(-I*x + 2).as_leading_term(x, cdir=1) == asin(2)
946
+ assert asin(I*x - 2).as_leading_term(x, cdir=1) == -asin(2)
947
+ assert asin(-I*x - 2).as_leading_term(x, cdir=1) == -pi + asin(2)
948
+ # Tests concerning im(ndir) == 0
949
+ assert asin(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == -pi/2 + I*log(2 - sqrt(3))
950
+ assert asin(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(2 - sqrt(3))
951
+
952
+
953
+ def test_asin_rewrite():
954
+ assert asin(x).rewrite(log) == -I*log(I*x + sqrt(1 - x**2))
955
+ assert asin(x).rewrite(atan) == 2*atan(x/(1 + sqrt(1 - x**2)))
956
+ assert asin(x).rewrite(acos) == S.Pi/2 - acos(x)
957
+ assert asin(x).rewrite(acot) == 2*acot((sqrt(-x**2 + 1) + 1)/x)
958
+ assert asin(x).rewrite(asec) == -asec(1/x) + pi/2
959
+ assert asin(x).rewrite(acsc) == acsc(1/x)
960
+
961
+
962
+ def test_asin_fdiff():
963
+ assert asin(x).fdiff() == 1/sqrt(1 - x**2)
964
+ raises(ArgumentIndexError, lambda: asin(x).fdiff(2))
965
+
966
+
967
+ def test_acos():
968
+ assert acos(nan) is nan
969
+ assert acos(zoo) is zoo
970
+
971
+ assert acos.nargs == FiniteSet(1)
972
+ assert acos(oo) == I*oo
973
+ assert acos(-oo) == -I*oo
974
+
975
+ # Note: acos(-x) = pi - acos(x)
976
+ assert acos(0) == pi/2
977
+ assert acos(S.Half) == pi/3
978
+ assert acos(Rational(-1, 2)) == pi*Rational(2, 3)
979
+ assert acos(1) == 0
980
+ assert acos(-1) == pi
981
+ assert acos(sqrt(2)/2) == pi/4
982
+ assert acos(-sqrt(2)/2) == pi*Rational(3, 4)
983
+
984
+ # check round-trip for exact values:
985
+ for d in [5, 6, 8, 10, 12]:
986
+ for num in range(d):
987
+ if gcd(num, d) == 1:
988
+ assert acos(cos(num*pi/d)) == num*pi/d
989
+
990
+ assert acos(2*I) == pi/2 - asin(2*I)
991
+
992
+ assert acos(x).diff(x) == -1/sqrt(1 - x**2)
993
+
994
+ assert acos(0.2).is_real is True
995
+ assert acos(-2).is_real is False
996
+ assert acos(r).is_real is None
997
+
998
+ assert acos(Rational(1, 7), evaluate=False).is_positive is True
999
+ assert acos(Rational(-1, 7), evaluate=False).is_positive is True
1000
+ assert acos(Rational(3, 2), evaluate=False).is_positive is False
1001
+ assert acos(p).is_positive is None
1002
+
1003
+ assert acos(2 + p).conjugate() != acos(10 + p)
1004
+ assert acos(-3 + n).conjugate() != acos(-3 + n)
1005
+ assert acos(Rational(1, 3)).conjugate() == acos(Rational(1, 3))
1006
+ assert acos(Rational(-1, 3)).conjugate() == acos(Rational(-1, 3))
1007
+ assert acos(p + n*I).conjugate() == acos(p - n*I)
1008
+ assert acos(z).conjugate() != acos(conjugate(z))
1009
+
1010
+
1011
+ def test_acos_leading_term():
1012
+ assert acos(x).as_leading_term(x) == pi/2
1013
+ # Tests concerning branch points
1014
+ assert acos(x + 1).as_leading_term(x) == sqrt(2)*sqrt(-x)
1015
+ assert acos(x - 1).as_leading_term(x) == pi
1016
+ assert acos(1/x).as_leading_term(x, cdir=1) == -I*log(x) + I*log(2)
1017
+ assert acos(1/x).as_leading_term(x, cdir=-1) == I*log(x) + 2*pi - I*log(2)
1018
+ # Tests concerning points lying on branch cuts
1019
+ assert acos(I*x + 2).as_leading_term(x, cdir=1) == -acos(2)
1020
+ assert acos(-I*x + 2).as_leading_term(x, cdir=1) == acos(2)
1021
+ assert acos(I*x - 2).as_leading_term(x, cdir=1) == acos(-2)
1022
+ assert acos(-I*x - 2).as_leading_term(x, cdir=1) == 2*pi - acos(-2)
1023
+ # Tests concerning im(ndir) == 0
1024
+ assert acos(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == pi + I*log(sqrt(3) + 2)
1025
+ assert acos(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == pi + I*log(sqrt(3) + 2)
1026
+
1027
+
1028
+ def test_acos_series():
1029
+ assert acos(x).series(x, 0, 8) == \
1030
+ pi/2 - x - x**3/6 - 3*x**5/40 - 5*x**7/112 + O(x**8)
1031
+ assert acos(x).series(x, 0, 8) == pi/2 - asin(x).series(x, 0, 8)
1032
+ t5 = acos(x).taylor_term(5, x)
1033
+ assert t5 == -3*x**5/40
1034
+ assert acos(x).taylor_term(7, x, t5, 0) == -5*x**7/112
1035
+ assert acos(x).taylor_term(0, x) == pi/2
1036
+ assert acos(x).taylor_term(2, x) is S.Zero
1037
+
1038
+
1039
+ def test_acos_rewrite():
1040
+ assert acos(x).rewrite(log) == pi/2 + I*log(I*x + sqrt(1 - x**2))
1041
+ assert acos(x).rewrite(atan) == pi*(-x*sqrt(x**(-2)) + 1)/2 + atan(sqrt(1 - x**2)/x)
1042
+ assert acos(0).rewrite(atan) == S.Pi/2
1043
+ assert acos(0.5).rewrite(atan) == acos(0.5).rewrite(log)
1044
+ assert acos(x).rewrite(asin) == S.Pi/2 - asin(x)
1045
+ assert acos(x).rewrite(acot) == -2*acot((sqrt(-x**2 + 1) + 1)/x) + pi/2
1046
+ assert acos(x).rewrite(asec) == asec(1/x)
1047
+ assert acos(x).rewrite(acsc) == -acsc(1/x) + pi/2
1048
+
1049
+
1050
+ def test_acos_fdiff():
1051
+ assert acos(x).fdiff() == -1/sqrt(1 - x**2)
1052
+ raises(ArgumentIndexError, lambda: acos(x).fdiff(2))
1053
+
1054
+
1055
+ def test_atan():
1056
+ assert atan(nan) is nan
1057
+
1058
+ assert atan.nargs == FiniteSet(1)
1059
+ assert atan(oo) == pi/2
1060
+ assert atan(-oo) == -pi/2
1061
+ assert atan(zoo) == AccumBounds(-pi/2, pi/2)
1062
+
1063
+ assert atan(0) == 0
1064
+ assert atan(1) == pi/4
1065
+ assert atan(sqrt(3)) == pi/3
1066
+ assert atan(-(1 + sqrt(2))) == pi*Rational(-3, 8)
1067
+ assert atan(sqrt(5 - 2 * sqrt(5))) == pi/5
1068
+ assert atan(-sqrt(1 - 2 * sqrt(5)/ 5)) == -pi/10
1069
+ assert atan(sqrt(1 + 2 * sqrt(5) / 5)) == pi*Rational(3, 10)
1070
+ assert atan(-2 + sqrt(3)) == -pi/12
1071
+ assert atan(2 + sqrt(3)) == pi*Rational(5, 12)
1072
+ assert atan(-2 - sqrt(3)) == pi*Rational(-5, 12)
1073
+
1074
+ # check round-trip for exact values:
1075
+ for d in [5, 6, 8, 10, 12]:
1076
+ for num in range(-(d//2), d//2 + 1):
1077
+ if gcd(num, d) == 1:
1078
+ assert atan(tan(num*pi/d)) == num*pi/d
1079
+
1080
+ assert atan(oo) == pi/2
1081
+ assert atan(x).diff(x) == 1/(1 + x**2)
1082
+
1083
+ assert atan(r).is_real is True
1084
+
1085
+ assert atan(-2*I) == -I*atanh(2)
1086
+ assert unchanged(atan, cot(x))
1087
+ assert atan(cot(Rational(1, 4))) == Rational(-1, 4) + pi/2
1088
+ assert acot(Rational(1, 4)).is_rational is False
1089
+
1090
+ for s in (x, p, n, np, nn, nz, ep, en, enp, enn, enz):
1091
+ if s.is_real or s.is_extended_real is None:
1092
+ assert s.is_nonzero is atan(s).is_nonzero
1093
+ assert s.is_positive is atan(s).is_positive
1094
+ assert s.is_negative is atan(s).is_negative
1095
+ assert s.is_nonpositive is atan(s).is_nonpositive
1096
+ assert s.is_nonnegative is atan(s).is_nonnegative
1097
+ else:
1098
+ assert s.is_extended_nonzero is atan(s).is_nonzero
1099
+ assert s.is_extended_positive is atan(s).is_positive
1100
+ assert s.is_extended_negative is atan(s).is_negative
1101
+ assert s.is_extended_nonpositive is atan(s).is_nonpositive
1102
+ assert s.is_extended_nonnegative is atan(s).is_nonnegative
1103
+ assert s.is_extended_nonzero is atan(s).is_extended_nonzero
1104
+ assert s.is_extended_positive is atan(s).is_extended_positive
1105
+ assert s.is_extended_negative is atan(s).is_extended_negative
1106
+ assert s.is_extended_nonpositive is atan(s).is_extended_nonpositive
1107
+ assert s.is_extended_nonnegative is atan(s).is_extended_nonnegative
1108
+
1109
+
1110
+ def test_atan_rewrite():
1111
+ assert atan(x).rewrite(log) == I*(log(1 - I*x)-log(1 + I*x))/2
1112
+ assert atan(x).rewrite(asin) == (-asin(1/sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x
1113
+ assert atan(x).rewrite(acos) == sqrt(x**2)*acos(1/sqrt(x**2 + 1))/x
1114
+ assert atan(x).rewrite(acot) == acot(1/x)
1115
+ assert atan(x).rewrite(asec) == sqrt(x**2)*asec(sqrt(x**2 + 1))/x
1116
+ assert atan(x).rewrite(acsc) == (-acsc(sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x
1117
+
1118
+ assert atan(-5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:-5*I})
1119
+ assert atan(5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:5*I})
1120
+
1121
+
1122
+ def test_atan_fdiff():
1123
+ assert atan(x).fdiff() == 1/(x**2 + 1)
1124
+ raises(ArgumentIndexError, lambda: atan(x).fdiff(2))
1125
+
1126
+
1127
+ def test_atan_leading_term():
1128
+ assert atan(x).as_leading_term(x) == x
1129
+ assert atan(1/x).as_leading_term(x, cdir=1) == pi/2
1130
+ assert atan(1/x).as_leading_term(x, cdir=-1) == -pi/2
1131
+ # Tests concerning branch points
1132
+ assert atan(x + I).as_leading_term(x, cdir=1) == -I*log(x)/2 + pi/4 + I*log(2)/2
1133
+ assert atan(x + I).as_leading_term(x, cdir=-1) == -I*log(x)/2 - 3*pi/4 + I*log(2)/2
1134
+ assert atan(x - I).as_leading_term(x, cdir=1) == I*log(x)/2 + pi/4 - I*log(2)/2
1135
+ assert atan(x - I).as_leading_term(x, cdir=-1) == I*log(x)/2 + pi/4 - I*log(2)/2
1136
+ # Tests concerning points lying on branch cuts
1137
+ assert atan(x + 2*I).as_leading_term(x, cdir=1) == I*atanh(2)
1138
+ assert atan(x + 2*I).as_leading_term(x, cdir=-1) == -pi + I*atanh(2)
1139
+ assert atan(x - 2*I).as_leading_term(x, cdir=1) == pi - I*atanh(2)
1140
+ assert atan(x - 2*I).as_leading_term(x, cdir=-1) == -I*atanh(2)
1141
+ # Tests concerning re(ndir) == 0
1142
+ assert atan(2*I - I*x - x**2).as_leading_term(x, cdir=1) == -pi/2 + I*log(3)/2
1143
+ assert atan(2*I - I*x - x**2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(3)/2
1144
+
1145
+
1146
+ def test_atan2():
1147
+ assert atan2.nargs == FiniteSet(2)
1148
+ assert atan2(0, 0) is S.NaN
1149
+ assert atan2(0, 1) == 0
1150
+ assert atan2(1, 1) == pi/4
1151
+ assert atan2(1, 0) == pi/2
1152
+ assert atan2(1, -1) == pi*Rational(3, 4)
1153
+ assert atan2(0, -1) == pi
1154
+ assert atan2(-1, -1) == pi*Rational(-3, 4)
1155
+ assert atan2(-1, 0) == -pi/2
1156
+ assert atan2(-1, 1) == -pi/4
1157
+ i = symbols('i', imaginary=True)
1158
+ r = symbols('r', real=True)
1159
+ eq = atan2(r, i)
1160
+ ans = -I*log((i + I*r)/sqrt(i**2 + r**2))
1161
+ reps = ((r, 2), (i, I))
1162
+ assert eq.subs(reps) == ans.subs(reps)
1163
+
1164
+ x = Symbol('x', negative=True)
1165
+ y = Symbol('y', negative=True)
1166
+ assert atan2(y, x) == atan(y/x) - pi
1167
+ y = Symbol('y', nonnegative=True)
1168
+ assert atan2(y, x) == atan(y/x) + pi
1169
+ y = Symbol('y')
1170
+ assert atan2(y, x) == atan2(y, x, evaluate=False)
1171
+
1172
+ u = Symbol("u", positive=True)
1173
+ assert atan2(0, u) == 0
1174
+ u = Symbol("u", negative=True)
1175
+ assert atan2(0, u) == pi
1176
+
1177
+ assert atan2(y, oo) == 0
1178
+ assert atan2(y, -oo)== 2*pi*Heaviside(re(y), S.Half) - pi
1179
+
1180
+ assert atan2(y, x).rewrite(log) == -I*log((x + I*y)/sqrt(x**2 + y**2))
1181
+ assert atan2(0, 0) is S.NaN
1182
+
1183
+ ex = atan2(y, x) - arg(x + I*y)
1184
+ assert ex.subs({x:2, y:3}).rewrite(arg) == 0
1185
+ assert ex.subs({x:2, y:3*I}).rewrite(arg) == -pi - I*log(sqrt(5)*I/5)
1186
+ assert ex.subs({x:2*I, y:3}).rewrite(arg) == -pi/2 - I*log(sqrt(5)*I)
1187
+ assert ex.subs({x:2*I, y:3*I}).rewrite(arg) == -pi + atan(Rational(2, 3)) + atan(Rational(3, 2))
1188
+ i = symbols('i', imaginary=True)
1189
+ r = symbols('r', real=True)
1190
+ e = atan2(i, r)
1191
+ rewrite = e.rewrite(arg)
1192
+ reps = {i: I, r: -2}
1193
+ assert rewrite == -I*log(abs(I*i + r)/sqrt(abs(i**2 + r**2))) + arg((I*i + r)/sqrt(i**2 + r**2))
1194
+ assert (e - rewrite).subs(reps).equals(0)
1195
+
1196
+ assert atan2(0, x).rewrite(atan) == Piecewise((pi, re(x) < 0),
1197
+ (0, Ne(x, 0)),
1198
+ (nan, True))
1199
+ assert atan2(0, r).rewrite(atan) == Piecewise((pi, r < 0), (0, Ne(r, 0)), (S.NaN, True))
1200
+ assert atan2(0, i),rewrite(atan) == 0
1201
+ assert atan2(0, r + i).rewrite(atan) == Piecewise((pi, r < 0), (0, True))
1202
+
1203
+ assert atan2(y, x).rewrite(atan) == Piecewise(
1204
+ (2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)),
1205
+ (pi, re(x) < 0),
1206
+ (0, (re(x) > 0) | Ne(im(x), 0)),
1207
+ (nan, True))
1208
+ assert conjugate(atan2(x, y)) == atan2(conjugate(x), conjugate(y))
1209
+
1210
+ assert diff(atan2(y, x), x) == -y/(x**2 + y**2)
1211
+ assert diff(atan2(y, x), y) == x/(x**2 + y**2)
1212
+
1213
+ assert simplify(diff(atan2(y, x).rewrite(log), x)) == -y/(x**2 + y**2)
1214
+ assert simplify(diff(atan2(y, x).rewrite(log), y)) == x/(x**2 + y**2)
1215
+
1216
+ assert str(atan2(1, 2).evalf(5)) == '0.46365'
1217
+ raises(ArgumentIndexError, lambda: atan2(x, y).fdiff(3))
1218
+
1219
+ def test_issue_17461():
1220
+ class A(Symbol):
1221
+ is_extended_real = True
1222
+
1223
+ def _eval_evalf(self, prec):
1224
+ return Float(5.0)
1225
+
1226
+ x = A('X')
1227
+ y = A('Y')
1228
+ assert abs(atan2(x, y).evalf() - 0.785398163397448) <= 1e-10
1229
+
1230
+ def test_acot():
1231
+ assert acot(nan) is nan
1232
+
1233
+ assert acot.nargs == FiniteSet(1)
1234
+ assert acot(-oo) == 0
1235
+ assert acot(oo) == 0
1236
+ assert acot(zoo) == 0
1237
+ assert acot(1) == pi/4
1238
+ assert acot(0) == pi/2
1239
+ assert acot(sqrt(3)/3) == pi/3
1240
+ assert acot(1/sqrt(3)) == pi/3
1241
+ assert acot(-1/sqrt(3)) == -pi/3
1242
+ assert acot(x).diff(x) == -1/(1 + x**2)
1243
+
1244
+ assert acot(r).is_extended_real is True
1245
+
1246
+ assert acot(I*pi) == -I*acoth(pi)
1247
+ assert acot(-2*I) == I*acoth(2)
1248
+ assert acot(x).is_positive is None
1249
+ assert acot(n).is_positive is False
1250
+ assert acot(p).is_positive is True
1251
+ assert acot(I).is_positive is False
1252
+ assert acot(Rational(1, 4)).is_rational is False
1253
+ assert unchanged(acot, cot(x))
1254
+ assert unchanged(acot, tan(x))
1255
+ assert acot(cot(Rational(1, 4))) == Rational(1, 4)
1256
+ assert acot(tan(Rational(-1, 4))) == Rational(1, 4) - pi/2
1257
+
1258
+
1259
+ def test_acot_rewrite():
1260
+ assert acot(x).rewrite(log) == I*(log(1 - I/x)-log(1 + I/x))/2
1261
+ assert acot(x).rewrite(asin) == x*(-asin(sqrt(-x**2)/sqrt(-x**2 - 1)) + pi/2)*sqrt(x**(-2))
1262
+ assert acot(x).rewrite(acos) == x*sqrt(x**(-2))*acos(sqrt(-x**2)/sqrt(-x**2 - 1))
1263
+ assert acot(x).rewrite(atan) == atan(1/x)
1264
+ assert acot(x).rewrite(asec) == x*sqrt(x**(-2))*asec(sqrt((x**2 + 1)/x**2))
1265
+ assert acot(x).rewrite(acsc) == x*(-acsc(sqrt((x**2 + 1)/x**2)) + pi/2)*sqrt(x**(-2))
1266
+
1267
+ assert acot(-I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:-I/5})
1268
+ assert acot(I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:I/5})
1269
+
1270
+
1271
+ def test_acot_fdiff():
1272
+ assert acot(x).fdiff() == -1/(x**2 + 1)
1273
+ raises(ArgumentIndexError, lambda: acot(x).fdiff(2))
1274
+
1275
+ def test_acot_leading_term():
1276
+ assert acot(1/x).as_leading_term(x) == x
1277
+ # Tests concerning branch points
1278
+ assert acot(x + I).as_leading_term(x, cdir=1) == I*log(x)/2 + pi/4 - I*log(2)/2
1279
+ assert acot(x + I).as_leading_term(x, cdir=-1) == I*log(x)/2 + pi/4 - I*log(2)/2
1280
+ assert acot(x - I).as_leading_term(x, cdir=1) == -I*log(x)/2 + pi/4 + I*log(2)/2
1281
+ assert acot(x - I).as_leading_term(x, cdir=-1) == -I*log(x)/2 - 3*pi/4 + I*log(2)/2
1282
+ # Tests concerning points lying on branch cuts
1283
+ assert acot(x).as_leading_term(x, cdir=1) == pi/2
1284
+ assert acot(x).as_leading_term(x, cdir=-1) == -pi/2
1285
+ assert acot(x + I/2).as_leading_term(x, cdir=1) == pi - I*acoth(S(1)/2)
1286
+ assert acot(x + I/2).as_leading_term(x, cdir=-1) == -I*acoth(S(1)/2)
1287
+ assert acot(x - I/2).as_leading_term(x, cdir=1) == I*acoth(S(1)/2)
1288
+ assert acot(x - I/2).as_leading_term(x, cdir=-1) == -pi + I*acoth(S(1)/2)
1289
+ # Tests concerning re(ndir) == 0
1290
+ assert acot(I/2 - I*x - x**2).as_leading_term(x, cdir=1) == -pi/2 - I*log(3)/2
1291
+ assert acot(I/2 - I*x - x**2).as_leading_term(x, cdir=-1) == -pi/2 - I*log(3)/2
1292
+
1293
+
1294
+ def test_attributes():
1295
+ assert sin(x).args == (x,)
1296
+
1297
+
1298
+ def test_sincos_rewrite():
1299
+ assert sin(pi/2 - x) == cos(x)
1300
+ assert sin(pi - x) == sin(x)
1301
+ assert cos(pi/2 - x) == sin(x)
1302
+ assert cos(pi - x) == -cos(x)
1303
+
1304
+
1305
+ def _check_even_rewrite(func, arg):
1306
+ """Checks that the expr has been rewritten using f(-x) -> f(x)
1307
+ arg : -x
1308
+ """
1309
+ return func(arg).args[0] == -arg
1310
+
1311
+
1312
+ def _check_odd_rewrite(func, arg):
1313
+ """Checks that the expr has been rewritten using f(-x) -> -f(x)
1314
+ arg : -x
1315
+ """
1316
+ return func(arg).func.is_Mul
1317
+
1318
+
1319
+ def _check_no_rewrite(func, arg):
1320
+ """Checks that the expr is not rewritten"""
1321
+ return func(arg).args[0] == arg
1322
+
1323
+
1324
+ def test_evenodd_rewrite():
1325
+ a = cos(2) # negative
1326
+ b = sin(1) # positive
1327
+ even = [cos]
1328
+ odd = [sin, tan, cot, asin, atan, acot]
1329
+ with_minus = [-1, -2**1024 * E, -pi/105, -x*y, -x - y]
1330
+ for func in even:
1331
+ for expr in with_minus:
1332
+ assert _check_even_rewrite(func, expr)
1333
+ assert _check_no_rewrite(func, a*b)
1334
+ assert func(
1335
+ x - y) == func(y - x) # it doesn't matter which form is canonical
1336
+ for func in odd:
1337
+ for expr in with_minus:
1338
+ assert _check_odd_rewrite(func, expr)
1339
+ assert _check_no_rewrite(func, a*b)
1340
+ assert func(
1341
+ x - y) == -func(y - x) # it doesn't matter which form is canonical
1342
+
1343
+
1344
+ def test_as_leading_term_issue_5272():
1345
+ assert sin(x).as_leading_term(x) == x
1346
+ assert cos(x).as_leading_term(x) == 1
1347
+ assert tan(x).as_leading_term(x) == x
1348
+ assert cot(x).as_leading_term(x) == 1/x
1349
+
1350
+
1351
+ def test_leading_terms():
1352
+ assert sin(1/x).as_leading_term(x) == AccumBounds(-1, 1)
1353
+ assert sin(S.Half).as_leading_term(x) == sin(S.Half)
1354
+ assert cos(1/x).as_leading_term(x) == AccumBounds(-1, 1)
1355
+ assert cos(S.Half).as_leading_term(x) == cos(S.Half)
1356
+ assert sec(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
1357
+ assert csc(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
1358
+ assert tan(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
1359
+ assert cot(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity)
1360
+
1361
+ # https://github.com/sympy/sympy/issues/21038
1362
+ f = sin(pi*(x + 4))/(3*x)
1363
+ assert f.as_leading_term(x) == pi/3
1364
+
1365
+
1366
+ def test_atan2_expansion():
1367
+ assert cancel(atan2(x**2, x + 1).diff(x) - atan(x**2/(x + 1)).diff(x)) == 0
1368
+ assert cancel(atan(y/x).series(y, 0, 5) - atan2(y, x).series(y, 0, 5)
1369
+ + atan2(0, x) - atan(0)) == O(y**5)
1370
+ assert cancel(atan(y/x).series(x, 1, 4) - atan2(y, x).series(x, 1, 4)
1371
+ + atan2(y, 1) - atan(y)) == O((x - 1)**4, (x, 1))
1372
+ assert cancel(atan((y + x)/x).series(x, 1, 3) - atan2(y + x, x).series(x, 1, 3)
1373
+ + atan2(1 + y, 1) - atan(1 + y)) == O((x - 1)**3, (x, 1))
1374
+ assert Matrix([atan2(y, x)]).jacobian([y, x]) == \
1375
+ Matrix([[x/(y**2 + x**2), -y/(y**2 + x**2)]])
1376
+
1377
+
1378
+ def test_aseries():
1379
+ def t(n, v, d, e):
1380
+ assert abs(
1381
+ n(1/v).evalf() - n(1/x).series(x, dir=d).removeO().subs(x, v)) < e
1382
+ t(atan, 0.1, '+', 1e-5)
1383
+ t(atan, -0.1, '-', 1e-5)
1384
+ t(acot, 0.1, '+', 1e-5)
1385
+ t(acot, -0.1, '-', 1e-5)
1386
+
1387
+
1388
+ def test_issue_4420():
1389
+ i = Symbol('i', integer=True)
1390
+ e = Symbol('e', even=True)
1391
+ o = Symbol('o', odd=True)
1392
+
1393
+ # unknown parity for variable
1394
+ assert cos(4*i*pi) == 1
1395
+ assert sin(4*i*pi) == 0
1396
+ assert tan(4*i*pi) == 0
1397
+ assert cot(4*i*pi) is zoo
1398
+
1399
+ assert cos(3*i*pi) == cos(pi*i) # +/-1
1400
+ assert sin(3*i*pi) == 0
1401
+ assert tan(3*i*pi) == 0
1402
+ assert cot(3*i*pi) is zoo
1403
+
1404
+ assert cos(4.0*i*pi) == 1
1405
+ assert sin(4.0*i*pi) == 0
1406
+ assert tan(4.0*i*pi) == 0
1407
+ assert cot(4.0*i*pi) is zoo
1408
+
1409
+ assert cos(3.0*i*pi) == cos(pi*i) # +/-1
1410
+ assert sin(3.0*i*pi) == 0
1411
+ assert tan(3.0*i*pi) == 0
1412
+ assert cot(3.0*i*pi) is zoo
1413
+
1414
+ assert cos(4.5*i*pi) == cos(0.5*pi*i)
1415
+ assert sin(4.5*i*pi) == sin(0.5*pi*i)
1416
+ assert tan(4.5*i*pi) == tan(0.5*pi*i)
1417
+ assert cot(4.5*i*pi) == cot(0.5*pi*i)
1418
+
1419
+ # parity of variable is known
1420
+ assert cos(4*e*pi) == 1
1421
+ assert sin(4*e*pi) == 0
1422
+ assert tan(4*e*pi) == 0
1423
+ assert cot(4*e*pi) is zoo
1424
+
1425
+ assert cos(3*e*pi) == 1
1426
+ assert sin(3*e*pi) == 0
1427
+ assert tan(3*e*pi) == 0
1428
+ assert cot(3*e*pi) is zoo
1429
+
1430
+ assert cos(4.0*e*pi) == 1
1431
+ assert sin(4.0*e*pi) == 0
1432
+ assert tan(4.0*e*pi) == 0
1433
+ assert cot(4.0*e*pi) is zoo
1434
+
1435
+ assert cos(3.0*e*pi) == 1
1436
+ assert sin(3.0*e*pi) == 0
1437
+ assert tan(3.0*e*pi) == 0
1438
+ assert cot(3.0*e*pi) is zoo
1439
+
1440
+ assert cos(4.5*e*pi) == cos(0.5*pi*e)
1441
+ assert sin(4.5*e*pi) == sin(0.5*pi*e)
1442
+ assert tan(4.5*e*pi) == tan(0.5*pi*e)
1443
+ assert cot(4.5*e*pi) == cot(0.5*pi*e)
1444
+
1445
+ assert cos(4*o*pi) == 1
1446
+ assert sin(4*o*pi) == 0
1447
+ assert tan(4*o*pi) == 0
1448
+ assert cot(4*o*pi) is zoo
1449
+
1450
+ assert cos(3*o*pi) == -1
1451
+ assert sin(3*o*pi) == 0
1452
+ assert tan(3*o*pi) == 0
1453
+ assert cot(3*o*pi) is zoo
1454
+
1455
+ assert cos(4.0*o*pi) == 1
1456
+ assert sin(4.0*o*pi) == 0
1457
+ assert tan(4.0*o*pi) == 0
1458
+ assert cot(4.0*o*pi) is zoo
1459
+
1460
+ assert cos(3.0*o*pi) == -1
1461
+ assert sin(3.0*o*pi) == 0
1462
+ assert tan(3.0*o*pi) == 0
1463
+ assert cot(3.0*o*pi) is zoo
1464
+
1465
+ assert cos(4.5*o*pi) == cos(0.5*pi*o)
1466
+ assert sin(4.5*o*pi) == sin(0.5*pi*o)
1467
+ assert tan(4.5*o*pi) == tan(0.5*pi*o)
1468
+ assert cot(4.5*o*pi) == cot(0.5*pi*o)
1469
+
1470
+ # x could be imaginary
1471
+ assert cos(4*x*pi) == cos(4*pi*x)
1472
+ assert sin(4*x*pi) == sin(4*pi*x)
1473
+ assert tan(4*x*pi) == tan(4*pi*x)
1474
+ assert cot(4*x*pi) == cot(4*pi*x)
1475
+
1476
+ assert cos(3*x*pi) == cos(3*pi*x)
1477
+ assert sin(3*x*pi) == sin(3*pi*x)
1478
+ assert tan(3*x*pi) == tan(3*pi*x)
1479
+ assert cot(3*x*pi) == cot(3*pi*x)
1480
+
1481
+ assert cos(4.0*x*pi) == cos(4.0*pi*x)
1482
+ assert sin(4.0*x*pi) == sin(4.0*pi*x)
1483
+ assert tan(4.0*x*pi) == tan(4.0*pi*x)
1484
+ assert cot(4.0*x*pi) == cot(4.0*pi*x)
1485
+
1486
+ assert cos(3.0*x*pi) == cos(3.0*pi*x)
1487
+ assert sin(3.0*x*pi) == sin(3.0*pi*x)
1488
+ assert tan(3.0*x*pi) == tan(3.0*pi*x)
1489
+ assert cot(3.0*x*pi) == cot(3.0*pi*x)
1490
+
1491
+ assert cos(4.5*x*pi) == cos(4.5*pi*x)
1492
+ assert sin(4.5*x*pi) == sin(4.5*pi*x)
1493
+ assert tan(4.5*x*pi) == tan(4.5*pi*x)
1494
+ assert cot(4.5*x*pi) == cot(4.5*pi*x)
1495
+
1496
+
1497
+ def test_inverses():
1498
+ raises(AttributeError, lambda: sin(x).inverse())
1499
+ raises(AttributeError, lambda: cos(x).inverse())
1500
+ assert tan(x).inverse() == atan
1501
+ assert cot(x).inverse() == acot
1502
+ raises(AttributeError, lambda: csc(x).inverse())
1503
+ raises(AttributeError, lambda: sec(x).inverse())
1504
+ assert asin(x).inverse() == sin
1505
+ assert acos(x).inverse() == cos
1506
+ assert atan(x).inverse() == tan
1507
+ assert acot(x).inverse() == cot
1508
+
1509
+
1510
+ def test_real_imag():
1511
+ a, b = symbols('a b', real=True)
1512
+ z = a + b*I
1513
+ for deep in [True, False]:
1514
+ assert sin(
1515
+ z).as_real_imag(deep=deep) == (sin(a)*cosh(b), cos(a)*sinh(b))
1516
+ assert cos(
1517
+ z).as_real_imag(deep=deep) == (cos(a)*cosh(b), -sin(a)*sinh(b))
1518
+ assert tan(z).as_real_imag(deep=deep) == (sin(2*a)/(cos(2*a) +
1519
+ cosh(2*b)), sinh(2*b)/(cos(2*a) + cosh(2*b)))
1520
+ assert cot(z).as_real_imag(deep=deep) == (-sin(2*a)/(cos(2*a) -
1521
+ cosh(2*b)), sinh(2*b)/(cos(2*a) - cosh(2*b)))
1522
+ assert sin(a).as_real_imag(deep=deep) == (sin(a), 0)
1523
+ assert cos(a).as_real_imag(deep=deep) == (cos(a), 0)
1524
+ assert tan(a).as_real_imag(deep=deep) == (tan(a), 0)
1525
+ assert cot(a).as_real_imag(deep=deep) == (cot(a), 0)
1526
+
1527
+
1528
+ @XFAIL
1529
+ def test_sin_cos_with_infinity():
1530
+ # Test for issue 5196
1531
+ # https://github.com/sympy/sympy/issues/5196
1532
+ assert sin(oo) is S.NaN
1533
+ assert cos(oo) is S.NaN
1534
+
1535
+
1536
+ @slow
1537
+ def test_sincos_rewrite_sqrt():
1538
+ # equivalent to testing rewrite(pow)
1539
+ for p in [1, 3, 5, 17]:
1540
+ for t in [1, 8]:
1541
+ n = t*p
1542
+ # The vertices `exp(i*pi/n)` of a regular `n`-gon can
1543
+ # be expressed by means of nested square roots if and
1544
+ # only if `n` is a product of Fermat primes, `p`, and
1545
+ # powers of 2, `t'. The code aims to check all vertices
1546
+ # not belonging to an `m`-gon for `m < n`(`gcd(i, n) == 1`).
1547
+ # For large `n` this makes the test too slow, therefore
1548
+ # the vertices are limited to those of index `i < 10`.
1549
+ for i in range(1, min((n + 1)//2 + 1, 10)):
1550
+ if 1 == gcd(i, n):
1551
+ x = i*pi/n
1552
+ s1 = sin(x).rewrite(sqrt)
1553
+ c1 = cos(x).rewrite(sqrt)
1554
+ assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
1555
+ assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n)
1556
+ assert 1e-3 > abs(sin(x.evalf(5)) - s1.evalf(2)), "fails for %d*pi/%d" % (i, n)
1557
+ assert 1e-3 > abs(cos(x.evalf(5)) - c1.evalf(2)), "fails for %d*pi/%d" % (i, n)
1558
+ assert cos(pi/14).rewrite(sqrt) == sqrt(cos(pi/7)/2 + S.Half)
1559
+ assert cos(pi*Rational(-15, 2)/11, evaluate=False).rewrite(
1560
+ sqrt) == -sqrt(-cos(pi*Rational(4, 11))/2 + S.Half)
1561
+ assert cos(Mul(2, pi, S.Half, evaluate=False), evaluate=False).rewrite(
1562
+ sqrt) == -1
1563
+ e = cos(pi/3/17) # don't use pi/15 since that is caught at instantiation
1564
+ a = (
1565
+ -3*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17) + 17)/64 -
1566
+ 3*sqrt(34)*sqrt(sqrt(17) + 17)/128 - sqrt(sqrt(17) +
1567
+ 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17)
1568
+ + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 - sqrt(-sqrt(17)
1569
+ + 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1570
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 - Rational(1, 32) +
1571
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1572
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 +
1573
+ 3*sqrt(2)*sqrt(sqrt(17) + 17)/128 + sqrt(34)*sqrt(-sqrt(17) + 17)/128
1574
+ + 13*sqrt(2)*sqrt(-sqrt(17) + 17)/128 + sqrt(17)*sqrt(-sqrt(17) +
1575
+ 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17)
1576
+ + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 + 5*sqrt(17)/32
1577
+ + sqrt(3)*sqrt(-sqrt(2)*sqrt(sqrt(17) + 17)*sqrt(sqrt(17)/32 +
1578
+ sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
1579
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1580
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/8 -
1581
+ 5*sqrt(2)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
1582
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1583
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
1584
+ Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1585
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 -
1586
+ 3*sqrt(2)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 +
1587
+ sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
1588
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1589
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/32
1590
+ + sqrt(34)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
1591
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1592
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
1593
+ Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1594
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 +
1595
+ sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
1596
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1597
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/2 +
1598
+ S.Half + sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) +
1599
+ 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) -
1600
+ sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) +
1601
+ 6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) -
1602
+ sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) +
1603
+ 6*sqrt(17) + 34)/32 + sqrt(34)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 +
1604
+ sqrt(2)*sqrt(-sqrt(17) + 17)/32 +
1605
+ sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) +
1606
+ 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 +
1607
+ Rational(15, 32))/32)/2)
1608
+ assert e.rewrite(sqrt) == a
1609
+ assert e.n() == a.n()
1610
+ # coverage of fermatCoords: multiplicity > 1; the following could be
1611
+ # different but that portion of the code should be tested in some way
1612
+ assert cos(pi/9/17).rewrite(sqrt) == \
1613
+ sin(pi/9)*sin(pi*Rational(2, 17)) + cos(pi/9)*cos(pi*Rational(2, 17))
1614
+
1615
+
1616
+ @slow
1617
+ def test_sincos_rewrite_sqrt_257():
1618
+ assert cos(pi/257).rewrite(sqrt).evalf(64) == cos(pi/257).evalf(64)
1619
+
1620
+
1621
+ @slow
1622
+ def test_tancot_rewrite_sqrt():
1623
+ # equivalent to testing rewrite(pow)
1624
+ for p in [1, 3, 5, 17]:
1625
+ for t in [1, 8]:
1626
+ n = t*p
1627
+ for i in range(1, min((n + 1)//2 + 1, 10)):
1628
+ if 1 == gcd(i, n):
1629
+ x = i*pi/n
1630
+ if 2*i != n and 3*i != 2*n:
1631
+ t1 = tan(x).rewrite(sqrt)
1632
+ assert not t1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
1633
+ assert 1e-3 > abs( tan(x.evalf(7)) - t1.evalf(4) ), "fails for %d*pi/%d" % (i, n)
1634
+ if i != 0 and i != n:
1635
+ c1 = cot(x).rewrite(sqrt)
1636
+ assert not c1.has(cot, tan), "fails for %d*pi/%d" % (i, n)
1637
+ assert 1e-3 > abs( cot(x.evalf(7)) - c1.evalf(4) ), "fails for %d*pi/%d" % (i, n)
1638
+
1639
+
1640
+ def test_sec():
1641
+ x = symbols('x', real=True)
1642
+ z = symbols('z')
1643
+
1644
+ assert sec.nargs == FiniteSet(1)
1645
+
1646
+ assert sec(zoo) is nan
1647
+ assert sec(0) == 1
1648
+ assert sec(pi) == -1
1649
+ assert sec(pi/2) is zoo
1650
+ assert sec(-pi/2) is zoo
1651
+ assert sec(pi/6) == 2*sqrt(3)/3
1652
+ assert sec(pi/3) == 2
1653
+ assert sec(pi*Rational(5, 2)) is zoo
1654
+ assert sec(pi*Rational(9, 7)) == -sec(pi*Rational(2, 7))
1655
+ assert sec(pi*Rational(3, 4)) == -sqrt(2) # issue 8421
1656
+ assert sec(I) == 1/cosh(1)
1657
+ assert sec(x*I) == 1/cosh(x)
1658
+ assert sec(-x) == sec(x)
1659
+
1660
+ assert sec(asec(x)) == x
1661
+
1662
+ assert sec(z).conjugate() == sec(conjugate(z))
1663
+
1664
+ assert (sec(z).as_real_imag() ==
1665
+ (cos(re(z))*cosh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
1666
+ cos(re(z))**2*cosh(im(z))**2),
1667
+ sin(re(z))*sinh(im(z))/(sin(re(z))**2*sinh(im(z))**2 +
1668
+ cos(re(z))**2*cosh(im(z))**2)))
1669
+
1670
+ assert sec(x).expand(trig=True) == 1/cos(x)
1671
+ assert sec(2*x).expand(trig=True) == 1/(2*cos(x)**2 - 1)
1672
+
1673
+ assert sec(x).is_extended_real == True
1674
+ assert sec(z).is_real == None
1675
+
1676
+ assert sec(a).is_algebraic is None
1677
+ assert sec(na).is_algebraic is False
1678
+
1679
+ assert sec(x).as_leading_term() == sec(x)
1680
+
1681
+ assert sec(0, evaluate=False).is_finite == True
1682
+ assert sec(x).is_finite == None
1683
+ assert sec(pi/2, evaluate=False).is_finite == False
1684
+
1685
+ assert series(sec(x), x, x0=0, n=6) == 1 + x**2/2 + 5*x**4/24 + O(x**6)
1686
+
1687
+ # https://github.com/sympy/sympy/issues/7166
1688
+ assert series(sqrt(sec(x))) == 1 + x**2/4 + 7*x**4/96 + O(x**6)
1689
+
1690
+ # https://github.com/sympy/sympy/issues/7167
1691
+ assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) ==
1692
+ 1/sqrt(x - pi*Rational(3, 2)) + (x - pi*Rational(3, 2))**Rational(3, 2)/12 +
1693
+ (x - pi*Rational(3, 2))**Rational(7, 2)/160 + O((x - pi*Rational(3, 2))**4, (x, pi*Rational(3, 2))))
1694
+
1695
+ assert sec(x).diff(x) == tan(x)*sec(x)
1696
+
1697
+ # Taylor Term checks
1698
+ assert sec(z).taylor_term(4, z) == 5*z**4/24
1699
+ assert sec(z).taylor_term(6, z) == 61*z**6/720
1700
+ assert sec(z).taylor_term(5, z) == 0
1701
+
1702
+
1703
+ def test_sec_rewrite():
1704
+ assert sec(x).rewrite(exp) == 1/(exp(I*x)/2 + exp(-I*x)/2)
1705
+ assert sec(x).rewrite(cos) == 1/cos(x)
1706
+ assert sec(x).rewrite(tan) == (tan(x/2)**2 + 1)/(-tan(x/2)**2 + 1)
1707
+ assert sec(x).rewrite(pow) == sec(x)
1708
+ assert sec(x).rewrite(sqrt) == sec(x)
1709
+ assert sec(z).rewrite(cot) == (cot(z/2)**2 + 1)/(cot(z/2)**2 - 1)
1710
+ assert sec(x).rewrite(sin) == 1 / sin(x + pi / 2, evaluate=False)
1711
+ assert sec(x).rewrite(tan) == (tan(x / 2)**2 + 1) / (-tan(x / 2)**2 + 1)
1712
+ assert sec(x).rewrite(csc) == csc(-x + pi/2, evaluate=False)
1713
+
1714
+
1715
+ def test_sec_fdiff():
1716
+ assert sec(x).fdiff() == tan(x)*sec(x)
1717
+ raises(ArgumentIndexError, lambda: sec(x).fdiff(2))
1718
+
1719
+
1720
+ def test_csc():
1721
+ x = symbols('x', real=True)
1722
+ z = symbols('z')
1723
+
1724
+ # https://github.com/sympy/sympy/issues/6707
1725
+ cosecant = csc('x')
1726
+ alternate = 1/sin('x')
1727
+ assert cosecant.equals(alternate) == True
1728
+ assert alternate.equals(cosecant) == True
1729
+
1730
+ assert csc.nargs == FiniteSet(1)
1731
+
1732
+ assert csc(0) is zoo
1733
+ assert csc(pi) is zoo
1734
+ assert csc(zoo) is nan
1735
+
1736
+ assert csc(pi/2) == 1
1737
+ assert csc(-pi/2) == -1
1738
+ assert csc(pi/6) == 2
1739
+ assert csc(pi/3) == 2*sqrt(3)/3
1740
+ assert csc(pi*Rational(5, 2)) == 1
1741
+ assert csc(pi*Rational(9, 7)) == -csc(pi*Rational(2, 7))
1742
+ assert csc(pi*Rational(3, 4)) == sqrt(2) # issue 8421
1743
+ assert csc(I) == -I/sinh(1)
1744
+ assert csc(x*I) == -I/sinh(x)
1745
+ assert csc(-x) == -csc(x)
1746
+
1747
+ assert csc(acsc(x)) == x
1748
+
1749
+ assert csc(z).conjugate() == csc(conjugate(z))
1750
+
1751
+ assert (csc(z).as_real_imag() ==
1752
+ (sin(re(z))*cosh(im(z))/(sin(re(z))**2*cosh(im(z))**2 +
1753
+ cos(re(z))**2*sinh(im(z))**2),
1754
+ -cos(re(z))*sinh(im(z))/(sin(re(z))**2*cosh(im(z))**2 +
1755
+ cos(re(z))**2*sinh(im(z))**2)))
1756
+
1757
+ assert csc(x).expand(trig=True) == 1/sin(x)
1758
+ assert csc(2*x).expand(trig=True) == 1/(2*sin(x)*cos(x))
1759
+
1760
+ assert csc(x).is_extended_real == True
1761
+ assert csc(z).is_real == None
1762
+
1763
+ assert csc(a).is_algebraic is None
1764
+ assert csc(na).is_algebraic is False
1765
+
1766
+ assert csc(x).as_leading_term() == csc(x)
1767
+
1768
+ assert csc(0, evaluate=False).is_finite == False
1769
+ assert csc(x).is_finite == None
1770
+ assert csc(pi/2, evaluate=False).is_finite == True
1771
+
1772
+ assert series(csc(x), x, x0=pi/2, n=6) == \
1773
+ 1 + (x - pi/2)**2/2 + 5*(x - pi/2)**4/24 + O((x - pi/2)**6, (x, pi/2))
1774
+ assert series(csc(x), x, x0=0, n=6) == \
1775
+ 1/x + x/6 + 7*x**3/360 + 31*x**5/15120 + O(x**6)
1776
+
1777
+ assert csc(x).diff(x) == -cot(x)*csc(x)
1778
+
1779
+ assert csc(x).taylor_term(2, x) == 0
1780
+ assert csc(x).taylor_term(3, x) == 7*x**3/360
1781
+ assert csc(x).taylor_term(5, x) == 31*x**5/15120
1782
+ raises(ArgumentIndexError, lambda: csc(x).fdiff(2))
1783
+
1784
+
1785
+ def test_asec():
1786
+ z = Symbol('z', zero=True)
1787
+ assert asec(z) is zoo
1788
+ assert asec(nan) is nan
1789
+ assert asec(1) == 0
1790
+ assert asec(-1) == pi
1791
+ assert asec(oo) == pi/2
1792
+ assert asec(-oo) == pi/2
1793
+ assert asec(zoo) == pi/2
1794
+
1795
+ assert asec(sec(pi*Rational(13, 4))) == pi*Rational(3, 4)
1796
+ assert asec(1 + sqrt(5)) == pi*Rational(2, 5)
1797
+ assert asec(2/sqrt(3)) == pi/6
1798
+ assert asec(sqrt(4 - 2*sqrt(2))) == pi/8
1799
+ assert asec(-sqrt(4 + 2*sqrt(2))) == pi*Rational(5, 8)
1800
+ assert asec(sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(3, 10)
1801
+ assert asec(-sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(7, 10)
1802
+ assert asec(sqrt(2) - sqrt(6)) == pi*Rational(11, 12)
1803
+
1804
+ assert asec(x).diff(x) == 1/(x**2*sqrt(1 - 1/x**2))
1805
+
1806
+ assert asec(x).rewrite(log) == I*log(sqrt(1 - 1/x**2) + I/x) + pi/2
1807
+ assert asec(x).rewrite(asin) == -asin(1/x) + pi/2
1808
+ assert asec(x).rewrite(acos) == acos(1/x)
1809
+ assert asec(x).rewrite(atan) == \
1810
+ pi*(1 - sqrt(x**2)/x)/2 + sqrt(x**2)*atan(sqrt(x**2 - 1))/x
1811
+ assert asec(x).rewrite(acot) == \
1812
+ pi*(1 - sqrt(x**2)/x)/2 + sqrt(x**2)*acot(1/sqrt(x**2 - 1))/x
1813
+ assert asec(x).rewrite(acsc) == -acsc(x) + pi/2
1814
+ raises(ArgumentIndexError, lambda: asec(x).fdiff(2))
1815
+
1816
+
1817
+ def test_asec_is_real():
1818
+ assert asec(S.Half).is_real is False
1819
+ n = Symbol('n', positive=True, integer=True)
1820
+ assert asec(n).is_extended_real is True
1821
+ assert asec(x).is_real is None
1822
+ assert asec(r).is_real is None
1823
+ t = Symbol('t', real=False, finite=True)
1824
+ assert asec(t).is_real is False
1825
+
1826
+
1827
+ def test_asec_leading_term():
1828
+ assert asec(1/x).as_leading_term(x) == pi/2
1829
+ # Tests concerning branch points
1830
+ assert asec(x + 1).as_leading_term(x) == sqrt(2)*sqrt(x)
1831
+ assert asec(x - 1).as_leading_term(x) == pi
1832
+ # Tests concerning points lying on branch cuts
1833
+ assert asec(x).as_leading_term(x, cdir=1) == -I*log(x) + I*log(2)
1834
+ assert asec(x).as_leading_term(x, cdir=-1) == I*log(x) + 2*pi - I*log(2)
1835
+ assert asec(I*x + 1/2).as_leading_term(x, cdir=1) == asec(1/2)
1836
+ assert asec(-I*x + 1/2).as_leading_term(x, cdir=1) == -asec(1/2)
1837
+ assert asec(I*x - 1/2).as_leading_term(x, cdir=1) == 2*pi - asec(-1/2)
1838
+ assert asec(-I*x - 1/2).as_leading_term(x, cdir=1) == asec(-1/2)
1839
+ # Tests concerning im(ndir) == 0
1840
+ assert asec(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=1) == pi + I*log(2 - sqrt(3))
1841
+ assert asec(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=-1) == pi + I*log(2 - sqrt(3))
1842
+
1843
+
1844
+ def test_asec_series():
1845
+ assert asec(x).series(x, 0, 9) == \
1846
+ I*log(2) - I*log(x) - I*x**2/4 - 3*I*x**4/32 \
1847
+ - 5*I*x**6/96 - 35*I*x**8/1024 + O(x**9)
1848
+ t4 = asec(x).taylor_term(4, x)
1849
+ assert t4 == -3*I*x**4/32
1850
+ assert asec(x).taylor_term(6, x, t4, 0) == -5*I*x**6/96
1851
+
1852
+
1853
+ def test_acsc():
1854
+ assert acsc(nan) is nan
1855
+ assert acsc(1) == pi/2
1856
+ assert acsc(-1) == -pi/2
1857
+ assert acsc(oo) == 0
1858
+ assert acsc(-oo) == 0
1859
+ assert acsc(zoo) == 0
1860
+ assert acsc(0) is zoo
1861
+
1862
+ assert acsc(csc(3)) == -3 + pi
1863
+ assert acsc(csc(4)) == -4 + pi
1864
+ assert acsc(csc(6)) == 6 - 2*pi
1865
+ assert unchanged(acsc, csc(x))
1866
+ assert unchanged(acsc, sec(x))
1867
+
1868
+ assert acsc(2/sqrt(3)) == pi/3
1869
+ assert acsc(csc(pi*Rational(13, 4))) == -pi/4
1870
+ assert acsc(sqrt(2 + 2*sqrt(5)/5)) == pi/5
1871
+ assert acsc(-sqrt(2 + 2*sqrt(5)/5)) == -pi/5
1872
+ assert acsc(-2) == -pi/6
1873
+ assert acsc(-sqrt(4 + 2*sqrt(2))) == -pi/8
1874
+ assert acsc(sqrt(4 - 2*sqrt(2))) == pi*Rational(3, 8)
1875
+ assert acsc(1 + sqrt(5)) == pi/10
1876
+ assert acsc(sqrt(2) - sqrt(6)) == pi*Rational(-5, 12)
1877
+
1878
+ assert acsc(x).diff(x) == -1/(x**2*sqrt(1 - 1/x**2))
1879
+
1880
+ assert acsc(x).rewrite(log) == -I*log(sqrt(1 - 1/x**2) + I/x)
1881
+ assert acsc(x).rewrite(asin) == asin(1/x)
1882
+ assert acsc(x).rewrite(acos) == -acos(1/x) + pi/2
1883
+ assert acsc(x).rewrite(atan) == \
1884
+ (-atan(sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x
1885
+ assert acsc(x).rewrite(acot) == (-acot(1/sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x
1886
+ assert acsc(x).rewrite(asec) == -asec(x) + pi/2
1887
+ raises(ArgumentIndexError, lambda: acsc(x).fdiff(2))
1888
+
1889
+
1890
+ def test_csc_rewrite():
1891
+ assert csc(x).rewrite(pow) == csc(x)
1892
+ assert csc(x).rewrite(sqrt) == csc(x)
1893
+
1894
+ assert csc(x).rewrite(exp) == 2*I/(exp(I*x) - exp(-I*x))
1895
+ assert csc(x).rewrite(sin) == 1/sin(x)
1896
+ assert csc(x).rewrite(tan) == (tan(x/2)**2 + 1)/(2*tan(x/2))
1897
+ assert csc(x).rewrite(cot) == (cot(x/2)**2 + 1)/(2*cot(x/2))
1898
+ assert csc(x).rewrite(cos) == 1/cos(x - pi/2, evaluate=False)
1899
+ assert csc(x).rewrite(sec) == sec(-x + pi/2, evaluate=False)
1900
+
1901
+ # issue 17349
1902
+ assert csc(1 - exp(-besselj(I, I))).rewrite(cos) == \
1903
+ -1/cos(-pi/2 - 1 + cos(I*besselj(I, I)) +
1904
+ I*cos(-pi/2 + I*besselj(I, I), evaluate=False), evaluate=False)
1905
+
1906
+
1907
+ def test_acsc_leading_term():
1908
+ assert acsc(1/x).as_leading_term(x) == x
1909
+ # Tests concerning branch points
1910
+ assert acsc(x + 1).as_leading_term(x) == pi/2
1911
+ assert acsc(x - 1).as_leading_term(x) == -pi/2
1912
+ # Tests concerning points lying on branch cuts
1913
+ assert acsc(x).as_leading_term(x, cdir=1) == I*log(x) + pi/2 - I*log(2)
1914
+ assert acsc(x).as_leading_term(x, cdir=-1) == -I*log(x) - 3*pi/2 + I*log(2)
1915
+ assert acsc(I*x + 1/2).as_leading_term(x, cdir=1) == acsc(1/2)
1916
+ assert acsc(-I*x + 1/2).as_leading_term(x, cdir=1) == pi - acsc(1/2)
1917
+ assert acsc(I*x - 1/2).as_leading_term(x, cdir=1) == -pi - acsc(-1/2)
1918
+ assert acsc(-I*x - 1/2).as_leading_term(x, cdir=1) == -acsc(1/2)
1919
+ # Tests concerning im(ndir) == 0
1920
+ assert acsc(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=1) == -pi/2 + I*log(sqrt(3) + 2)
1921
+ assert acsc(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(sqrt(3) + 2)
1922
+
1923
+
1924
+ def test_acsc_series():
1925
+ assert acsc(x).series(x, 0, 9) == \
1926
+ -I*log(2) + pi/2 + I*log(x) + I*x**2/4 \
1927
+ + 3*I*x**4/32 + 5*I*x**6/96 + 35*I*x**8/1024 + O(x**9)
1928
+ t6 = acsc(x).taylor_term(6, x)
1929
+ assert t6 == 5*I*x**6/96
1930
+ assert acsc(x).taylor_term(8, x, t6, 0) == 35*I*x**8/1024
1931
+
1932
+
1933
+ def test_asin_nseries():
1934
+ assert asin(x + 2)._eval_nseries(x, 4, None, I) == -asin(2) + pi + \
1935
+ sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
1936
+ assert asin(x + 2)._eval_nseries(x, 4, None, -I) == asin(2) - \
1937
+ sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
1938
+ assert asin(x - 2)._eval_nseries(x, 4, None, I) == -asin(2) - \
1939
+ sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
1940
+ assert asin(x - 2)._eval_nseries(x, 4, None, -I) == asin(2) - pi + \
1941
+ sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
1942
+ # testing nseries for asin at branch points
1943
+ assert asin(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) - \
1944
+ sqrt(2)*(-x)**(S(3)/2)/12 - 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
1945
+ assert asin(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) + \
1946
+ sqrt(2)*x**(S(3)/2)/12 + 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
1947
+ assert asin(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) + \
1948
+ sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
1949
+ assert asin(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - \
1950
+ sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
1951
+
1952
+
1953
+ def test_acos_nseries():
1954
+ assert acos(x + 2)._eval_nseries(x, 4, None, I) == -acos(2) - sqrt(3)*I*x/3 + \
1955
+ sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
1956
+ assert acos(x + 2)._eval_nseries(x, 4, None, -I) == acos(2) + sqrt(3)*I*x/3 - \
1957
+ sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
1958
+ assert acos(x - 2)._eval_nseries(x, 4, None, I) == acos(-2) + sqrt(3)*I*x/3 + \
1959
+ sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
1960
+ assert acos(x - 2)._eval_nseries(x, 4, None, -I) == -acos(-2) + 2*pi - \
1961
+ sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
1962
+ # testing nseries for acos at branch points
1963
+ assert acos(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) + \
1964
+ sqrt(2)*(-x)**(S(3)/2)/12 + 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
1965
+ assert acos(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) - \
1966
+ sqrt(2)*x**(S(3)/2)/12 - 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
1967
+ assert acos(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) - \
1968
+ sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
1969
+ assert acos(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + \
1970
+ sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3)
1971
+
1972
+
1973
+ def test_atan_nseries():
1974
+ assert atan(x + 2*I)._eval_nseries(x, 4, None, 1) == I*atanh(2) - x/3 - \
1975
+ 2*I*x**2/9 + 13*x**3/81 + O(x**4)
1976
+ assert atan(x + 2*I)._eval_nseries(x, 4, None, -1) == I*atanh(2) - pi - \
1977
+ x/3 - 2*I*x**2/9 + 13*x**3/81 + O(x**4)
1978
+ assert atan(x - 2*I)._eval_nseries(x, 4, None, 1) == -I*atanh(2) + pi - \
1979
+ x/3 + 2*I*x**2/9 + 13*x**3/81 + O(x**4)
1980
+ assert atan(x - 2*I)._eval_nseries(x, 4, None, -1) == -I*atanh(2) - x/3 + \
1981
+ 2*I*x**2/9 + 13*x**3/81 + O(x**4)
1982
+ assert atan(1/x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2)
1983
+ assert atan(1/x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2)
1984
+ # testing nseries for atan at branch points
1985
+ assert atan(x + I)._eval_nseries(x, 4, None) == I*log(2)/2 + pi/4 - \
1986
+ I*log(x)/2 + x/4 + I*x**2/16 - x**3/48 + O(x**4)
1987
+ assert atan(x - I)._eval_nseries(x, 4, None) == -I*log(2)/2 + pi/4 + \
1988
+ I*log(x)/2 + x/4 - I*x**2/16 - x**3/48 + O(x**4)
1989
+
1990
+
1991
+ def test_acot_nseries():
1992
+ assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, 1) == -I*acoth(S(1)/2) + \
1993
+ pi - 4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4)
1994
+ assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, -1) == -I*acoth(S(1)/2) - \
1995
+ 4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4)
1996
+ assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, 1) == I*acoth(S(1)/2) - \
1997
+ 4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4)
1998
+ assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, -1) == I*acoth(S(1)/2) - \
1999
+ pi - 4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4)
2000
+ assert acot(x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2)
2001
+ assert acot(x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2)
2002
+ # testing nseries for acot at branch points
2003
+ assert acot(x + I)._eval_nseries(x, 4, None) == -I*log(2)/2 + pi/4 + \
2004
+ I*log(x)/2 - x/4 - I*x**2/16 + x**3/48 + O(x**4)
2005
+ assert acot(x - I)._eval_nseries(x, 4, None) == I*log(2)/2 + pi/4 - \
2006
+ I*log(x)/2 - x/4 + I*x**2/16 + x**3/48 + O(x**4)
2007
+
2008
+
2009
+ def test_asec_nseries():
2010
+ assert asec(x + S(1)/2)._eval_nseries(x, 4, None, I) == asec(S(1)/2) - \
2011
+ 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
2012
+ assert asec(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -asec(S(1)/2) + \
2013
+ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
2014
+ assert asec(x - S(1)/2)._eval_nseries(x, 4, None, I) == -asec(-S(1)/2) + \
2015
+ 2*pi + 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
2016
+ assert asec(x - S(1)/2)._eval_nseries(x, 4, None, -I) == asec(-S(1)/2) - \
2017
+ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
2018
+ # testing nseries for asec at branch points
2019
+ assert asec(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - \
2020
+ 5*sqrt(2)*x**(S(3)/2)/12 + 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
2021
+ assert asec(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + \
2022
+ 5*sqrt(2)*(-x)**(S(3)/2)/12 - 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
2023
+ assert asec(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - \
2024
+ sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3)
2025
+ assert asec(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) + \
2026
+ sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3)
2027
+
2028
+
2029
+ def test_acsc_nseries():
2030
+ assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/2) + \
2031
+ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
2032
+ assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/2) + \
2033
+ pi - 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
2034
+ assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/2) - pi -\
2035
+ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
2036
+ assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/2) + \
2037
+ 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
2038
+ # testing nseries for acsc at branch points
2039
+ assert acsc(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + \
2040
+ 5*sqrt(2)*x**(S(3)/2)/12 - 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3)
2041
+ assert acsc(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - \
2042
+ 5*sqrt(2)*(-x)**(S(3)/2)/12 + 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3)
2043
+ assert acsc(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + \
2044
+ sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3)
2045
+ assert acsc(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) - \
2046
+ sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3)
2047
+
2048
+
2049
+ def test_issue_8653():
2050
+ n = Symbol('n', integer=True)
2051
+ assert sin(n).is_irrational is None
2052
+ assert cos(n).is_irrational is None
2053
+ assert tan(n).is_irrational is None
2054
+
2055
+
2056
+ def test_issue_9157():
2057
+ n = Symbol('n', integer=True, positive=True)
2058
+ assert atan(n - 1).is_nonnegative is True
2059
+
2060
+
2061
+ def test_trig_period():
2062
+ x, y = symbols('x, y')
2063
+
2064
+ assert sin(x).period() == 2*pi
2065
+ assert cos(x).period() == 2*pi
2066
+ assert tan(x).period() == pi
2067
+ assert cot(x).period() == pi
2068
+ assert sec(x).period() == 2*pi
2069
+ assert csc(x).period() == 2*pi
2070
+ assert sin(2*x).period() == pi
2071
+ assert cot(4*x - 6).period() == pi/4
2072
+ assert cos((-3)*x).period() == pi*Rational(2, 3)
2073
+ assert cos(x*y).period(x) == 2*pi/abs(y)
2074
+ assert sin(3*x*y + 2*pi).period(y) == 2*pi/abs(3*x)
2075
+ assert tan(3*x).period(y) is S.Zero
2076
+ raises(NotImplementedError, lambda: sin(x**2).period(x))
2077
+
2078
+
2079
+ def test_issue_7171():
2080
+ assert sin(x).rewrite(sqrt) == sin(x)
2081
+ assert sin(x).rewrite(pow) == sin(x)
2082
+
2083
+
2084
+ def test_issue_11864():
2085
+ w, k = symbols('w, k', real=True)
2086
+ F = Piecewise((1, Eq(2*pi*k, 0)), (sin(pi*k)/(pi*k), True))
2087
+ soln = Piecewise((1, Eq(2*pi*k, 0)), (sinc(pi*k), True))
2088
+ assert F.rewrite(sinc) == soln
2089
+
2090
+ def test_real_assumptions():
2091
+ z = Symbol('z', real=False, finite=True)
2092
+ assert sin(z).is_real is None
2093
+ assert cos(z).is_real is None
2094
+ assert tan(z).is_real is False
2095
+ assert sec(z).is_real is None
2096
+ assert csc(z).is_real is None
2097
+ assert cot(z).is_real is False
2098
+ assert asin(p).is_real is None
2099
+ assert asin(n).is_real is None
2100
+ assert asec(p).is_real is None
2101
+ assert asec(n).is_real is None
2102
+ assert acos(p).is_real is None
2103
+ assert acos(n).is_real is None
2104
+ assert acsc(p).is_real is None
2105
+ assert acsc(n).is_real is None
2106
+ assert atan(p).is_positive is True
2107
+ assert atan(n).is_negative is True
2108
+ assert acot(p).is_positive is True
2109
+ assert acot(n).is_negative is True
2110
+
2111
+ def test_issue_14320():
2112
+ assert asin(sin(2)) == -2 + pi and (-pi/2 <= -2 + pi <= pi/2) and sin(2) == sin(-2 + pi)
2113
+ assert asin(cos(2)) == -2 + pi/2 and (-pi/2 <= -2 + pi/2 <= pi/2) and cos(2) == sin(-2 + pi/2)
2114
+ assert acos(sin(2)) == -pi/2 + 2 and (0 <= -pi/2 + 2 <= pi) and sin(2) == cos(-pi/2 + 2)
2115
+ assert acos(cos(20)) == -6*pi + 20 and (0 <= -6*pi + 20 <= pi) and cos(20) == cos(-6*pi + 20)
2116
+ assert acos(cos(30)) == -30 + 10*pi and (0 <= -30 + 10*pi <= pi) and cos(30) == cos(-30 + 10*pi)
2117
+
2118
+ assert atan(tan(17)) == -5*pi + 17 and (-pi/2 < -5*pi + 17 < pi/2) and tan(17) == tan(-5*pi + 17)
2119
+ assert atan(tan(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 < pi/2) and tan(15) == tan(-5*pi + 15)
2120
+ assert atan(cot(12)) == -12 + pi*Rational(7, 2) and (-pi/2 < -12 + pi*Rational(7, 2) < pi/2) and cot(12) == tan(-12 + pi*Rational(7, 2))
2121
+ assert acot(cot(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 <= pi/2) and cot(15) == cot(-5*pi + 15)
2122
+ assert acot(tan(19)) == -19 + pi*Rational(13, 2) and (-pi/2 < -19 + pi*Rational(13, 2) <= pi/2) and tan(19) == cot(-19 + pi*Rational(13, 2))
2123
+
2124
+ assert asec(sec(11)) == -11 + 4*pi and (0 <= -11 + 4*pi <= pi) and cos(11) == cos(-11 + 4*pi)
2125
+ assert asec(csc(13)) == -13 + pi*Rational(9, 2) and (0 <= -13 + pi*Rational(9, 2) <= pi) and sin(13) == cos(-13 + pi*Rational(9, 2))
2126
+ assert acsc(csc(14)) == -4*pi + 14 and (-pi/2 <= -4*pi + 14 <= pi/2) and sin(14) == sin(-4*pi + 14)
2127
+ assert acsc(sec(10)) == pi*Rational(-7, 2) + 10 and (-pi/2 <= pi*Rational(-7, 2) + 10 <= pi/2) and cos(10) == sin(pi*Rational(-7, 2) + 10)
2128
+
2129
+ def test_issue_14543():
2130
+ assert sec(2*pi + 11) == sec(11)
2131
+ assert sec(2*pi - 11) == sec(11)
2132
+ assert sec(pi + 11) == -sec(11)
2133
+ assert sec(pi - 11) == -sec(11)
2134
+
2135
+ assert csc(2*pi + 17) == csc(17)
2136
+ assert csc(2*pi - 17) == -csc(17)
2137
+ assert csc(pi + 17) == -csc(17)
2138
+ assert csc(pi - 17) == csc(17)
2139
+
2140
+ x = Symbol('x')
2141
+ assert csc(pi/2 + x) == sec(x)
2142
+ assert csc(pi/2 - x) == sec(x)
2143
+ assert csc(pi*Rational(3, 2) + x) == -sec(x)
2144
+ assert csc(pi*Rational(3, 2) - x) == -sec(x)
2145
+
2146
+ assert sec(pi/2 - x) == csc(x)
2147
+ assert sec(pi/2 + x) == -csc(x)
2148
+ assert sec(pi*Rational(3, 2) + x) == csc(x)
2149
+ assert sec(pi*Rational(3, 2) - x) == -csc(x)
2150
+
2151
+
2152
+ def test_as_real_imag():
2153
+ # This is for https://github.com/sympy/sympy/issues/17142
2154
+ # If it start failing again in irrelevant builds or in the master
2155
+ # please open up the issue again.
2156
+ expr = atan(I/(I + I*tan(1)))
2157
+ assert expr.as_real_imag() == (expr, 0)
2158
+
2159
+
2160
+ def test_issue_18746():
2161
+ e3 = cos(S.Pi*(x/4 + 1/4))
2162
+ assert e3.period() == 8
llmeval-env/lib/python3.10/site-packages/sympy/functions/special/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Stub __init__.py for the sympy.functions.special package
llmeval-env/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
llmeval-env/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)
llmeval-env/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)
llmeval-env/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.'''))
llmeval-env/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))
llmeval-env/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)
llmeval-env/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
llmeval-env/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)
llmeval-env/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)
llmeval-env/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())
llmeval-env/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